branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
sequencelengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<file_sep>#!/bin/bash # Download and install netkit-ng in home directory # <NAME>: 11 Oct 2017 cd ~ wget https://github.com/netkit-ng/netkit-ng-core/releases/download/3.0.4/netkit-ng-core-32-3.0.4.tar.bz2 wget https://github.com/netkit-ng/netkit-ng-build/releases/download/0.1.3/netkit-ng-kernel-i386-K3.2-0.1.3.tar.bz2 wget https://github.com/netkit-ng/netkit-ng-build/releases/download/0.1.3/netkit-ng-filesystem-i386-F7.0-0.1.3.tar.bz2 for i in netkit-ng*.tar.bz2; do tar -xvjSf $i; done cat >> ~/.bashrc <<EOF # additions for netkit-ng export NETKIT_HOME="$HOME/netkit-ng" export MANPATH=":\$NETKIT_HOME/man" export PATH="\$PATH:\$NETKIT_HOME/bin" EOF sudo apt-get update && sudo apt-get install libc6-i386 wireshark echo $(source ~/.bashrc && cd $NETKIT_HOME && ./check_configuration.sh)
c2e9d92e0c1a1a5d0705bbf7c5f756781cdac5ce
[ "Shell" ]
1
Shell
john2296/Crypto-PMA
1e11ac9379b942a0ffe0b9a856631ee91da665e2
5a73ad212e3495e91e0a8b482468b6a64c8e22dd
refs/heads/master
<file_sep>#include "enemyShot.h" #include "enemyBarrageManager.h" namespace { static const double PI = 3.1415926535898; static const double PI2 = 3.1415926535898 * 2; double rang(double, float _ang) { return (-_ang + _ang * 2 * GetRand(10000) / 10000.0); } } EnemyShot::EnemyShot(SceneBase* _scene, Vector2 _pos, int _maxbullet, int _barrageKind, int _bulletKind, int _bulletColor) : GameObject(_scene) { base_position = _pos; bulletMax = _maxbullet; pattern = _barrageKind; bulletKind = _bulletKind; bulletColor = _bulletColor; speed = 3; coolTime = 0; first = true; eBM = GetScene()->FindGameObject<EnemyBarrageManager>(); pl = GetScene()->FindGameObject<Player>(); plPos = pl->GetPosition(); } EnemyShot::~EnemyShot() { } void EnemyShot::Update() { switch (pattern) { case 0: ShotPattern_0(); break; case 1: ShotPattern_1(); break; case 2: ShotPattern_2(); break; case 3: ShotPattern_3(); break; case 4: ShotPattern_4(); break; default:break; } if (first == true) { for (int i = 0; i < bulletMax; i++) { eBM->Create(base_position, base_angle, bulletMax, bulletKind, bulletColor, speed); } first = false; } } void EnemyShot::Draw() { } void EnemyShot::ShotPattern_0() { //拡散弾 for (int i = 0; i < bulletMax; i++) { base_angle = (360 / bulletMax) * i * (DX_PI / 180); //eBM->Create(base_position, base_angle, bulletMax, bulletKind, bulletColor, speed); } } void EnemyShot::ShotPattern_1() { //ホーミング base_angle = Shotatan2(base_position); } void EnemyShot::ShotPattern_2() { } void EnemyShot::ShotPattern_3() { } void EnemyShot::ShotPattern_4() { } double EnemyShot::Shotatan2(Vector2 _position) { return atan2((float)plPos.y - _position.y, (float)plPos.x - _position.x); } double EnemyShot::Rang(double ang) { return (-ang + ang * 2 * GetRand(10000) / 10000.0); } void EnemyShot::Create() { } <file_sep>#include "shotManager.h" ShotManager::ShotManager(SceneBase * _scene) : GameObject (_scene) { shots.clear(); } ShotManager::~ShotManager() { for (auto it = shots.begin(); it != shots.end();) { delete (*it); it = shots.erase(it); } shots.clear(); } void ShotManager::Update() { for (auto it = shots.begin(); it != shots.end();) { (*it)->Update(); if ((*it)->IsDestroy()) { delete(*it); it = shots.erase(it); } else it++; } for (auto& s : shots) { s->Update(); } } void ShotManager::Draw() { for (auto& s : shots) { s->Draw(); } } void ShotManager::Spawn(Vector2 _pos) { ShotBase* s = new ShotBase(GetScene(), _pos); if (s != nullptr) shots.emplace_back(s); } <file_sep>#pragma once #include "../Library/sceneBase.h" class PlayScene : public SceneBase { public: PlayScene(); ~PlayScene(); void Update() override; void Draw() override; bool CanMove() const; void Clear(); void GameOver(); private: enum STATE { BEFORE_PLAY, IN_PLAY, CLEAR, GAMEOVER, }; STATE state; int counter; int hImage; int bgmSound; static int mStartTime; //測定開始時刻 static int mCount; //カウンタ static float mFps; //fps static const int N = 60; //平均を取るサンプル数 static const int FPS = 60; //設定したFPS };<file_sep>#pragma once #include "..//Library/gameObject.h" #include "vector2.h" #include "enemyBarrage.h" #include "enemyBarrageManager.h" #include "player.h" class EnemyShot : public GameObject { public: EnemyShot(SceneBase* _scene, Vector2 _pos, int _maxbullet, int _barrageKind, int _bulletKind, int _bulletColor); ~EnemyShot(); void Update(); void Draw(); void ShotPattern_0(); void ShotPattern_1(); void ShotPattern_2(); void ShotPattern_3(); void ShotPattern_4(); double Shotatan2(Vector2 _position); double Rang(double ang); void Create(); private: Vector2 base_position; double base_angle; int pattern; int cnt; int bulletMax; int bulletKind; int bulletColor; int interval; float coolTime; float speed; bool first; Vector2 plPos; EnemyBarrageManager* eBM; Player* pl; };<file_sep>#include "vShaped_MINIONS.h" #include <assert.h> namespace { static const int CENTER_X = 20; static const int CENTER_Y = 20; static const int WIDTH = 40; static const int HEIGHT = 40; static const int RADIUS = 20; } VShaped_MINIONS::VShaped_MINIONS(SceneBase* scene, int _x, int _y, int _cnt, int _pattern, float _speed, int _barrageTime, int _maxBullet, int _barrageKind, int _color, int _hp, int _bulletKind, int _waitTime, int _stagnationTime, int _itemKind, EnemyBase* _boss) : EnemyBase(scene) { position = Vector2(_x, _y); hImage = LoadGraph("data\\texture\\furball.png"); assert(hImage > 0); cnt = _cnt; pattern = _pattern; speed = _speed; barrageTime = _barrageTime; maxBullet = _maxBullet; barrageKind = _barrageKind; color = _color; hp = _hp; bulletKind = _bulletKind; waitTime = _waitTime; stagnationTime = _stagnationTime; itemKind = _itemKind; shotFlag = false; specialAttack = false; itM = GetScene()->FindGameObject<ItemManager>(); efM = GetScene()->FindGameObject<EfectManager>(); eM = GetScene()->FindGameObject<EnemyManager>(); pl = GetScene()->FindGameObject<Player>(); boss = _boss; bPosition = boss->GetPosition(); beforeBossPos = boss->GetPosition(); } VShaped_MINIONS::~VShaped_MINIONS() { DeleteGraph(hImage); boss = nullptr; } void VShaped_MINIONS::Update() { bPosition = boss->GetPosition(); base_angle = HomingBoss(bPosition); if (hp == 0) { efM->Create(position, 0, 0, 10, 0.5f, 0.5f, Efect::ColorPalette::white); itM->Create(position, itemKind); DestroyMe(); } if (position.x + WIDTH < 250 || position.x > 1175 || position.y + HEIGHT < -200 || position.y > 1040) { DestroyMe(); } position.x = position.x + cos(base_angle) * 3; position.y = position.y + sin(base_angle) * 3; cnt++; //position.x += velocity.x * speed; //position.y += velocity.y * speed; beforeBossPos = boss->GetPosition(); } void VShaped_MINIONS::Draw() { DrawRectGraph((int)position.x, (int)position.y, 0, 0, 40, 40, hImage, true); } bool VShaped_MINIONS::Collision(Vector2 center, float radius) const { if (hp == 0) return false; float dx = (position.x + CENTER_X) - center.x; float dy = (position.y + CENTER_Y) - center.y; return (dx*dx + dy * dy < (radius + RADIUS)*(radius + RADIUS)); } void VShaped_MINIONS::AddDamage(int damage) { hp -= damage; if (hp < 0) { hp = 0; } } void VShaped_MINIONS::setBoss(EnemyBase * _e) { boss = _e; } double VShaped_MINIONS::HomingBoss(Vector2 _bPos) { return atan2((float)_bPos.y - beforeBossPos.y, (float)_bPos.x - beforeBossPos.x); } <file_sep>#include "player.h" #include <assert.h> #include "debugScreen.h" namespace { static const int playerHeight = 48; //高さ static const int playerWidth = 48; //幅 static const int playerRadius = 24; static const float moveSpeed = 10.0f; //移動速度 } Player::Player(SceneBase* scene) : GameObject(scene) { position = Vector2(725, 900); corePosition = Vector2(position.x + 15, position.y + 21); shotCoolTime = 0; remainingPlayer = 3; shotPower = 9; hPlayerImage = LoadGraph("data\\texture\\reimu.png"); assert(hPlayerImage > 0); hPlayerCoreImage = LoadGraph("data\\texture\\playercore.png"); assert(hPlayerCoreImage > 0); pubPos = position; exist = true; efM = GetScene()->FindGameObject<EfectManager>(); eM = GetScene()->FindGameObject<EnemyManager>(); itM = GetScene()->FindGameObject<ItemManager>(); state = INVICIBLE; invincibleTime = 150; score = 0; } Player::~Player() { DestroyMe(); } void Player::Update() { if (shotPower <= 0) shotPower = 1; switch (state) { case INVICIBLE: Move(); Shot(); Collision(); invincibleTime -= 1; pubPos = position; corePosition = Vector2(position.x + 15.0f, position.y + 21.0f); if (invincibleTime <= 0) { state = ALIVE; } break; case ALIVE: Move(); Shot(); Collision(); corePosition = Vector2(position.x + 15.0f, position.y + 21.0f); shotCoolTime--; pubPos = position; corePosition = Vector2(position.x + 15.0f, position.y + 21.0f); break; case DEAD: Resurrection(); break; default: break; } } void Player::Draw() { switch (state) { case INVICIBLE: if (invincibleTime % 2 == 0) { SetDrawBright(40, 40, 40); DrawGraph((int)position.x, (int)position.y, hPlayerImage, true); //プレイヤーの描画 DrawGraph((int)position.x + 15, (int)position.y + 21, hPlayerCoreImage, true); //プレイヤーの描画 SetDrawBright(255, 255, 255); } if (invincibleTime % 2 == 1) { DrawGraph((int)position.x, (int)position.y, hPlayerImage, true); //プレイヤーの描画 DrawGraph((int)position.x + 15, (int)position.y + 21, hPlayerCoreImage, true); //プレイヤーの描画 } DebugPrintf(0, 200, "STATE = INVICIBLE"); break; case ALIVE: DrawGraph((int)position.x, (int)position.y, hPlayerImage, true); //プレイヤーの描画 DrawGraph((int)position.x + 15, (int)position.y + 21, hPlayerCoreImage, true); //プレイヤーの描画 DebugPrintf(0, 200, "STATE = ALIVE"); break; case DEAD: DebugPrintf(0, 200, "STATE = DEAD"); break; default: break; } int posX, posY; posX = position.x; posY = position.y; int cposX, cposY; cposX = corePosition.x + 5; cposY = corePosition.y + 5; DebugPrintf(0, 480, "score:%d", score); DebugPrintf(0, 500, "あと%d", remainingPlayer); DebugPrintf(0, 520, "Power:%d", shotPower); } void Player::Move() { if (CheckHitKey(KEY_INPUT_LEFT)) { position.x -= moveSpeed; } if (CheckHitKey(KEY_INPUT_RIGHT)) { position.x += moveSpeed; } if (CheckHitKey(KEY_INPUT_UP)) { position.y -= moveSpeed; } if (CheckHitKey(KEY_INPUT_DOWN)) { position.y += moveSpeed; } if (position.x < 310) { position.x = 310; } if (position.x + playerWidth > 1175) { position.x = 1175.0f - playerWidth; } if (position.y < 30) { position.y = 30; } if (position.y + playerHeight > 1040) { position.y = 1040.0f - playerHeight; } } void Player::Shot() { ShotManager* s = GetScene()->FindGameObject<ShotManager>(); if (CheckHitKey(KEY_INPUT_Z)) { if (shotCoolTime < 0) { if (shotPower < 10) { s->Spawn(position); } if (shotPower >= 10 && shotPower < 20) { s->Spawn(Vector2(position.x - 15, position.y)); s->Spawn(Vector2(position.x + 15, position.y)); } if (shotPower >= 20 && shotPower < 30) { s->Spawn(position); s->Spawn(Vector2(position.x - 30, position.y)); s->Spawn(Vector2(position.x + 30, position.y)); } if (shotPower >= 30 && shotPower < 40) { s->Spawn(Vector2(position.x - 15, position.y)); s->Spawn(Vector2(position.x - 45, position.y)); s->Spawn(Vector2(position.x + 15, position.y)); s->Spawn(Vector2(position.x + 45, position.y)); } if (shotPower >= 40) { s->Spawn(position); s->Spawn(Vector2(position.x - 30, position.y)); s->Spawn(Vector2(position.x - 60, position.y)); s->Spawn(Vector2(position.x + 30, position.y)); s->Spawn(Vector2(position.x + 60, position.y)); } shotCoolTime = 5; } } shotCoolTime--; } void Player::Resurrection() { if (remainingPlayer >= 0) { if (resurrectionCoolTime <= 0) { position = Vector2(Vector2(725, 900)); exist = true; state = INVICIBLE; invincibleTime = 180; } } resurrectionCoolTime -= 1; } void Player::Collision() { if (state == ALIVE) { if (e != nullptr) { e = eM->Collision(Vector2(corePosition.x + 5.0f, corePosition.y + 5.0f), 5.0f); } EnemyBarrageManager* eBM = GetScene()->FindGameObject<EnemyBarrageManager>(); eBM->GetPlayerPosition(Vector2(corePosition.x + 5.0f, corePosition.y + 5.0f)); if (e != nullptr) { efM->Create(position, 0, 0, 3, 1, 2, Efect::ColorPalette::white); remainingPlayer -= 1; resurrectionCoolTime = 60; shotPower -= 5; exist = false; state = DEAD; } if (eBM->Collision(Vector2(corePosition.x + 5.0f, corePosition.y + 5.0f), 5.0f)) { efM->Create(position, 0, 0, 3, 1, 2, Efect::ColorPalette::white); remainingPlayer -= 1; resurrectionCoolTime = 60; shotPower -= 5; exist = false; state = DEAD; } } int ItemKind = 0; ItemKind = itM->Collision(Vector2(corePosition.x + 5.0f, corePosition.y + 5.0f), playerRadius); switch (ItemKind) { case 1: shotPower += 1; break; case 2: score += 1000; break; case 3: bomb += 1; break; case 4: remainingPlayer += 1; break; } } Vector2 Player::GetPosition() { return position; } <file_sep>#pragma once #include "..//Library/gameObject.h" #include "vector2.h" #include "player.h" class EnemyBarrage : public GameObject { public: EnemyBarrage(SceneBase* _scene, Vector2 _pos, double _base_angle, int _bulletMax, Vector2 _playerPos, int _bulletKind, int _bulletColor, float _speed); virtual ~EnemyBarrage(); virtual void Update(); virtual void Draw(); virtual bool Collision(Vector2 center, float radius) const; //プレイヤーとの当たり判定 private: /*struct Bullet { Vector2 position; bool flag; int hImage; float angle; bool first; int cnt; float spd; int state; }; Bullet bullet[1000];*/ Vector2 position; bool flag; //int hImage; float angle; bool first; float spd; int state; double base_angle; int pattern; int cnt; int bulletMax; int bulletKind; int HEIGHT, WIDTH; int CENTER_X, CENTER_Y; int RADIUS; int bulletColor; int interval; float coolTime; Vector2 plPos; public: enum hImage_ID { dotbullet = 0, smallbullet1, smallbullet2, mediumbullet, largebullet, ricegrainbullet, MAX }; int hImage[hImage_ID::MAX]; //敵の弾の画像ハンドラ enum ColorPalette { white = 0, red, green, blue, }; ColorPalette colorPalette; };<file_sep>#pragma once #include "vector2.h" typedef struct { int flag; //フラグ int cnt; //カウンタ int power; //パワー int point; //ポイント int score; //スコア int num; //残機数 int mutekicnt; //無敵状態とカウント int shot_mode; //ショットモード int money; //お金 int img; //画像 int slow; //スローかどうか Vector2 position; //座標 }ch_t; typedef struct { //フラグ、カウンタ、移動パターン、向き、敵の種類、HP最大値、落とすアイテム、画像 int flag; int cnt; int pattern; int muki; int knd; int hp; int hp_max; int item_n[6]; int img; //座標、速度x成分、速度y成分、スピード、角度 double x, y, vx, vy, sp, ang; //弾幕開始時間、弾幕の種類、弾の種類、色、状態、待機時間、停滞時間 int bltime, blknd, blknd2, col, state, wtime, wait; }enemy_t;<file_sep>#include "vShaped_BOSS.h" #include <assert.h> namespace { static const int CENTER_X = 20; static const int CENTER_Y = 20; static const int WIDTH = 40; static const int HEIGHT = 40; static const int RADIUS = 20; } VShaped_BOSS::VShaped_BOSS(SceneBase* scene, int _x, int _y, int _cnt, int _pattern, float _speed, int _barrageTime, int _maxBullet, int _barrageKind, int _color, int _hp, int _bulletKind, int _waitTime, int _stagnationTime, int _itemKind) : EnemyBase(scene){ position = Vector2(_x, _y); hImage = LoadGraph("data\\texture\\furball.png"); assert(hImage > 0); cnt = _cnt; pattern = _pattern; speed = _speed; barrageTime = _barrageTime; maxBullet = _maxBullet; barrageKind = _barrageKind; color = _color; hp = _hp; bulletKind = _bulletKind; waitTime = _waitTime; stagnationTime = _stagnationTime; itemKind = _itemKind; shotFlag = false; eBM = GetScene()->FindGameObject<EnemyBarrageManager>(); efM = GetScene()->FindGameObject<EfectManager>(); itM = GetScene()->FindGameObject<ItemManager>(); eSM = GetScene()->FindGameObject<EnemyShotManager>(); pl = GetScene()->FindGameObject<Player>(); } VShaped_BOSS::~VShaped_BOSS() { DeleteGraph(hImage); } void VShaped_BOSS::Update() { if (hp == 0) { efM->Create(position, 0, 0, 10, 0.5f, 0.5f, Efect::ColorPalette::white); itM->Create(position, itemKind); DestroyMe(); } /*if (position.x + WIDTH < 310 || position.x > 1175 || position.y + HEIGHT < -40 || position.y > 1040) { DestroyMe(); }*/ //switch (pattern) //{ //case 0: MovePattern_0(); break; //下に移動、一定時間止まって上に戻る //} if (cnt == waitTime) { velocity.y = 3; } if (cnt == waitTime + 150) { velocity.y = 0; velocity.x = 3; } cnt++; position.x += velocity.x * speed; position.y += velocity.y * speed; } void VShaped_BOSS::Draw() { DrawRectGraph((int)position.x, (int)position.y, 0, 0, 40, 40, hImage, true); } bool VShaped_BOSS::Collision(Vector2 center, float radius) const { if (hp == 0) return false; float dx = (position.x + CENTER_X) - center.x; float dy = (position.y + CENTER_Y) - center.y; return (dx*dx + dy * dy < (radius + RADIUS)*(radius + RADIUS)); } void VShaped_BOSS::AddDamage(int damage) { hp -= damage; if (hp < 0) { hp = 0; } } void VShaped_BOSS::MovePattern_0() { //if (cnt == waitTime) //velocity.y = 3; } Vector2 VShaped_BOSS::GetPosition() { return position; } <file_sep>#include "background.h" #include <assert.h> BackGround::BackGround(SceneBase * scene) : GameObject(scene) { hImage = LoadGraph("data\\texture\\haikei.png"); assert(hImage > 0); firstY = 30; secondY = -980; } BackGround::~BackGround() { } void BackGround::Update() { firstY += 5; secondY += 5; if (firstY > 1040) { firstY = -975; } if (secondY > 1040) { secondY = -975; } } void BackGround::Draw() { DrawGraph(X, firstY, hImage, true); DrawGraph(X, secondY, hImage, true); DrawBox(310, 30, 1175, 1040, GetColor(255, 255, 255), false); //プレイ領域 DrawLine(310, 535, 1175, 535, GetColor(255, 255, 255)); //プレイ領域の真ん中の線 DrawLine(240, 0, 240, 1080, GetColor(255, 255, 255)); //左端の線 DrawLine(1680, 0, 1680, 1080, GetColor(255, 255, 255)); //右端の線 DrawLine(742.5f, 30, 742.5f, 1040, GetColor(255, 255, 255)); //右端の線 } <file_sep>#include "enemyShotManager.h" EnemyShotManager::EnemyShotManager(SceneBase * _scene) : GameObject(_scene) { shots.clear(); } EnemyShotManager::~EnemyShotManager() { for (auto it = shots.begin(); it != shots.end();) { delete (*it); it = shots.erase(it); } shots.clear(); } void EnemyShotManager::Update() { for (auto it = shots.begin(); it != shots.end();) { (*it)->Update(); if ((*it)->IsDestroy()) { delete(*it); it = shots.erase(it); } else it++; } for (auto& eS : shots) { eS->Update(); } } void EnemyShotManager::Draw() { } void EnemyShotManager::Create(Vector2 _pos, int _maxbullet, int _barrageKind, int _bulletKind, int _bulletColor) { EnemyShot* eS = new EnemyShot(GetScene(), _pos, _maxbullet, _barrageKind, _bulletKind, _bulletColor); if (eS != nullptr) { shots.emplace_back(eS); } } <file_sep>#include "itemManager.h" #include "powerupItem.h" #include "scoreItem.h" ItemManager::ItemManager(SceneBase* scene) : GameObject(scene) { items.clear(); } ItemManager::~ItemManager() { for (auto it = items.begin(); it != items.end();) { delete (*it); it = items.erase(it); } items.clear(); } void ItemManager::Update() { for (auto it = items.begin(); it != items.end();) { (*it)->Update(); if ((*it)->IsDestroy()) { delete(*it); it = items.erase(it); } else it++; } for (auto& it : items) { it->Update(); } } void ItemManager::Draw() { for (auto& it : items) { it->Draw(); } } void ItemManager::Create(Vector2 _pos, int _itemKind) { ItemBase* it = nullptr; itemKind = _itemKind; switch (_itemKind) { case POWERUP: it = new PowerupItem(GetScene(), _pos); break; case SCORE: it = new ScoreItem(GetScene(), _pos); break; } it->itemKind = _itemKind; if (it != nullptr) items.emplace_back(it); } int ItemManager::Collision(Vector2 center, float radius) { for (auto it : items) { if (it->Collision(center, radius)) return it->itemKind; } return false; } <file_sep>#pragma once #include "../Library/gameObject.h" class Board : public GameObject { public: Board(SceneBase* _scene); ~Board(); void Update(); void Draw(); private: int hImage; };<file_sep>#pragma once //itemManager.h #include "..//Library/gameObject.h" #include "itemBase.h" class ItemManager : public GameObject { public: ItemManager(SceneBase* scene); ~ItemManager(); void Update(); void Draw(); enum ITEM_TYPE { NONE = 0, POWERUP, SCORE, BOMB, EXTEND, }; void Create(Vector2 _pos, int _itemKind); int Collision(Vector2 center, float radius); private: std::list<ItemBase*> items; int itemKind; };<file_sep>#include "playScene.h" #include "../Library/sceneManager.h" #include "DebugScreen.h" #include "player.h" #include "background.h" #include "shotManager.h" #include "board.h" #include "enemyManager.h" #include "field.h" #include "efectManager.h" #include "enemyBarrageManager.h" #include "itemManager.h" #include "enemyShotManager.h" PlayScene::PlayScene() { CreateGameObject<BackGround>(); CreateGameObject<Field>(); CreateGameObject<EfectManager>(); CreateGameObject<EnemyManager>(); CreateGameObject<EnemyBarrageManager>(); CreateGameObject<EnemyShotManager>(); CreateGameObject<ShotManager>(); CreateGameObject<ItemManager>(); CreateGameObject<Player>(); CreateGameObject<Board>(); state = BEFORE_PLAY; } PlayScene::~PlayScene() { } void PlayScene::Update() { if (CheckHitKey(KEY_INPUT_T)) { SceneManager::ChangeScene("TitleScene"); } counter++; switch (state) { case BEFORE_PLAY: if (counter >= 180) { PlaySoundMem(bgmSound, DX_PLAYTYPE_LOOP); state = IN_PLAY; counter = 0; } break; case IN_PLAY: break; case CLEAR: break; case GAMEOVER: break; } SceneBase::Update(); } void PlayScene::Draw() { SceneBase::Draw(); switch (state) { case BEFORE_PLAY: DrawString(0, 20, "BEFORE_PLAY", GetColor(255, 255, 255)); break; case IN_PLAY: DrawString(0, 20, "IN_PLAY", GetColor(255, 255, 255)); break; case CLEAR: DrawString(0, 20, "CLEAR", GetColor(255, 255, 255)); break; case GAMEOVER: DrawString(0, 20, "GAME_OVER", GetColor(255, 255, 255)); break; } DrawString(0, 0, "PLAY SCENE", GetColor(255, 255, 255)); DrawString(100, 400, "Push [T]Key To Title", GetColor(255, 255, 255)); } bool PlayScene::CanMove() const { return state != BEFORE_PLAY; } void PlayScene::Clear() { } void PlayScene::GameOver() { } <file_sep>#include "field.h" #include "enemyManager.h" Field::Field(SceneBase * scene) : GameObject(scene) { } Field::~Field() { } void Field::Start() { int n, num, i, fp; char fname[32] = { "data\\enemy\\storyH0.csv" }; int input[64]; char inputc[64]; int cnt; //カウンタ float x, y; //座標 float speed; //スピード float angle; //角度 int exist; //生存フラグ int pattern; //移動パターン int direction; //向き int type; //敵の種類 int hp; //体力 int hp_max; //体力最大値 int itemKind; //落とすアイテム int barrageTime; //弾幕開始時間 int maxBullet; //弾の数 int barrageKind; //弾幕の種類 int bulletKind; //弾の種類 int color; //弾の色 int state; //敵の状態 int waitTime; //待機時間 int stagnationTime; //停滞時間 EnemyManager* eM = GetScene()->FindGameObject<EnemyManager>(); fp = FileRead_open(fname); //ファイル読み込み if (fp == NULL) { printfDx("read error\n"); return; } for (i = 0; i < 2; i++) //最初の2行は読まない while (FileRead_getc(fp) != '\n'); n = 0, num = 0; while (1) { for (i = 0; i < 64; i++) { inputc[i] = input[i] = FileRead_getc(fp); //1文字取得する if (inputc[i] == '/') { //スラッシュがあったら while (FileRead_getc(fp) != '\n'); //改行までループ i = 1; //カウンタを最初に戻して continue; } if (input[i] == ',' || input[i] == '\n') { //カンマか改行なら inputc[i] = '\0'; //そこまでを文字列とし break; } if (input[i] == EOF) { goto EXFILE; //終了 } } switch (num) { case 0: cnt = atoi(inputc); break; case 1: pattern = atoi(inputc); break; case 2: type = atoi(inputc); break; case 3: x = atoi(inputc); break; case 4: y = atoi(inputc); break; case 5: speed = atoi(inputc); break; case 6: barrageTime = atoi(inputc); break; case 7: maxBullet = atoi(inputc); break; case 8: barrageKind = atoi(inputc); break; case 9: color = atoi(inputc); break; case 10: hp = atoi(inputc); break; case 11:bulletKind = atoi(inputc); break; case 12:waitTime = atoi(inputc); break; case 13:stagnationTime = atoi(inputc); break; case 14:itemKind = atoi(inputc); break; } num++; if (num == 15) { switch (type) { case 0: eM->Create(EnemyManager::ENEMY_TYPE::FURBALL, x, y, cnt, pattern, speed, barrageTime, maxBullet, barrageKind, color, hp, bulletKind, waitTime, stagnationTime, itemKind); break; case 1: eM->Create(EnemyManager::ENEMY_TYPE::FAIRY, x, y, cnt, pattern, speed, barrageTime, maxBullet, barrageKind, color, hp, bulletKind, waitTime, stagnationTime, itemKind); break; case 2: eM->Create(EnemyManager::ENEMY_TYPE::VSHAPED, x, y, cnt, pattern, speed, barrageTime, maxBullet, barrageKind, color, hp, bulletKind, waitTime, stagnationTime, itemKind); break; } num = 0; n++; } } EXFILE: FileRead_close(fp); } void Field::Draw() { } <file_sep>#pragma once #include "enemyBase.h" #include "enemyBarrageManager.h" #include "itemManager.h" #include "enemyShotManager.h" #include "player.h" #include "vShaped_BOSS.h" class VShaped_MINIONS : public EnemyBase { public: VShaped_MINIONS(SceneBase* scene, int x, int y, int cnt, int pattern, float speed, int barrageTime, int maxBullet, int barrageKind, int color, int hp, int bulletKind, int waitTime, int stagnationTime, int itemKind, EnemyBase* _boss); ~VShaped_MINIONS(); void Update() override; void Draw() override; bool Collision(Vector2 center, float radius) const override; void AddDamage(int damage) override; void setBoss(EnemyBase* _e); double HomingBoss(Vector2 _bPos); private: int hImage; bool hitShot; Vector2 position; //自分の座標 Vector2 bPosition; //親分の現在座標 Vector2 beforeBossPos; Vector2 velocity; //速度成分 int cnt; //カウンタ float speed; //スピード float angle; //角度 int exist; //生存フラグ int pattern; //移動パターン int direction; //向き int type; //敵の種類 int hp; //体力 int hp_max; //体力最大値 int itemKind; //落とすアイテム int barrageTime; //弾幕開始時間 int maxBullet; //弾の数 int barrageKind; //弾幕の種類 int bulletKind; //弾の種類 int color; //弾の色 int state; //敵の状態 int waitTime; //待機時間 int stagnationTime; //停滞時間 bool shotFlag; //弾を撃っていたらtrue bool specialAttack; //trueだったら特攻 double base_angle; Vector2 plPos; //自機の座標 EnemyManager* eM; EnemyBarrageManager* eBM; EfectManager* efM; ItemManager* itM; EnemyShotManager* eSM; Player* pl; EnemyBase* boss; };<file_sep>#include "efectManager.h" EfectManager::EfectManager(SceneBase * scene) : GameObject (scene) { efects.clear(); } EfectManager::~EfectManager() { for (auto it = efects.begin(); it != efects.end();) { delete (*it); it = efects.erase(it); } efects.clear(); } void EfectManager::Update() { for (auto it = efects.begin(); it != efects.end();) { (*it)->Update(); if ((*it)->IsDestroy()) { delete(*it); it = efects.erase(it); } else it++; } for (auto& ef : efects) { ef->Update(); } } void EfectManager::Draw() { for (auto& ef : efects) { ef->Draw(); } } void EfectManager::Create(Vector2 pos, int _pattern, int _drawPattern, float _valueSpeed, float _sizeSpeed, float firstSize, int _color) { Efect* ef = new Efect(GetScene(), pos, _pattern, _drawPattern, _valueSpeed, _sizeSpeed, firstSize, _color); if (ef != nullptr) efects.emplace_back(ef); } <file_sep>#pragma once #include "../Library/gameObject.h" #include "vector2.h" #include "efectManager.h" /// <summary> /// 敵の基底クラス /// </summary> class EnemyBase : public GameObject { public: EnemyBase(SceneBase* _scene) : GameObject(_scene) {} virtual ~EnemyBase() {} virtual void Update() override {} virtual void Draw() override {} virtual bool Collision(Vector2 center, float radius) const { return false; } //プレイヤー、弾との当たり判定 virtual void AddDamage(int damage){} virtual void MovePattern_0(){} //移動パターン virtual void MovePattern_1(){} //移動パターン virtual void MovePattern_2(){} //移動パターン virtual void MovePattern_3(){} //移動パターン virtual void MovePattern_4(){} //移動パターン virtual void MovePattern_5(){} //移動パターン virtual Vector2 GetPosition() { return position; } private: Vector2 position; //座標 Vector2 velocity; //速度成分 float spped; //スピード float angle; //角度 int cnt; //カウンタ int exist; //生存フラグ int pattern; //移動パターン int direction; //向き int type; //敵の種類 int hp; //体力 int hp_max; //体力最大値 int item[6]; //落とすアイテム int barrageTime; //弾幕開始時間 int barrageKind; //弾幕の種類 int bulletKind; //弾の種類 int color; //弾の色 int state; //敵の状態 int waitTime; //待機時間 int stagnationTime; //停滞時間 };<file_sep>#pragma once #include "..//Library/gameObject.h" #include "enemyShot.h" class EnemyShot; class EnemyShotManager : public GameObject { public: EnemyShotManager(SceneBase* _scene); ~EnemyShotManager(); void Update(); void Draw(); void Create(Vector2 _pos, int _maxbullet, int _barrageKind, int _bulletKind, int _bulletColor); private: std::list<EnemyShot*> shots; };<file_sep>#pragma once //efectManager.h #include "..//Library/gameObject.h" #include "efect.h" class EfectManager : public GameObject { public: EfectManager(SceneBase* scene); ~EfectManager(); void Update(); void Draw(); /// <summary> /// /// </summary> /// <param name="pos">生成場所</param> /// <param name="_pattern">動きのパターン</param> /// <param name="_drawPattern">描画パターン</param> /// <param name="_valueSpeed">消える速度</param> /// <param name="_sizeSpeed">サイズの変わる速度</param> /// <param name="firstSize">最初の大きさ</param> void Create(Vector2 pos, int _pattern, int _drawPattern, float _valueSpeed, float _sizeSpeed, float firstSize, int _color); private: std::list<Efect*> efects; };<file_sep>#include "enemyBarrage.h" #include <assert.h> namespace { //定数の配列 テーブル static const std::string folder = "data\\texture\\enemybullet\\"; static const std::string fileName[EnemyBarrage::hImage_ID::MAX] = { "dotbullet", "smallbullet1", "smallbullet2", "mediumbullet", "largebullet", "ricegrainbullet2" }; } EnemyBarrage::EnemyBarrage(SceneBase* _scene, Vector2 _pos, double _base_angle, int _bulletMax, Vector2 _playerPos, int _bulletKind, int _bulletColor, float _speed) : GameObject(_scene) { bulletMax = _bulletMax; //pattern = 0; bulletKind = _bulletKind; bulletColor = _bulletColor; plPos = _playerPos; /*for (int i = 0; i < bulletMax; i++) { bullet[i].position = _pos; bullet->flag = true; bullet[i].first = true; bullet->spd = _speed; }*/ position = _pos; flag = true; spd = _speed; base_angle = _base_angle; for (int i = 0; i < hImage_ID::MAX; i++) { hImage[i] = LoadGraph((folder + fileName[i] + ".png").c_str()); assert(hImage[i] > 0); } switch (bulletKind) { case dotbullet: WIDTH = 9; HEIGHT = 9; CENTER_X = 4; CENTER_Y = 4; RADIUS = 4; break; case smallbullet1: WIDTH = 13; HEIGHT = 13; CENTER_X = 6; CENTER_Y = 6; RADIUS = 6; break; case smallbullet2: WIDTH = 17; HEIGHT = 17; CENTER_X = 8; CENTER_Y = 8; RADIUS = 8; break; case mediumbullet: WIDTH = 27; HEIGHT = 27; CENTER_X = 13; CENTER_Y = 13; RADIUS = 13; break; case largebullet: WIDTH = 62; HEIGHT = 62; CENTER_X = 31; CENTER_Y = 31; RADIUS = 22; break; case ricegrainbullet: WIDTH = 16; HEIGHT = 7; CENTER_X = 8; CENTER_Y = 3; RADIUS = 3; break; } coolTime = 0; } EnemyBarrage::~EnemyBarrage() { } void EnemyBarrage::Update() { /*for (int i = 0; i < bulletMax; i++) { bullet[i].cnt += 1; bullet[i].position.x = bullet[i].position.x + cos(bullet[i].angle) * bullet[i].spd; bullet[i].position.y = bullet[i].position.y + sin(bullet[i].angle) * bullet[i].spd; }*/ cnt += 1; position.x = position.x + cos(base_angle) * spd; position.y = position.y + sin(base_angle) * spd; /*画面外に出たら消す*/ /*for (int i = 0; i < bulletMax; i++) { if (bullet[i].position.x + WIDTH < 310 || bullet[i].position.x > 1175 || bullet[i].position.y + HEIGHT < -40 || bullet[i].position.y > 1040) { bullet[i].flag = false; } }*/ if (position.x + WIDTH < 310 || position.x > 1175 || position.y + HEIGHT < -40 || position.y > 1040) { flag = false; } /*画面外に出たら消す*/ cnt += 1; coolTime -= 1; } void EnemyBarrage::Draw() { switch (bulletColor) { case white: SetDrawBright(255, 255, 255); break; case red: SetDrawBright(255, 0, 0); break; case green: SetDrawBright(0, 255, 0); break; case blue: SetDrawBright(0, 0, 255); break; } //for (int i = 0; i < bulletMax; i++) { // if (bullet[i].flag) { // //DrawGraph((int)bullet[i].position.x, (int)bullet[i].position.y, hImage[bulletKind], true); // DrawRotaGraph((int)bullet[i].position.x, (int)bullet[i].position.y, 1, bullet[i].angle, hImage[bulletKind], true); // } //} if (flag) { DrawRotaGraph((int)position.x, (int)position.y, 1, base_angle, hImage[bulletKind], true); } SetDrawBright(255, 255, 255); } //void EnemyBarrage::BarragePattern_0(int _i) //{ // /*拡散弾*/ // bullet[_i].angle = (float)((360 / bulletMax) * _i * (DX_PI / 180)); // //bullet[_i].position.x = bullet[_i].position.x + cos(bullet[_i].angle) * 5; // //bullet[_i].position.y = bullet[_i].position.y + sin(bullet[_i].angle) * 5; // bullet[_i].spd = 5; // bullet[_i].flag = true; // // coolTime = 300; // // for (int i = 0; i < bulletMax; i++) { // if (!bullet[i].flag) { // bullet[i].angle = (float)((360)) // } // } //} // //void EnemyBarrage::BarragePattern_1(int _i) //{ // /*自機狙い*/ // if (bullet[_i].first) { // bullet[_i].angle = Shotatan2(bullet[_i].position); // bullet[_i].first = false; // } // bullet[_i].position.x = bullet[_i].position.x + cos(bullet[_i].angle) * (_i + 1); // bullet[_i].position.y = bullet[_i].position.y + sin(bullet[_i].angle) * (_i + 1); // bullet[_i].flag = true; //} // //void EnemyBarrage::BarragePattern_2(int _i) //{ // //ばらまき // int t = bullet[_i].cnt; // if (t >= 0 && t < 120 && t % 2 == 0) { // if (bullet[_i].first) { // bullet[_i].angle = Shotatan2(bullet[_i].position) + Rang(PI / 4); // bullet[_i].first = false; // } // bullet[_i].flag = 1; // bullet[_i].cnt = 0; // bullet[_i].spd = 3 + Rang(1.5); // } //} // //void EnemyBarrage::BarragePattern_3(int _i) //{ // //ばらまき(減速) // int t = bullet[_i].cnt; // if (t >= 0 && t < 120 && t % 2 == 0) { // if (bullet[_i].first) { // bullet[_i].angle = Shotatan2(bullet[_i].position) + Rang(PI / 4); // bullet[_i].first = false; // } // bullet[_i].flag = 1; // bullet[_i].cnt = 0; // bullet[_i].spd = 4 + Rang(2); // } // for (int i = 0; i < bulletMax; i++) {//全弾分ループ // if (bullet[i].spd > 1.5)//速度が1.5より大きいものがあれば // bullet[i].spd -= 0.04;//減速 // } //} // //void EnemyBarrage::BarragePattern_4(int _i) //{ // int t = cnt; // if (t >= 0 && t < 1200 && t % 90 == 0) { // double angle = rang(PI, bullet[_i].angle); // for (int j = 0; j < 2; j++) {//途中から2分裂する分 // bullet[_i].angle = angle + PI2 / 60 * _i;//円形60個 // bullet[_i].flag = true; // bullet[_i].cnt = 0; // bullet[_i].state = j;//ステータス。0か1かで回転がかわる // bullet[_i].spd = 2; // } // } // if (bullet[_i].flag > 0) {//登録されている弾があれば // int state = bullet[_i].state; // int cnt = bullet[_i].cnt; // if (30 < cnt && cnt < 120) {//30〜120カウントなら // bullet[_i].spd -= 1.2 / 90.0;//90カウントかけて1.2減らす // bullet[_i].angle += (PI / 2) / 90.0*(state ? -1 : 1);//90カウントかけて90°傾ける // } // } //} bool EnemyBarrage::Collision(Vector2 center, float radius) const { /*for (int i = 0; i < bulletMax; i++) { float dx = (bullet[i].position.x + CENTER_X) - center.x; float dy = (bullet[i].position.y + CENTER_Y) - center.y; if (dx*dx + dy * dy < (radius + RADIUS)*(radius + RADIUS)) { return true; break; } }*/ float dx = (position.x + CENTER_X) - center.x; float dy = (position.y + CENTER_Y) - center.y; if (dx*dx + dy * dy < (radius + RADIUS)*(radius + RADIUS)) { return true; } return false; } <file_sep>#include "shotBase.h" #include "enemyManager.h" #include "enemyBase.h" #include "efectManager.h" ShotBase::ShotBase(SceneBase * _scene, Vector2 _pos) : GameObject(_scene) { position.x = _pos.x; position.y = _pos.y; hImage = LoadGraph("data\\texture\\shot.png"); value = 255; size = 0; } ShotBase::~ShotBase() { } void ShotBase::Update() { position.y -= speed; EfectManager* efM = GetScene()->FindGameObject<EfectManager>(); if (position.y < 30) { DestroyMe(); } EnemyManager* eneM = GetScene()->FindGameObject<EnemyManager>(); EnemyBase* e = eneM->Collision(Vector2(position.x + 10.0f, position.y + 10.0f), 5.0f); if (e != nullptr) { efM->Create(position, 3, 0, 5, 0.1f, 1, Efect::ColorPalette::red); e->AddDamage(10); DestroyMe(); } } void ShotBase::Draw() { DrawGraph((int)position.x + 10, (int)position.y, hImage, true); } <file_sep>#include "enemyBarrageManager.h" #include "player.h" #include "playScene.h" EnemyBarrageManager::EnemyBarrageManager(SceneBase* scene) { barrages.clear(); } EnemyBarrageManager::~EnemyBarrageManager() { for (auto it = barrages.begin(); it != barrages.end();) { delete (*it); it = barrages.erase(it); } barrages.clear(); } void EnemyBarrageManager::Update() { for (auto it = barrages.begin(); it != barrages.end();) { (*it)->Update(); if ((*it)->IsDestroy()) { delete(*it); it = barrages.erase(it); } else it++; } for (auto& eb : barrages) { eb->Update(); } } void EnemyBarrageManager::Draw() { for (auto& eb : barrages) { eb->Draw(); } } void EnemyBarrageManager::Create(Vector2 pos, double _base_angle,int _bulletMax,int _bulletKind,int _bulletColor, float _speed) { EnemyBarrage* eb = new EnemyBarrage(GetScene(), pos, _base_angle, _bulletMax, playerPosition, _bulletKind, _bulletColor, _speed); if (eb != nullptr) barrages.emplace_back(eb); } void EnemyBarrageManager::GetPlayerPosition(Vector2 pos) { playerPosition = pos; } bool EnemyBarrageManager::Collision(Vector2 center, float radius) { for (auto eb : barrages) { if (eb->Collision(center, radius)) return true; } return false; }<file_sep>#pragma once //shotManager.h #include "..//Library/gameObject.h" #include "shotBase.h" class ShotManager : public GameObject{ public: ShotManager(SceneBase* _scene); ~ShotManager(); void Update() override; void Draw() override; void Spawn(Vector2 _pos); private: std::list<ShotBase*> shots; };<file_sep>#include "scoreItem.h" #include <assert.h> #include "debugScreen.h" namespace { static const int CENTER_X = 16; static const int CENTER_Y = 16; static const int RADIUS = 16; } ScoreItem::ScoreItem(SceneBase * _scene, Vector2 _position) : ItemBase(_scene) { position = _position; hImage = LoadGraph("data\\texture\\item\\scoreItem.png"); assert(hImage > 0); velocity.y = -2; exist = true; } ScoreItem::~ScoreItem() { } void ScoreItem::Update() { if (position.y > 1080) { exist = false; } if (!exist) DestroyMe(); if (cnt == 60) velocity.y = 0; if (cnt == 70) velocity.y = 2; position.y += velocity.y; cnt++; } void ScoreItem::Draw() { DrawGraph(position.x, position.y, hImage, true); } bool ScoreItem::Collision(Vector2 center, float radius) { float dx = (position.x + CENTER_X) - center.x; float dy = (position.y + CENTER_Y) - center.y; if (dx*dx + dy * dy < (radius + RADIUS)*(radius + RADIUS)) { exist = false; return true; } return false; } <file_sep>#include "powerupItem.h" #include <assert.h> #include "debugScreen.h" namespace { static const int CENTER_X = 16; static const int CENTER_Y = 16; static const int RADIUS = 16; } PowerupItem::PowerupItem(SceneBase* _scene,Vector2 _position) : ItemBase(_scene) { position = _position; hImage = LoadGraph("data\\texture\\item\\powerupItem.png"); assert(hImage > 0); velocity.y = -2; exist = true; } PowerupItem::~PowerupItem() { } void PowerupItem::Update() { if (position.y > 1080) { exist = false; } if (!exist) DestroyMe(); if (cnt == 60) velocity.y = 0; if (cnt == 70) velocity.y = 2; position.y += velocity.y; cnt++; } void PowerupItem::Draw() { DrawGraph(position.x, position.y, hImage, true); } bool PowerupItem::Collision(Vector2 center, float radius) { float dx = (position.x + CENTER_X) - center.x; float dy = (position.y + CENTER_Y) - center.y; if (dx*dx + dy * dy < (radius + RADIUS)*(radius + RADIUS)) { exist = false; return true; } return false; } <file_sep>#pragma once class Vector2 { public: double x, y; Vector2() : x(0), y(0) {} Vector2(double _x, double _y) : x(_x), y(_y) {} Vector2(int _x, int _y) : x(static_cast<double>(_x)), y(static_cast<double>(_y)) {} };<file_sep>#include "furball.h" #include <assert.h> #include "enemyBarrageManager.h" namespace { static const int CENTER_X = 20; static const int CENTER_Y = 20; static const int WIDTH = 40; static const int HEIGHT = 40; static const int RADIUS = 20; } Furball::Furball(SceneBase* scene, int _x, int _y, int _cnt, int _pattern, float _speed, int _barrageTime, int _maxBullet, int _barrageKind, int _color, int _hp, int _bulletKind, int _waitTime, int _stagnationTime, int _itemKind) : EnemyBase(scene) { position = Vector2(_x, _y); hImage = LoadGraph("data\\texture\\furball.png"); assert(hImage > 0); cnt = _cnt; pattern = _pattern; speed = _speed; barrageTime = _barrageTime; maxBullet = _maxBullet; barrageKind = _barrageKind; color = _color; hp = _hp; bulletKind = _bulletKind; waitTime = _waitTime; stagnationTime = _stagnationTime; itemKind = _itemKind; shotFlag = false; eBM = GetScene()->FindGameObject<EnemyBarrageManager>(); efM = GetScene()->FindGameObject<EfectManager>(); itM = GetScene()->FindGameObject<ItemManager>(); eSM = GetScene()->FindGameObject<EnemyShotManager>(); pl = GetScene()->FindGameObject<Player>(); } Furball::~Furball() { DeleteGraph(hImage); } void Furball::Update() { if (hp == 0) { efM->Create(position, 0, 0, 10, 0.5f, 0.5f, Efect::ColorPalette::white); itM->Create(position, itemKind); DestroyMe(); } if (position.x + WIDTH < 310 || position.x > 1175 || position.y + HEIGHT < -40 || position.y > 1040) { DestroyMe(); } switch (pattern) { case 0: MovePattern_0(); break; //下に移動、一定時間止まって上に戻る case 1: MovePattern_1(); break; //下に移動、一定時間止まって左下に進む case 2: MovePattern_2(); break; //下に移動、一定時間止まって右下に進む case 3: MovePattern_3(); break; //下に移動、即座に左下に進む case 4: MovePattern_4(); break; //下に移動、即座に右下に進む case 5: MovePattern_5(); break; // } cnt++; position.x += velocity.x * speed; position.y += velocity.y * speed; } void Furball::Draw() { DrawRectGraph((int)position.x, (int)position.y, 0, 0, 40, 40, hImage, true); DrawFormatString(0, 60, GetColor(255, 255, 255), "%d", cnt); } bool Furball::Collision(Vector2 center, float radius) const { if (hp == 0) return false; float dx = (position.x + CENTER_X) - center.x; float dy = (position.y + CENTER_Y) - center.y; return (dx*dx + dy * dy < (radius + RADIUS)*(radius + RADIUS)); } void Furball::AddDamage(int damage) { hp -= damage; if (hp < 0) { hp = 0; } } void Furball::MovePattern_0() { if (cnt == waitTime) velocity.y = 3; if (cnt == waitTime + 60) { velocity.y = 0; //eBM->Create(position, maxBullet, barrageKind, bulletKind, color); eSM->Create(position, maxBullet, barrageKind, bulletKind, color); } if (cnt == waitTime + 60 + stagnationTime) velocity.y = -2; } void Furball::MovePattern_1() { if (cnt == waitTime) velocity.y = 3; if (cnt == waitTime + 180) eSM->Create(position, maxBullet, barrageKind, bulletKind, color); } void Furball::MovePattern_2() { if (cnt == waitTime) velocity.y = 3; if (cnt == waitTime + 60) velocity.y = 0; if (cnt == waitTime + 60 + stagnationTime) { velocity.y = 3; velocity.x = 1; } } void Furball::MovePattern_3() { if (cnt == waitTime) velocity.y = 5; if (cnt == waitTime + 60) { velocity.y -= 5 / 50; velocity.x -= 5; //eBM->Create(position, maxBullet, barrageKind, bulletKind, color); eSM->Create(position, maxBullet, barrageKind, bulletKind, color); } /*if (cnt == waitTime + 65) { eBM->Create(position); } if (cnt == waitTime + 70) { eBM->Create(position); }*/ } void Furball::MovePattern_4() { if (cnt == waitTime) velocity.y = 5; if (cnt == waitTime + 60) { velocity.y -= 5 / 50; velocity.x += 5; eSM->Create(position, maxBullet, barrageKind, bulletKind, color); } } void Furball::MovePattern_5() { } <file_sep>#pragma once static const int SCREEN_WIDTH = 1920; //static const int SCREEN_WIDTH = 800; static const int SCREEN_HEIGHT = 1080; //static const int SCREEN_HEIGHT = 600; static const BOOL WINDOW_MODE = TRUE; //static const BOOL WINDOW_MODE = FALSE; static const char* WINDOW_NAME = "プロジェクト"; static const float WINDOW_EXTEND = 1.0f;<file_sep>#include "efect.h" #include <assert.h> namespace { //定数の配列 テーブル static const std::string folder = "data\\texture\\efect\\"; static const std::string fileName[Efect::hImage_ID::MAX] = { "efect1", "efect2", "efect3", "efect4", "efect5", }; } Efect::Efect(SceneBase * scene, Vector2 _pos, int _pattern, int _drawPattern, float _valueSpeed, float _sizeSpeed, float firstSize,int _color) : GameObject(scene) { position = _pos; pattern = _pattern; drawPattern = _drawPattern; valueSpeed = _valueSpeed; sizeSpeed = _sizeSpeed; size = firstSize; color = _color; value = 255; efectKind = 3; for (int i = 0; i < hImage_ID::MAX; i++) { hImage[i] = LoadGraph((folder + fileName[i] + ".png").c_str()); assert(hImage[i] > 0); } for (int i = 0; i < 10; i++) { first[i] = true; } } Efect::~Efect() { } void Efect::Update() { switch (pattern) { case 0: pattern_0(); break; case 1: pattern_1(); break; case 2: pattern_2(); break; case 3: pattern_3(); break; } } void Efect::Draw() { SetDrawArea(310, 30, 1175, 1040); switch (color) { case white: SetDrawBright(255, 255, 255); break; case red: SetDrawBright(255, 0, 0); break; case green: SetDrawBright( 0, 255, 0); break; case blue: SetDrawBright( 0, 0, 255); break; } switch (drawPattern) { case 0: drawPattern_0(); break; case 1: drawPattern_1(); break; } SetDrawArea(0, 0, 1920, 1080); SetDrawBright(255, 255, 255); } void Efect::pattern_0() { //生成場所を中心に大きくなって消える value -= valueSpeed; size += sizeSpeed; if (value <= 0) DestroyMe(); } void Efect::pattern_1() { //試作段階 float angle[10]; for (int i = 0; i < 10; i++) { if (first[i]) { pos[i] = position; first[i] = false; } angle[i] = (float)((360 / 10)* i * (DX_PI / 180)); pos[i].x = pos[i].x + cos(angle[i]) * (i - 10); pos[i].y = pos[i].y + sin(angle[i]) * (10 - i); } value -= 3; if (value <= 0) DestroyMe(); } void Efect::pattern_2() { value -= valueSpeed; if (size < 5) size += sizeSpeed; if (size >= 5) size += sizeSpeed / 5; if (value <= 0) DestroyMe(); } void Efect::pattern_3() { value -= valueSpeed; size += sizeSpeed; position.y -= 5; } void Efect::drawPattern_0() { SetDrawBlendMode(DX_BLENDMODE_ALPHA, (int)value); DrawRotaGraph((int)position.x, (int)position.y, (int)size, 0, hImage[efectKind], true); SetDrawBlendMode(DX_BLENDMODE_NOBLEND, 255); } void Efect::drawPattern_1() { for (int i = 0; i < 10; i++) { SetDrawBlendMode(DX_BLENDMODE_ALPHA, (int)value); DrawRotaGraph(pos[i].x, pos[i].y, (int)size, 0, hImage[efectKind], true); SetDrawBlendMode(DX_BLENDMODE_NOBLEND, 255); } } <file_sep>#pragma once #include "../Library/gameObject.h" #include "shotManager.h" #include "vector2.h" #include "efectManager.h" #include "enemyBase.h" #include "enemyManager.h" #include "enemyBarrageManager.h" #include "enemyBarrageManager.h" #include "itemManager.h" class Player : public GameObject { public: Player(SceneBase* scene); ~Player(); void Update(); void Draw(); void Move(); //移動 void Shot(); //ショット void Resurrection(); //復活 void Collision(); //当たり判定 Vector2 GetPosition(); int score; //スコア private: Vector2 position; //プレイヤーの画像の座標 Vector2 corePosition; //プレイヤーの当たり判定の座標 int hPlayerImage; //自機の画像ファイルのハンドラ int hPlayerCoreImage; //自機の当たり判定の画像ファイルのハンドラ float shotCoolTime; //ショットのクールタイム bool exist; //生きてたらtrue float resurrectionCoolTime; //復活するまでの時間 int invincibleTime; //無敵時間 int remainingPlayer; //残機 int shotPower; //自機の攻撃力 int bomb; //ボムの数 EnemyBase* e; EnemyManager* eM; EfectManager* efM; ItemManager* itM; enum State { INVICIBLE, //無敵 ALIVE, //生きている DEAD, //死んでいる }; State state; public: Vector2 pubPos; };<file_sep>#include "enemyManager.h" #include "furball.h" #include "playScene.h" #include "vShaped_BOSS.h" #include "vShaped_MINIONS.h" EnemyManager::EnemyManager(SceneBase * scene) : GameObject(scene) { enemies.clear(); } EnemyManager::~EnemyManager() { for (auto it = enemies.begin(); it != enemies.end(); ) { delete (*it); it = enemies.erase(it); } enemies.clear(); } void EnemyManager::Update() { PlayScene* scene = dynamic_cast<PlayScene*>(GetScene()); if (scene != nullptr && !scene->CanMove()) return; // ゲームを開始する前など、動けない時は、Updateを行わない for (auto it = enemies.begin(); it != enemies.end();) { (*it)->Update(); if ((*it)->IsDestroy()) { // 削除が要求されたので delete (*it); it = enemies.erase(it); } else it++; } } void EnemyManager::Draw() { for (auto e : enemies) { e->Draw(); } } void EnemyManager::Create(ENEMY_TYPE type, int x, int y, int cnt, int pattern, float speed, int barraeTime, int maxBullet, int barrageKind, int color, int hp, int bulletKind, int waitTime, int stagnationTime, int itemKind) { EnemyBase* e = nullptr; switch (type) { case FURBALL: e = new Furball(GetScene(), x, y, cnt, pattern, speed, barraeTime, maxBullet, barrageKind, color, hp, bulletKind, waitTime, stagnationTime, itemKind); break; case FAIRY: break; case VSHAPED: //親分 e = new VShaped_BOSS(GetScene(), x, y, cnt, pattern, speed, barraeTime, maxBullet, barrageKind, color, hp, bulletKind, waitTime, stagnationTime, itemKind); enemies.emplace_back(e); EnemyBase* boss; boss = e; //子分 e = new VShaped_MINIONS(GetScene(), x - 30, y - 30, cnt, 1, speed, barraeTime, maxBullet, barrageKind, color, hp, bulletKind, waitTime, stagnationTime, itemKind, boss); if (e != nullptr) enemies.emplace_back(e); e = new VShaped_MINIONS(GetScene(), x - 60, y - 60, cnt, 2, speed, barraeTime, maxBullet, barrageKind, color, hp, bulletKind, waitTime, stagnationTime, itemKind, boss); if (e != nullptr) enemies.emplace_back(e); e = new VShaped_MINIONS(GetScene(), x + 30, y - 30, cnt, 3, speed, barraeTime, maxBullet, barrageKind, color, hp, bulletKind, waitTime, stagnationTime, itemKind, boss); if (e != nullptr) enemies.emplace_back(e); e = new VShaped_MINIONS(GetScene(), x + 60, y - 60, cnt, 4, speed, barraeTime, maxBullet, barrageKind, color, hp, bulletKind, waitTime, stagnationTime, itemKind, boss); break; } if (e != nullptr) enemies.emplace_back(e); } EnemyBase * EnemyManager::Collision(Vector2 center, float radius) const { for (auto e : enemies) { if (e->Collision(center, radius)) return e; } return nullptr; } <file_sep>#pragma once #include "vector2.h" #include "../Library/gameObject.h" class Field : public GameObject { public: Field(SceneBase* scene); ~Field(); void Start() override; void Draw() override; };<file_sep>#pragma once #include "..//Library/gameObject.h" #include "enemyBarrage.h" #include "player.h" class EnemyBarrage; class EnemyBarrageManager : public GameObject { public: EnemyBarrageManager(SceneBase* scene); ~EnemyBarrageManager(); void Update() override; void Draw() override; void Create(Vector2 pos, double _base_angle,int _bulletMax, int _bulletKind, int _bulletColor, float _speed); void GetPlayerPosition(Vector2 pos); bool Collision(Vector2 center, float radius); private: std::list<EnemyBarrage*> barrages; Vector2 playerPosition; };<file_sep>#include "board.h" #include <assert.h> Board::Board(SceneBase* _scene) : GameObject (_scene) { hImage = LoadGraph("data\\texture\\board.png"); assert(hImage > 0); } Board::~Board() { } void Board::Update() { } void Board::Draw() { DrawGraph(240, 0, hImage, true); } <file_sep>#pragma once #include "..//Library/gameObject.h" #include "vector2.h" class ItemBase : public GameObject { public: ItemBase(SceneBase* _scene) {}; virtual ~ItemBase() {}; virtual void Update() override {}; virtual void Draw() override {}; virtual bool Collision(Vector2 center, float radius) { return false; }; int itemKind; };<file_sep>#pragma once #include "..//Library/gameObject.h" class BackGround : public GameObject { public: BackGround(SceneBase* scene); ~BackGround(); void Update(); void Draw(); private: int hImage; const float X = 310; float firstY, secondY; };<file_sep>#pragma once #include "itemBase.h" class PowerupItem : public ItemBase { public: PowerupItem(SceneBase* _scene, Vector2 _position); ~PowerupItem(); void Update() override; void Draw() override; bool Collision(Vector2 center, float radius) override; private: Vector2 position; Vector2 velocity; int hImage; bool exist; int cnt; };
5a2420d502241a5547bc53032bdab5e6252f1253
[ "C", "C++" ]
39
C++
yoshikihosono/syukatuProject
78fd375876c06087b0dd27b43dc3c7ccd14556e0
aa5ae329b51ef16b3d9ddebb6abe04cd765132a0
refs/heads/master
<repo_name>FilBot3/knife_use<file_sep>/lib/chef/knife/use.rb # # # require 'chef/knife' module ConfigManage class UseConfig < Chef::Knife deps do # require 'yaml' end banner "knife use config CONFIG_VALUE (options)" option :knife_config_file, :short => "-C VALUE", :long => "--Conf VALUE", :description => "The config to load" def run custom_knife = {} # Check if --Conf was set, if not, use default $HOME/.chef/use_config.yml read_config = "#{ENV['HOME']}/.chef/use_config.yml" #config[:knife_config_file] or # Read the config file yaml_config = YAML.load_file( read_config ) # assign path to variable if it matches what is in the config and ARGV[2] yaml_config.each do |key, value| custom_knife = value if key == ARGV[2] end # Read the existing $HOME/.chef/knife.rb and replace the config line with our new config old_knife_config = File.read("#{ENV['HOME']}/.chef/knife.rb") # Sub the old line out for the new config new_knife_config = old_knife_config.gsub(/Chef::Config.from_file\(.*\)/, "Chef::Config.from_file(\"#{custom_knife['location']}\")") # Write the knife.rb file File.open("#{ENV['HOME']}/.chef/knife.rb", "w") { |file| file.puts new_knife_config } end end end<file_sep>/lib/knife_use.rb require "knife_use/version" module KnifeUse # Your code goes here... end <file_sep>/Rakefile require "bundler/gem_tasks" #require "rspec/core/rake_task" #require "minitest/testtask" #RSpec::Core::RakeTask.new(:spec) do |t| # t.pattern = 'spec/**/*_spec.rb' # t.libs.push 'spec' #end #Rake::TestTask.new do |t| # t.pattern = 'test/**/*_test.rb' # t.libs.push 'test' #end <file_sep>/README.md # Knife Use This is a knife plugin to allow a user to have multiple knife.rb files and use it similar to RVM, or PIK. ## Installation Add this line to your application's Gemfile: ```ruby gem 'knife_use' ``` And then execute: $ bundle Or install it yourself as: $ gem install knife_use ## Usage Create a standard knife.rb in your $HOME/.chef directory. Inside that knife.rb, place the following line, as it is required: ``` Chef::Config.from_file("/home/user/.chef/knife.rb") ``` There must be an existing file there in order for Chef to utilize this plugin. Inside the $HOME/.chef directory, add the use_config.yml from the gem's example directory, and add the locations of the custom knife.rb files. The way this plugin works, it allows the $HOME/.chef/knife.rb to have global defaults, as it only changes the Chef::Config.from_file line. ## Development After checking out the repo, run `bin/setup` to install dependencies. Then, run `bin/console` for an interactive prompt that will allow you to experiment. To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release` to create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org). ## Contributing 1. Fork it ( https://github.com/predatorian3/knife_use/fork ) 2. Create your feature branch (`git checkout -b my-new-feature`) 3. Commit your changes (`git commit -am 'Add some feature'`) 4. Push to the branch (`git push origin my-new-feature`) 5. Create a new Pull Request ## I have to admit I realize that this can be easily solved by having multiple chef-repo directories with the custom knife.rb files.<file_sep>/lib/chef/knife/list.rb # # # require 'chef/knife' module ConfigManage class UseList < Chef::Knife deps do # require 'yaml' end banner "knife use list (options)" option :knife_config_file, :short => "-C VALUE", :long => "--Conf VALUE", :description => "The config to load" def run # Look to see if --Conf is filled out if not fileld out, then set to default $HOME/.chef/use_config.yml read_config = "#{ENV['HOME']}/.chef/use_config.yml" #config[:knife_config_file] or # Read teh config file yaml_config = YAML.load_file( read_config ) # Display each entry in the config file yaml_config.each do |key, value| puts key.to_sym end end end end
5c3eb4667f2b1f3460070c4b6dc748599eaed79a
[ "Markdown", "Ruby" ]
5
Ruby
FilBot3/knife_use
058b6608386fd5a98652546d789495a7ce0a8926
226100f398afe0cae9cad9806ce46cae17ebf6eb
refs/heads/master
<file_sep>import tweepy from tweepy import OAuthHandler import json from collections import Counter import sys import config #------------------ #basic code to get latest tweets, issue of response 420 auth = OAuthHandler(config.consumer_key, config.consumer_secret) auth.set_access_token(config.access_token, config.access_secret) api = tweepy.API(auth) counter = Counter() with open("data/treatment_definitons.txt", "r") as fh: lines = fh.readlines() lines += ["medicine", "treatment", "cure", "drug"] for line in lines: treatments = line.strip().split(",") name = treatments[0] print("==== {} ===".format(name)) for treatment in treatments: sys.stderr.write("Treatment {}\n".format(treatment)) searchQuery = 'tinnitus ' + treatment # this is what we're searching for maxTweets = 10000000 # Some arbitrary large number tweetsPerQry = 100 # this is the max the API permits # If results only below a specific ID are, set max_id to that ID. # else default to no upper limit, start from the most recent tweet matching the search query. max_id = -1 tweetCount = 0 while tweetCount < maxTweets: try: if (max_id <= 0): new_tweets = api.search(q=searchQuery, count=tweetsPerQry) else: new_tweets = api.search(q=searchQuery, count=tweetsPerQry, max_id=str(max_id - 1)) if not new_tweets: sys.stderr.write("No more tweets found\n") break for tweet in new_tweets: print(json.dumps(tweet._json) + '\n') tweetCount += len(new_tweets) if len(new_tweets) < tweetsPerQry: sys.stderr.write("No more tweets found (D)\n") break sys.stderr.write("Downloaded {0} tweets\n".format(tweetCount)) max_id = new_tweets[-1].id except tweepy.TweepError as e: # Just exit if any error sys.stderr.write("some error : " + str(e) + "\n") break counter[name] += tweetCount sys.stderr.write("Downloaded {0} tweets for query {1}\n".format(tweetCount, searchQuery)) for treatment, count in counter.items(): sys.stderr.write("{}: {}\n".format(treatment, count)) <file_sep>import tweepy from tweepy import OAuthHandler import json import sys import config auth = OAuthHandler(config.consumer_key, config.consumer_secret) auth.set_access_token(config.access_token, config.access_secret) api = tweepy.API(auth) searchQuery = '<PASSWORD>' # this is what we're searching for maxTweets = 10000000 # Some arbitrary large number tweetsPerQry = 100 # this is the max the API permits # If results only below a specific ID are, set max_id to that ID. # else default to no upper limit, start from the most recent tweet matching the search query. max_id = -1 tweetCount = 0 while tweetCount < maxTweets: try: if (max_id <= 0): new_tweets = api.search(q=searchQuery, count=tweetsPerQry) else: new_tweets = api.search(q=searchQuery, count=tweetsPerQry, max_id=str(max_id - 1)) if not new_tweets: sys.stderr.write("No more tweets found\n") break for tweet in new_tweets: print(json.dumps(tweet._json) + '\n') tweetCount += len(new_tweets) # if len(new_tweets) < tweetsPerQry: # sys.stderr.write("No more tweets found (D)\n") # break sys.stderr.write("Downloaded {0} tweets\n".format(tweetCount)) max_id = new_tweets[-1].id except tweepy.TweepError as e: # Just exit if any error sys.stderr.write("some error : " + str(e) + "\n") break sys.stderr.write("Downloaded {0} tweets for query {1}\n".format(tweetCount, searchQuery)) <file_sep>consumer_key = #FILL IN consumer_secret = #FILL IN access_token = #FILL IN access_secret = #FILL IN
1f4fef91e20b89e8fe01260aa894f4207b31d450
[ "Python" ]
3
Python
sourabhDandage/Talk3_extension
c9f8cfcf17a31fdd12520f07dd7e3e44428af7f3
819105b41149e4b0956c7b592883b2eb0f6131fa
refs/heads/master
<file_sep>import styles from './SeekApp.less'; import React, { PropTypes } from 'react'; import classnames from 'classnames'; export default function SeekApp({ fullScreen, children }) { const className = classnames({ [styles.root]: true, [styles.fullScreen]: fullScreen }); return ( <div className={className}> {children} </div> ); } SeekApp.propTypes = { fullScreen: PropTypes.bool, children: PropTypes.node }; SeekApp.defaultProps = { fullScreen: false }; <file_sep>import React from 'react'; import { Route, IndexRoute } from 'react-router'; import App from 'App/App'; import Home from 'Home/Home'; import Buttons from 'Buttons/Buttons'; import TextFields from 'TextFields/TextFields'; import Autosuggest from 'Autosuggest/Autosuggest'; import Icons from 'Icons/Icons'; import Typography from 'Typography/Typography'; import Textarea from 'Textarea/Textarea'; export default ( <Route path="/" component={App}> <IndexRoute component={Home} /> <Route path="/buttons" component={Buttons} /> <Route path="/textfields" component={TextFields} /> <Route path="/autosuggest" component={Autosuggest} /> <Route path="/textarea" component={Textarea} /> <Route path="/icons" component={Icons} /> <Route path="/typography" component={Typography} /> </Route> ); <file_sep>#!/bin/sh set -e PRE_COMMIT=.git/hooks/pre-commit cat > $PRE_COMMIT <<- EOM #!/bin/sh if [ "\$SKIP_LINT" != "true" ]; then $(which npm) run lint fi EOM chmod +x $PRE_COMMIT
2242af9df415dc30be4b863136aad9c4a75d861e
[ "JavaScript", "Shell" ]
3
JavaScript
georgespyropoulos/seek-style-guide
31009ff6ec67bab2ccfc048addabf0d96a18f534
68907fa6b7b5ce5aa1c5b0023f0f9848d35a54f3
refs/heads/master
<repo_name>CoolHandDev/go-vue-embedded<file_sep>/go.mod module github.com/CoolHandDev/go-vue-embedded go 1.14 require github.com/markbates/pkger v0.16.0 <file_sep>/main.go package main import ( "fmt" "log" "net/http" "github.com/markbates/pkger" ) func main() { mux := http.NewServeMux() fs := http.FileServer(pkger.Dir("/front-end/dist/")) mux.Handle("/", fs) srv := &http.Server{ Addr: "127.0.0.1:4022", Handler: mux, } fmt.Println("serving at", srv.Addr) err := srv.ListenAndServe() if err != nil { log.Fatal(err) } } func handleDefault(w http.ResponseWriter, r *http.Request) { } <file_sep>/README.md # Description Example of embedding a Vue application inside a Go binary. Here we explore how a project might be structured and built. The Vue application is bootstrapped using Vue CLI (v3). ## Vue Development is done in the /front-end directory ## Go Development is done in the root directory # Build Process Run `make` to start the build process ## Vue Vue was bootstrapped using the the Vue cli. The makefile target, build-vue-app, runs `npm run build` and the resulting output is placed in the `front-end/dist` directory ## Go [Packr](https://github.com/gobuffalo/packr) is used to embedd the front-end assets to the Go binary. In `main.go` the line `box := packr.NewBox("./front-end/dist")` refers to the distribution directory of the Vue front-end. The build-go makefile target will generate the Go source code containing the front-end assets and then run the Go build to generate the static binary executable. # How to run the application Run the `go-vue-embedded` binary. Open up the browser to http://127.0.0.1:4022/#/. The `#` is due to Vue router's default [mode](https://router.vuejs.org/guide/essentials/history-mode.html). # Conclusion Embedding a Vue application in Go is possible and straightforward thanks to [Pkger](https://github.com/markbates/pkger). <file_sep>/Makefile all: build-vue-app build-go .PHONY: build-vue-app build-vue-app: npm run --prefix front-end build .PHONY: build-go build-go: pkger go build -o go-vue-embedded .
85aea9df2afa2ab1778f7d67adfebb82a238a243
[ "Go", "Makefile", "Go Module", "Markdown" ]
4
Go Module
CoolHandDev/go-vue-embedded
10163a7373e3fd5ff3e8c172fb304d9265bd7454
697ecb7a24aee7325d2daf69bb382e630ba3cec6
refs/heads/master
<repo_name>coldinsomnia/04_BattleTank<file_sep>/BattleTank/Source/BattleTank/TankBarrel.cpp // Fill out your copyright notice in the Description page of Project Settings. #include "TankBarrel.h" #include "Engine/World.h" #include "Components/StaticMeshComponent.h" #include "Components/SceneComponent.h" void UTankBarrel::Elevate(float RelativeSpeed) { // Move the barrel the right amount this frame // Given a max elevation speed, and the frame time auto ClampedRelativeSpeed = FMath::Clamp<float>(RelativeSpeed, -1.0f, 1.0f); auto ElevationChange = ClampedRelativeSpeed * MaxDegreesPerSecond * GetWorld()->DeltaTimeSeconds; auto RawNewElevation = RelativeRotation.Pitch + ElevationChange; auto ClampedElevation = FMath::Clamp<float>(RawNewElevation, MinimumElevation, MaximumElevation); SetRelativeRotation(FRotator(ClampedElevation, 0, 0)); }<file_sep>/BattleTank/Source/BattleTank/Projectile.h // Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "Engine/World.h" #include "GameFramework/Actor.h" #include "GameFramework/ProjectileMovementComponent.h" #include "PhysicsEngine/RadialForceComponent.h" #include "Particles/ParticleSystemComponent.h" #include "Components/PrimitiveComponent.h" #include "TimerManager.h" #include "Projectile.generated.h" UCLASS() class BATTLETANK_API AProjectile : public AActor { GENERATED_BODY() public: // Sets default values for this actor's properties AProjectile(); void Launch(float Speed); protected: // Called when the game starts or when spawned virtual void BeginPlay() override; public: // Called every frame virtual void Tick(float DeltaTime) override; private: UProjectileMovementComponent* ProjectileMovementComponent = nullptr; UPROPERTY(VisibleAnywhere) UStaticMeshComponent* CollisionMesh = nullptr; UPROPERTY(VisibleAnywhere) UParticleSystemComponent* LaunchBlast = nullptr; UPROPERTY(VisibleAnywhere) UParticleSystemComponent* ImpactBlast = nullptr; UPROPERTY(VisibleAnywhere) URadialForceComponent* ExplosionForce = nullptr; // Blueprint callable, no implementation needed UFUNCTION(BlueprintCallable, Category = "Collision") void OnHit(UPrimitiveComponent* HitComponent, AActor* OtherActor, UPrimitiveComponent* OtherComponent, FVector NormalImpulse, const FHitResult& Hit); UFUNCTION(BlueprintCallable, Category = "Collision") void OnTimerExpire(); UPROPERTY(EditDefaultsOnly, Category = "Setup") float DestroyDelay = 10.0f; }; <file_sep>/README.md # 04_BattleTank a game about tanks mate :)
5b302b7bb8855ccbb55623a53cd5852aded13c8c
[ "Markdown", "C++" ]
3
C++
coldinsomnia/04_BattleTank
b085b76d71a4bec9786d1cc4a620d9fa4c0fccea
39e3f9e7af60b61f5834564286e633cea072e50a
refs/heads/master
<repo_name>deeeki/bremen<file_sep>/spec/bremen/base_spec.rb $:.unshift(File.expand_path('../../', __FILE__)) require 'spec_helper' envfile = File.expand_path('../../../.env', __FILE__) if File.exists?(envfile) File.open(envfile, 'r').each do |line| key, val = line.chomp.split('=', 2) ENV[key] = val end end SITES = ['Youtube', 'Mixcloud', 'Nicovideo'] SITES << 'Soundcloud' if ENV['SOUNDCLOUD_CLIENT_ID'] describe Bremen::Base do describe '.search' do SITES.each do |site| describe site do let(:klass){ Bremen.const_get(site) } describe 'pagination' do let(:params){ {keyword: 'kyary pamyu pamyu', limit: 1} } let(:track_page1){ klass.search(params.merge(page: 1)).first } let(:track_page2){ klass.search(params.merge(page: 2)).first } it 'first tracks on each pages are different' do track_page1.uid.wont_equal track_page2.uid end end describe 'no result keyword' do let(:params){ {keyword: 'kyarolinecharonpropkyarypamyupamyu', limit: 1 } } subject{ klass.search(params) } it 'returns empty array' do subject.must_be_empty end end end end end end <file_sep>/lib/bremen.rb require 'bremen/version' require 'bremen/youtube' require 'bremen/soundcloud' require 'bremen/mixcloud' require 'bremen/nicovideo' module Bremen end <file_sep>/lib/bremen/author.rb module Bremen class Author attr_accessor :uid, :url, :name, :thumbnail_url def initialize attrs = {} attrs.each do |key, value| send("#{key}=", value) if respond_to?(key) end end end end <file_sep>/lib/bremen/youtube.rb require 'json' require 'bremen/base' module Bremen class Youtube < Bremen::Base BASE_URL = 'http://gdata.youtube.com/feeds/api/videos/' self.default_options = { order: 'published', #relevance/published/viewCount/rating limit: 25, page: 1, category: 'Music', tag: '', } class << self def build_query options = {} super(options.merge(alt: 'json')) end def find_url uid_or_url uid = uid_or_url.scan(%r{[?&]v=(.{11})}).flatten.first || uid_or_url "#{BASE_URL}#{uid}?#{build_query}" end def search_url options = {} options = default_options.merge(options) query = { vq: options[:keyword], orderby: options[:order], :"max-results" => options[:limit], :"start-index" => options[:page], } "#{BASE_URL}-/#{options[:category]}/#{options[:tag]}/?#{build_query(query)}" end def from_api hash = {} uid = hash['id']['$t'].sub('http://gdata.youtube.com/feeds/api/videos/', '') author = hash['author'].first new({ uid: uid, url: "http://www.youtube.com/watch?v=#{uid}", title: hash['title']['$t'], author: Bremen::Author.new({ uid: author.key?('yt$userId') ? author['yt$userId']['$t'] : nil, url: author['uri']['$t'].sub('gdata.youtube.com/feeds/api/users/', 'www.youtube.com/channel/UC'), name: author['name']['$t'], }), length: hash['media$group']['yt$duration']['seconds'].to_i, thumbnail_url: hash['media$group']['media$thumbnail'][0]['url'], created_at: Time.parse(hash['published']['$t']).utc, updated_at: Time.parse(hash['updated']['$t']).utc, }) end private def convert_singly response from_api(JSON.parse(response)['entry']) end def convert_multiply response feed = JSON.parse(response)['feed'] return [] unless feed['entry'] feed['entry'].map{|t| from_api(t) } end end end end <file_sep>/lib/bremen/request.rb require 'open-uri' require 'cgi' module Bremen module Request def get url open(url).read end def build_query options = {} options.to_a.map{|o| "#{o[0]}=#{CGI.escape(o[1].to_s)}" }.join('&') end end end <file_sep>/spec/bremen/youtube_spec.rb $:.unshift(File.expand_path('../../', __FILE__)) require 'spec_helper' describe Bremen::Youtube do describe '.find_url' do subject{ Bremen::Youtube.find_url(uid_or_url) } describe 'given id' do let(:uid_or_url){ 'XXXXXXXXXXX' } it 'generate' do subject.must_equal 'http://gdata.youtube.com/feeds/api/videos/XXXXXXXXXXX?alt=json' end end describe 'given url' do let(:uid_or_url){ 'http://www.youtube.com/watch?v=XXXXXXXXXXX' } it 'generate' do subject.must_equal 'http://gdata.youtube.com/feeds/api/videos/XXXXXXXXXXX?alt=json' end end end describe '.search_url' do subject{ Bremen::Youtube.search_url(params) } describe 'only keyword' do let(:params){ {keyword: 'searchword'} } it 'generate' do subject.must_equal 'http://gdata.youtube.com/feeds/api/videos/-/Music//?vq=searchword&orderby=published&max-results=25&start-index=1&alt=json' end end describe 'full params' do let(:params){ {keyword: 'searchword', order: 'relevance', limit: 10, page: 2, category: 'Entertainment', tag: 'game'} } it 'generate' do subject.must_equal 'http://gdata.youtube.com/feeds/api/videos/-/Entertainment/game/?vq=searchword&orderby=relevance&max-results=10&start-index=2&alt=json' end end end describe '.convert_singly' do subject{ Bremen::Youtube.send(:convert_singly, response) } let(:response){ fixture('youtube_single.json') } it 'convert successfully' do subject.title.must_equal 'Title' subject.created_at.zone.must_equal 'UTC' end end describe '.convert_multiply' do subject{ Bremen::Youtube.send(:convert_multiply, response) } let(:response){ fixture('youtube_multi.json') } it 'convert successfully' do subject.first.title.must_equal 'Title' subject.first.created_at.zone.must_equal 'UTC' end end end <file_sep>/README.md # Bremen [![Build Status](https://travis-ci.org/deeeki/bremen.png)](https://travis-ci.org/deeeki/bremen) [![Coverage Status](https://coveralls.io/repos/deeeki/bremen/badge.png)](https://coveralls.io/r/deeeki/bremen) [![Code Climate](https://codeclimate.com/github/deeeki/bremen.png)](https://codeclimate.com/github/deeeki/bremen) [![Gem Version](https://badge.fury.io/rb/bremen.png)](http://badge.fury.io/rb/bremen) **Bremen** provides common search interface for some music websites. it supports YouTube, SoundCloud, MixCloud and Nicovideo ## Installation Add this line to your application's Gemfile: gem 'bremen' And then execute: $ bundle Or install it yourself as: $ gem install bremen ## Setting As far as SoundCloud concerned, you need to set your app's client id before using. ```ruby Bremen::Soundcloud.client_id = 'your_client_id' ``` Alternately, you can set 'SOUNDCLOUD_CLIENT_ID' environment variable. ## Usage ### Retrieving a single track call `.find` method with uid(unique key) or url. ```ruby Bremen::Youtube.find('XXXXXXXXXXX') Bremen::Youtube.find('http://www.youtube.com/watch?v=XXXXXXXXXXX') Bremen::Soundcloud.find('1111111') Bremen::Soundcloud.find('http://soundcloud.com/author/title') Bremen::Mixcloud.find('/author/title/') Bremen::Mixcloud.find('http://www.mixcloud.com/author/title/') Bremen::Nicovideo.find('sm1111111') Bremen::Nicovideo.find('http://www.nicovideo.jp/watch/sm1111111') ``` ### Retrieving multiple tracks call `.search` method with keyword. ```ruby Bremen::Youtube.search(keyword: 'Perfume') ``` #### Optional params You can add optional parameters for filtering. But it doesn't support all official API's filters. ```ruby Bremen::Youtube.search(keyword: 'KyaryPamyuPamyu', order: 'relevance', limit: 10) ``` ### Track object Retrieving methods return Track object(s). attribute |type |description | -------------|-------------|--------------------------| uid |String |unique key for each site | url |String | | title |String | | author |Author Object|uid/url/name/thumbnail_url| length |Integer |duration of track | thumbnail_url|String |thumbnail image | created_at |Time |released datetime | updated_at |Time |modified datetime | ## API references - [Reference Guide: Data API Protocol - YouTube — Google Developers](https://developers.google.com/youtube/2.0/reference#Searching_for_videos) - [Docs - API - Reference - SoundCloud Developers](http://developers.soundcloud.com/docs/api/reference#tracks) - [API documentation | Mixcloud](http://www.mixcloud.com/developers/documentation/#search) ## Supported versions - Ruby 1.9.3 or higher ## Contributing 1. Fork it 2. Create your feature branch (`git checkout -b my-new-feature`) 3. Commit your changes (`git commit -am 'Add some feature'`) 4. Push to the branch (`git push origin my-new-feature`) 5. Create new Pull Request <file_sep>/spec/bremen/nicovideo_spec.rb $:.unshift(File.expand_path('../../', __FILE__)) require 'spec_helper' describe Bremen::Nicovideo do describe '.find_url' do subject{ Bremen::Nicovideo.find_url(uid_or_url) } describe 'given id' do let(:uid_or_url){ 'sm1111111' } it 'generate' do subject.must_equal 'http://www.nicovideo.jp/watch/sm1111111' end end describe 'given url' do let(:uid_or_url){ 'http://www.nicovideo.jp/watch/sm1111111' } it 'generate' do subject.must_equal 'http://www.nicovideo.jp/watch/sm1111111' end end end describe '.search_url' do subject{ Bremen::Nicovideo.search_url(params) } describe 'only keyword' do let(:params){ {keyword: 'searchword'} } it 'generate' do subject.must_equal 'http://www.nicovideo.jp/search/searchword?page=1&sort=f&order=d&f_range=&l_range=&opt_md=' end end describe 'full params' do let(:params){ {keyword: 'searchword', page: 2, sort: 'n', order: 'a', within: 3, length: 2, downloadable: 1} } it 'generate' do subject.must_equal 'http://www.nicovideo.jp/search/searchword?page=2&sort=n&order=a&f_range=3&l_range=2&opt_md=1' end end end describe '.convert_singly' do subject{ Bremen::Nicovideo.send(:convert_singly, response) } let(:response){ fixture('nicovideo_single.html') } it 'convert successfully' do subject.title.must_equal 'Title' subject.created_at.zone.must_equal 'UTC' end end describe '.convert_multiply' do subject{ Bremen::Nicovideo.send(:convert_multiply, response) } let(:response){ fixture('nicovideo_multi.html') } it 'convert successfully' do subject.first.title.must_equal 'Title' subject.first.created_at.zone.must_equal 'UTC' end end end <file_sep>/lib/bremen/nicovideo.rb require 'json' require 'bremen/base' module Bremen class Nicovideo < Bremen::Base BASE_URL = 'http://www.nicovideo.jp/' self.default_options = { keyword: '', page: 1, sort: 'f', #n(newer commented)/v(viewed)/r(most commented)/m(listed)/f(uploaded)/l(duration) order: 'd', #a(asc)/d(desc) within: '', #1(24h)/2(1w)/3(1m) length: '', #1(-5min)/2(20min-) downloadable: '', #1(music downloadable) } class << self def find_url uid_or_url unless uid_or_url.include?('www.nicovideo.jp') "#{BASE_URL}watch/#{uid_or_url}" else uid_or_url end end def search_url options = {} options = default_options.merge(options) query = { page: options[:page], sort: options[:sort], order: options[:order], f_range: options[:within], l_range: options[:length], opt_md: options[:downloadable], } "#{BASE_URL}search/#{CGI.escape(options[:keyword])}?#{build_query(query)}" end private def convert_singly response uid = response.scan(%r{<link rel="canonical" href="/watch/([^"]+)">}).flatten.first created_at = Time.parse(response.scan(%r{<meta property="video:release_date" content="(.+)">}).flatten.first.to_s).utc new({ uid: uid, url: "#{BASE_URL}watch/#{uid}", title: CGI.unescape(response.scan(%r{<meta property="og:title" content="(.+)">}).flatten.first.to_s), author: Bremen::Author.new({ name: response.scan(%r{<strong itemprop="name">(.+)</strong>}).flatten.first, }), length: response.scan(%r{<meta property="video:duration" content="(\d+)">}).flatten.first.to_i, thumbnail_url: response.scan(%r{<meta property="og:image" content="(.+)">}).flatten.first, created_at: created_at, updated_at: created_at, }) end def convert_multiply response return [] if response.scan(%r{<div class="videoList01">}).flatten.first response.scan(%r{<li class="item" [^>]+ data-enable-uad="1">\n(.*?)\n </li>}m).flatten.map do |html| uid = html.scan(%r{<div class="itemThumb" [^>]+ data-id="(.+)">}).flatten.first min, sec = html.scan(%r{<span class="videoLength">([\d:]+)</span></div>}).flatten.first.to_s.split(':') created_at = Time.parse(html.scan(%r{<span class="time">(.+:\d\d)</span>}).flatten.first.to_s.gsub(/\xE5\xB9\xB4|\xE6\x9C\x88|\xE6\x97\xA5/n, '')).utc new({ uid: uid, url: "#{BASE_URL}watch/#{uid}", title: CGI.unescape(html.scan(%r{<p class="itemTitle">\n\s+<a [^>]+>(.+)</a>}).flatten.first.to_s), length: min.to_i * 60 + sec.to_i, thumbnail_url: html.scan(%r{<img [^>]+data-original="([^"]+)"[^>]*data-thumbnail [^>]+/?>}).flatten.first, created_at: created_at, updated_at: created_at, }) end end end end end <file_sep>/spec/bremen/mixcloud_spec.rb $:.unshift(File.expand_path('../../', __FILE__)) require 'spec_helper' describe Bremen::Mixcloud do describe '.find_url' do subject{ Bremen::Mixcloud.find_url(uid_or_url) } describe 'given id' do let(:uid_or_url){ '/author/permalink/' } it 'generate' do subject.must_equal 'http://api.mixcloud.com/author/permalink/' end end describe 'given url' do let(:uid_or_url){ 'http://www.mixcloud.com/author/permalink/' } it 'generate' do subject.must_equal 'http://api.mixcloud.com/author/permalink/' end end end describe '.search_url' do subject{ Bremen::Mixcloud.search_url(params) } describe 'only keyword' do let(:params){ {keyword: 'searchword'} } it 'generate' do subject.must_equal 'http://api.mixcloud.com/search/?q=searchword&limit=20&offset=0&type=cloudcast' end end describe 'full params' do let(:params){ {keyword: 'searchword', limit: 10, page: 2} } it 'generate' do subject.must_equal 'http://api.mixcloud.com/search/?q=searchword&limit=10&offset=10&type=cloudcast' end end end describe '.convert_singly' do subject{ Bremen::Mixcloud.send(:convert_singly, response) } let(:response){ fixture('mixcloud_single.json') } it 'convert successfully' do subject.title.must_equal 'Title' subject.created_at.zone.must_equal 'UTC' end end describe '.convert_multiply' do subject{ Bremen::Mixcloud.send(:convert_multiply, response) } let(:response){ fixture('mixcloud_multi.json') } it 'convert successfully' do subject.first.title.must_equal 'Title' subject.first.created_at.zone.must_equal 'UTC' end end end <file_sep>/spec/spec_helper.rb if ENV['CI'] && RUBY_VERSION.start_with?('2.1') require 'coveralls' require 'codeclimate-test-reporter' SimpleCov.formatter = SimpleCov::Formatter::MultiFormatter[ Coveralls::SimpleCov::Formatter, CodeClimate::TestReporter::Formatter ] SimpleCov.start 'test_frameworks' end require 'minitest/autorun' require 'minitest/pride' require 'bremen' def fixture path File.read("#{File.dirname(__FILE__)}/fixtures/#{path}") end <file_sep>/lib/bremen/base.rb require 'bremen/track' require 'bremen/request' module Bremen class Base include Track extend Request class << self attr_accessor :default_options def find uid_or_url convert_singly(get(find_url(uid_or_url))) end def search options = {} convert_multiply(get(search_url(options))) end #abstract methods def find_url uid_or_url; end def search_url options = {}; end private def convert_singly response; end def convert_multiply response; end end end end <file_sep>/lib/bremen/track.rb require 'bremen/author' module Bremen module Track attr_accessor :uid, :url, :title, :author, :thumbnail_url, :length, :created_at, :updated_at def initialize attrs = {} attrs.each do |key, value| send("#{key}=", value) if respond_to?(key) end end end end <file_sep>/lib/bremen/soundcloud.rb require 'json' require 'bremen/base' module Bremen class Soundcloud < Bremen::Base BASE_URL = 'http://api.soundcloud.com/' self.default_options = { keyword: '', order: 'created_at', #created_at/hotness limit: 50, page: 1, filter: '', #(all)/public/private/streamable/downloadable } class << self attr_accessor :client_id def build_query options = {} self.client_id ||= ENV['SOUNDCLOUD_CLIENT_ID'] raise %Q{"#{self.name}.client_id" must be set} unless client_id super(options.merge(client_id: client_id)) end def find_url uid_or_url if uid_or_url.to_s =~ %r{\A\d+\Z} "#{BASE_URL}tracks/#{uid_or_url}.json?#{build_query}" else "#{BASE_URL}resolve.json?#{build_query({url: uid_or_url})}" end end def search_url options = {} options = default_options.merge(options) query = { q: options[:keyword], order: options[:order], limit: options[:limit], offset: options[:limit] * (options[:page] - 1), filter: options[:filter], } "#{BASE_URL}tracks.json?#{build_query(query)}" end def from_api hash = {} created_at = Time.parse(hash['created_at']).utc new({ uid: hash['id'].to_s, url: hash['permalink_url'], title: hash['title'], author: Bremen::Author.new({ uid: hash['user']['id'].to_s, url: hash['user']['permalink_url'], name: hash['user']['username'], thumbnail_url: hash['user']['avatar_url'].sub(%r{\?.*}, ''), }), length: (hash['duration'].to_i / 1000).round, thumbnail_url: hash['artwork_url'] ? hash['artwork_url'].sub(%r{\?.*}, '') : nil, created_at: created_at, updated_at: created_at, }) end private def convert_singly response from_api(JSON.parse(response)) end def convert_multiply response JSON.parse(response).map{|t| from_api(t) } end end end end <file_sep>/lib/bremen/mixcloud.rb require 'json' require 'bremen/base' module Bremen class Mixcloud < Bremen::Base BASE_URL = 'http://api.mixcloud.com/' self.default_options = { keyword: '', limit: 20, page: 1, } class << self def find_url uid_or_url if uid_or_url.to_s.include?('www.mixcloud.com') uid_or_url.sub('www.mixcloud.com', 'api.mixcloud.com') else "#{BASE_URL[0..-2]}#{uid_or_url}" end end def search_url options = {} options = default_options.merge(options) query = { q: options[:keyword], limit: options[:limit], offset: options[:limit] * (options[:page] - 1), type: 'cloudcast', } "#{BASE_URL}search/?#{build_query(query)}" end def from_api hash = {} created_at = Time.parse(hash['created_time']).utc new({ uid: hash['key'], url: hash['url'], title: hash['name'], author: Bremen::Author.new({ uid: hash['user']['key'], url: hash['user']['url'], name: hash['user']['name'], thumbnail_url: hash['user']['pictures']['medium'], }), length: hash['audio_length'].to_i, thumbnail_url: hash['pictures']['medium'], created_at: created_at, updated_at: created_at, }) end private def convert_singly response from_api(JSON.parse(response)) end def convert_multiply response JSON.parse(response)['data'].map{|t| from_api(t) } end end end end <file_sep>/Gemfile source 'https://rubygems.org' gemspec group :development do gem 'guard-minitest' gem 'terminal-notifier-guard' end group :test do gem 'coveralls', require: false gem 'codeclimate-test-reporter', require: false end <file_sep>/spec/bremen/soundcloud_spec.rb $:.unshift(File.expand_path('../../', __FILE__)) require 'spec_helper' describe Bremen::Soundcloud do after{ Bremen::Soundcloud.client_id = nil } describe '.build_query' do before do Bremen::Soundcloud.client_id = nil ENV['SOUNDCLOUD_CLIENT_ID'] = nil end describe 'not set client_id' do it 'raise error' do lambda{ Bremen::Soundcloud.build_query({a: 'b'}) }.must_raise RuntimeError end end describe 'set client_id via ENV' do before{ ENV['SOUNDCLOUD_CLIENT_ID'] = 'CID' } subject{ Bremen::Soundcloud.build_query({a: 'b'}) } it 'return query string' do subject.must_equal 'a=b&client_id=CID' end end describe 'set client_id directly' do before{ Bremen::Soundcloud.client_id = 'CID' } subject{ Bremen::Soundcloud.build_query({a: 'b'}) } it 'return query string' do subject.must_equal 'a=b&client_id=CID' end end end describe '.find_url' do before{ Bremen::Soundcloud.client_id = 'CID' } subject{ Bremen::Soundcloud.find_url(uid_or_url) } describe 'given id' do let(:uid_or_url){ 100 } it 'generate directly' do subject.must_equal 'http://api.soundcloud.com/tracks/100.json?client_id=CID' end end describe 'given url' do let(:uid_or_url){ 'http://soundcloud.com/author/permalink' } it 'generate with resolve resource' do subject.must_equal 'http://api.soundcloud.com/resolve.json?url=http%3A%2F%2Fsoundcloud.com%2Fauthor%2Fpermalink&client_id=CID' end end end describe '.search_url' do before{ Bremen::Soundcloud.client_id = 'CID' } subject{ Bremen::Soundcloud.search_url(params) } describe 'only keyword' do let(:params){ {keyword: 'searchword'} } it 'generate' do subject.must_equal 'http://api.soundcloud.com/tracks.json?q=searchword&order=created_at&limit=50&offset=0&filter=&client_id=CID' end end describe 'full params' do let(:params){ {keyword: 'searchword', order: 'hotness', limit: 10, page: 2, filter: 'public'} } it 'generate' do subject.must_equal 'http://api.soundcloud.com/tracks.json?q=searchword&order=hotness&limit=10&offset=10&filter=public&client_id=CID' end end end describe '.convert_singly' do subject{ Bremen::Soundcloud.send(:convert_singly, response) } let(:response){ fixture('soundcloud_single.json') } it 'convert successfully' do subject.title.must_equal 'Title' subject.uid.must_equal '11111111' subject.created_at.zone.must_equal 'UTC' end end describe '.convert_multiply' do subject{ Bremen::Soundcloud.send(:convert_multiply, response) } let(:response){ fixture('soundcloud_multi.json') } it 'convert successfully' do subject.first.title.must_equal 'Title' subject.first.uid.must_equal '11111111' subject.first.created_at.zone.must_equal 'UTC' end end end
e5b137494e6877fb07b0ed906e53a826d3c0d3fa
[ "Markdown", "Ruby" ]
17
Ruby
deeeki/bremen
ea337feed31748014b31ef837c44853095d1c6ca
c7ced47ff239a93975ac88d06ef8f324fa8462e9
refs/heads/master
<repo_name>zqrr/cw-spring-common-tool-ftp<file_sep>/src/main/java/cn/cloudwalk/common/tool/ftp/SFTPUtil.java package cn.cloudwalk.common.tool.ftp; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Vector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.jcraft.jsch.ChannelSftp; import com.jcraft.jsch.JSchException; import com.jcraft.jsch.SftpException; import cn.cloudwalk.common.tool.ftp.config.FTPProperties; import cn.cloudwalk.common.tool.ftp.sftp.SFTPChannel; import cn.cloudwalk.common.tool.ftp.sftp.SFTPConstants; public class SFTPUtil { private static final Logger logger = LoggerFactory.getLogger(FTPUtil.class); private static final int DEFAULT_TIME_OUT = 60000; private String host; private String port; private String userName; private String password; private String path; private String local; private String fileName; public String getHost() { return host; } public void setHost(String host) { this.host = host; } public String getPort() { return port; } public void setPort(String port) { this.port = port; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public String getLocal() { return local; } public void setLocal(String local) { this.local = local; } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } /** * Default Constructor * @param properties */ public SFTPUtil() {} /** * Constructor * @param properties */ public SFTPUtil(FTPProperties properties) { this.host = properties.getHost(); this.port = properties.getPort(); this.userName = properties.getUserName(); this.password = properties.getPassword(); this.path = properties.getPath(); this.local = properties.getLocal(); } /** * Constructor * @param host * @param port * @param userName * @param password * @param path */ public SFTPUtil(String host, String port, String userName, String password, String path, String local) { this.host = host; this.port = port; this.userName = userName; this.password = <PASSWORD>; this.path = path; this.local = local; } /** * get SFTPChannel * @return */ public SFTPChannel getSFTPChannel() { return new SFTPChannel(); } /** * get ChannelSftp * @throws JSchException */ public ChannelSftp openChannelSftp(SFTPChannel channel) throws JSchException { Map<String, String> sftpDetails = new HashMap<String, String>(); sftpDetails.put(SFTPConstants.SFTP_REQ_HOST, host); sftpDetails.put(SFTPConstants.SFTP_REQ_PORT, port); sftpDetails.put(SFTPConstants.SFTP_REQ_USERNAME, userName); sftpDetails.put(SFTPConstants.SFTP_REQ_PASSWORD, <PASSWORD>); try { return channel.getChannel(sftpDetails, DEFAULT_TIME_OUT); } catch (JSchException e) { e.printStackTrace(); logger.error("sftp get channel wrong." + e.getMessage()); throw new JSchException("getChannel exception.", e); } } /** * Disconnect from the SFTPServer. * @throws Exception */ public void close(ChannelSftp chSftp, SFTPChannel channel) throws Exception { try { if (chSftp != null) { chSftp.quit(); } if (channel != null) { channel.closeChannel(); } } catch (IOException e) { e.printStackTrace(); logger.error("close ChannelSftp wrong." + e.getMessage()); throw new JSchException("close ChannelSftp exception.", e); } catch (Exception e) { e.printStackTrace(); logger.error("close SFTPChannel wrong." + e.getMessage()); throw new Exception(e); } } /** * DownLoad file the files from Server path to local. * @param fileName * @throws Exception */ public void downloadFile(String fileName) throws Exception { SFTPChannel channel = null; ChannelSftp chSftp = null; long start = System.currentTimeMillis(); try { channel = this.getSFTPChannel(); chSftp = this.openChannelSftp(channel); chSftp.get(path + fileName, local); logger.info(fileName + "DownLoad file success,time:" + (System.currentTimeMillis() - start) + "ms."); } catch (SftpException e) { e.printStackTrace(); logger.error(fileName + "DownLoad file failed."); throw new Exception(e); } finally { this.close(chSftp, channel); } } /** * Upload file from local to Server path. * @param fileName * @throws Exception */ public void uploadFile(String fileName) throws Exception { SFTPChannel channel = null; ChannelSftp chSftp = null; long start = System.currentTimeMillis(); try { channel = this.getSFTPChannel(); chSftp = this.openChannelSftp(channel); this.checkPath(path); chSftp.put(local + fileName, path + fileName, ChannelSftp.OVERWRITE); logger.info(fileName + "UpLoad file success,time:" + (System.currentTimeMillis() - start) + "ms."); } catch (SftpException e) { e.printStackTrace(); logger.error(fileName + "UpLoad file failed."); throw new Exception(e); } finally { this.close(chSftp, channel); } } /** * Delete file from the path in Server. * @param fileName * @throws Exception */ public void deleteFile (String fileName) throws Exception { SFTPChannel channel = null; ChannelSftp chSftp = null; long start = System.currentTimeMillis(); try { channel = this.getSFTPChannel(); chSftp = this.openChannelSftp(channel); chSftp.rm(path + fileName); logger.info(fileName + "Delete file success,time:" + (System.currentTimeMillis() - start) + "ms."); } catch (SftpException e) { e.printStackTrace(); logger.error(fileName + "Delete file failed."); throw new Exception(e); } finally { this.close(chSftp, channel); } } /** * Show all the files in the Server path. * @param path * @return * @throws Exception */ public Vector showFiles() throws Exception { Vector ret = new Vector(); SFTPChannel channel = null; ChannelSftp chSftp = null; long start = System.currentTimeMillis(); try { channel = this.getSFTPChannel(); chSftp = this.openChannelSftp(channel); ret = chSftp.ls(path); logger.info(fileName + "show all files success,time:" + (System.currentTimeMillis() - start) + "ms."); } catch (SftpException e) { e.printStackTrace(); logger.error(fileName + "show all files failed."); throw new Exception(e); } finally { this.close(chSftp, channel); } System.out.print(ret.toString()); return ret; } /** * check path, if not exits , mkdir * @param path * @throws Exception */ public void checkPath(String path) throws Exception { String[] folders = path.split( "/" ); SFTPChannel channel = null; ChannelSftp chSftp = null; try { channel = this.getSFTPChannel(); chSftp = this.openChannelSftp(channel); chSftp.cd("/"); for (String folder : folders) { if (folder.length() > 0) { try { chSftp.cd(folder); } catch (SftpException e) { chSftp.mkdir(folder); chSftp.cd(folder); } } } } catch (SftpException e) { e.printStackTrace(); logger.error(fileName + "check path failed."); throw new Exception(e); } finally { this.close(chSftp, channel); } } /** * @param args * @throws Exception */ public static void main(String[] args) throws Exception { SFTPUtil test = new SFTPUtil("192.168.10.116", "22", "root", "123456", "/sftp/cc/", "d:/"); test.uploadFile("install.log"); //test.downloadFile("install.log"); //test.showFiles(); } } <file_sep>/src/main/java/cn/cloudwalk/common/tool/ftp/config/FTPProperties.java package cn.cloudwalk.common.tool.ftp.config; import java.io.Serializable; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; /** * * ClassName: FTPProperties <br/> * Description: FTP服务参数配置对象. <br/> * Date: 2017年10月26日 下午4:49:49 <br/> * * @author zq * @version 1.0.0 * @since 1.7 */ @Component @ConfigurationProperties(prefix = "cw.ftp") public class FTPProperties implements Serializable{ private static final long serialVersionUID = -8687067332135180094L; private String host; private String port; private String userName; private String password; private String path; private String local; public String getHost() { return host; } public void setHost(String host) { this.host = host; } public String getPort() { return port; } public void setPort(String port) { this.port = port; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public String getLocal() { return local; } public void setLocal(String local) { this.local = local; } } <file_sep>/README.md # cw-spring-common-tool-ftp ftp sftp tool
813768167e63e22daecd2f54b2c3b811d834a737
[ "Markdown", "Java" ]
3
Java
zqrr/cw-spring-common-tool-ftp
676612100bb3ee490ed72f804eeeb5a658793e3c
6401c9efa72ad9c966b6fb45a3367fbf1908a751
refs/heads/master
<repo_name>konap/PluralGrade<file_sep>/Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Speech.Synthesis; namespace Grades { class Program { static void Main(string[] args) { GradeBook g1 = new GradeBook(); GradeBook g2 = g1; g1.Name = "Scott Grade Book"; Console.Write(g2.Name); SpeechSynthesizer synth = new SpeechSynthesizer(); synth.Speak("Всем привет"); GradeBook book = new GradeBook(); book.AddGrade(91); book.AddGrade(81.5f); book.AddGrade(75); GradeStatistics stats = book.ComputeStatictics(); Console.WriteLine(stats.AverageGrade); } } } <file_sep>/README.md "# PluralGrade"
de4c6ea599c783602753db065aa519b95bd2e9de
[ "Markdown", "C#" ]
2
C#
konap/PluralGrade
e9a431f0004ca090f21a266bd6004e5468a52fcd
1c326e085671fe4611b2118378c5570e643beb3b
refs/heads/master
<file_sep>from Q1 import * import csv def complexityTest(): breadth = {} depth = {} for n in range(1, 11): resetCounter() for k in range(5): L = randomList(n) tree = build_sum_tree(L) breadthFirst(tree, n**2) try: breadth[n] += getCounter() except: breadth[n] = getCounter() resetCounter() depthFirst(tree, n**2) try: depth[n] += getCounter() except: depth[n] = getCounter() resetCounter() depth[n] /= 5 breadth[n] /= 5 return breadth, depth breadth, depth = complexityTest() print(breadth) print(depth) with open('output.csv', 'w') as output: writer = csv.writer(output) for key, value in breadth.items(): writer.writerow([key, value]) for key, value in depth.items(): writer.writerow([key, value]) <file_sep>from math import sqrt import time start = time.time() def is_divisible(n, primes): check = True for i in primes: if i > sqrt(n): return check if n % i == 0: check = False break else: check = True return check def find_primes(N): primes = [] for i in range(N - 1): number = i + 2 if number % 2 == 1 and is_divisible(number, primes): primes.append(number) return primes def brun(N): sum = 0 prime1 = 1 prime2 = 0 primes = find_primes(N) couple = True for i in primes: if couple: prime1 = i couple = False else: prime2 = i couple = True if abs(prime1 - prime2) == 2: sum += (1/prime1 + 1/prime2) return sum print(find_primes(200)) print() print(brun(10**6)) print("at the end", time.time()-start) <file_sep> /** * LazyRectangle class, manages the state of the Rectangle via caching and lazy * instatiation of state. * * @author <NAME> * @version 1.1 */ public class LazyRectangle extends BasicRectangle { private double height; private double width; private double area; private double perimeter; private boolean areaNotSet = true; private boolean perimeterNotSet = true; /** * Constructor makes a rectangle with sides of unit length */ public LazyRectangle() { this.width = 1.0; this.height = 1.0; } /** * Costructor makes a rectangle with the width and height passed in * as arguments. Negative values are set to zero. * * @param width rectangle width * @param height rectangle height */ public LazyRectangle(double width, double height) { this.setHeight(height); this.setWidth(width); } /* * Sets area state */ private void computeArea() { this.area = super.getArea(); this.areaNotSet = false; } /* * Sets perimeter state */ private void computePerimeter() { this.perimeter = super.getPerimeter(); this.perimeterNotSet = false; } /** * {@inheritDoc} */ public double getArea() { if (this.areaNotSet) this.computeArea(); return this.area; } /** * {@inheritDoc} */ public double getPerimeter(){ if (this.perimeterNotSet) this.computePerimeter(); return this.perimeter; } /** * {@inheritDoc} */ public void setHeight(double height){ super.setHeight(height); this.resetFlags(); } /** * {@inheritDoc} */ public void setWidth(double width){ super.setWidth(width); this.resetFlags(); } /* * Resets area and perimeter flags */ private void resetFlags(){ this.areaNotSet = true; this.perimeterNotSet = true; } } <file_sep>from anagram import make_anagram_dict from blanagram import blanagram D = make_anagram_dict(open("words.txt", "r")) while True: # The program asks for a word and then calculates all the anagrams # of the word and all the blanagrams that are not anagrams word = input("Type your word: ") try: anagrams = " ". join(D["".join(sorted(word))]) blanagrams = " ".join(blanagram(word, D)) except KeyError: print('"%s" is not a valid word' % word) print() print("Anagrams: ", anagrams) print("Blanagrams: ", blanagrams) print() <file_sep>def unique(L): D = {} for element in L: D[element] = 1 return list(D.keys()) def ounique(L): D = {} i = 0 for element in L: if element not in D: D[element] = i i += 1 return sorted(D, key=D.get) L = [9, 9, 1, 1, 1, 2, 2, 2, 3, 6, 7] print(unique(L)) print(ounique(L)) <file_sep>/* Rectangle class Object to contain data pertaining to Rectangles, along with some methods to access the data Code does not perform any type checking or exception handling author: <NAME> date: 14/01/12 */ public class Rectangle { // attributes/fields private int width; private int height; public static final int NUMBER_OF_SIDES = 4; //declared & assigned // constructors public Rectangle() { //default values create unit square width = 1; height = 1; } public Rectangle( int w, int h ) { width = w; height = h; } public int getWidth() { return width; } public int getHeight() { return height; } public int getArea() { return width*height; } public void rotateRectangle( ) { int temp = width; width = height; height = temp; } public double doubleSizes() { width = 2*width; height = 2*height; return width*height; } } <file_sep>public class RaceParticipant { // attributes private String forename; private String surname; private String formTutor; // constructor public RaceParticipant(String forename, String surname, String formTutor){ this.forename = forename; this.surname = surname; this.formTutor = formTutor; } // Method prints out information about this RaceParticipant public void printInfo() { System.out.println(); System.out.println(forename + " " + surname + ", tutor: " + formTutor); } }<file_sep>from random import random def riffle_once(L): """ It shuffles a given list using the riffle shuffle: divides the given list in two parts of equal size and for each iteration decides at random whether the next card should be taken from part 1 or part 2. Repeats until both part 1 and part 2 have no cards left L = List to shuffle """ LA = L[:int(len(L) / 2):-1] LB = L[int(len(L) / 2)::-1] shuffled = [] while len(LA) != 0 or len(LB) != 0: if len(LA) == 0: shuffled.append(LB.pop()) continue elif len(LB) == 0: shuffled.append(LA.pop()) continue rand = random() if rand >= 0.5: shuffled.append(LA.pop()) elif rand < 0.5: shuffled.append(LB.pop()) return shuffled def riffle(L, N): """ It uses the function "riffle_once" N times in order to shuffle a given list L = list to shuffle N = number of times that riffle_once must be used """ if N < 0: # guardian statement print("The number of shuffles must be a positive value") return None for i in range(N): L = riffle_once(L) return L def check_shuffle(L): """ It just checks that the function "riffle" is working properly, in order to do that it checks the following conditions: - The list after the shuffle must have the same legth of the list before the shuffle - Every element in the list before the shuffle must be in the list after the shuffle If both of the conditions above are True than returns True, otherwise it returns False L = list to be used in the process """ L_shuffled = riffle(L, int(random() * 100)) # shuffled a random number of times if len(L) != len(L_shuffled): # first condition return False while len(L) > 0: # second condition if L[-1] not in L_shuffled: return False else: i = L_shuffled.index(L.pop()) L_shuffled.pop(i) return True def quality(L): """ Takes in a shuffled list and gives it a "mark" on how well it's shuffled. The mark is given by counting how often an element in the list is followed by a bigger element, the mark then is the ratio bigger/total elements A well-shuffled list has an ideal mark of 0.5 L = List to evaluate """ big = 0 for i in range(len(L) - 1): if L[i] < L[i + 1]: big += 1 return big / len(L) def average_quality(N, trials): """ Returns the average quality of the shuffle function by using the "quality" function "trials" times on a list shuffled N times. It uses a list with the integer from 0 to 49 for the test N = Number of times that the function "riffle_once" must be used in every shuffle trials = Number of trials """ if N < 0: # guardian statement print("The number of shuffles must be a positive value") return None sum = 0 for i in range(trials): L = list(range(50)) L_shuffled = riffle(L, N) sum += quality(L_shuffled) return round(sum / trials, 4) for i in range(1, 16): print("using", i, "shuffles, the average quality of the algorithm is", average_quality(i, 30)) # According to the result of the iteration I think that N > 5 shuffle is # a good number of shuffles on a list of lenght 50 <file_sep>from dsa import * from Q1 import depthFirst, breadthFirst from itertools import permutations from time import time from copy import deepcopy def build_countdown_tree(lst, T=new_tree(0, [], "0")): # done for e in lst: val = [] for op in [add, sub, mul, div]: current_branch = deepcopy(T) val.append(map_tree(current_branch, e, op)) for t in val: t = clean_tree(t) T = add_child(T, t) return T def map_tree(T, num, operation): # done if children(T) == []: return new_tree(operation(value(T), num)[0], [], "(" + str(label(T)) + operation(value(T), num)[1] + str(num) + ")") else: T = new_tree(operation(value(T), num)[0], children(T), "(" + str(label(T)) + operation(value(T), num)[1] + str(num) + ")") for c in range(len(children(T))): children(T)[c] = map_tree(children(T)[c], num, operation) return T def add(n1, n2): return (n1 + n2, " + ") def sub(n1, n2): return (n1 - n2, " - ") def mul(n1, n2): return (n1 * n2, " * ") def div(n1, n2): return (n1 / n2, " / ") def permutations_tree(L, T=new_tree(0, [], "0")): L = list(permutations(L)) trees = [] for l in L: trees.append(build_countdown_tree(l)) for t in trees: T = add_child(T, t) return T def clean_tree(tree): if children(tree) == []: if value(tree) > 0 and value(tree) == int(value(tree)): return tree else: return new_tree(0, [], "0") else: if value(tree) >= 0 and value(tree) == int(value(tree)): for c in range(len(children(tree))): children(tree)[c] = clean_tree(children(tree)[c]) else: return new_tree(0, [], "0") return tree start = time() print("started") # tree = build_countdown_tree([1, 2, 3, 4, 5, 6]) # print(tree) # depth = depthFirst(tree, 1740) # print(time() - start) tree = permutations_tree([12, 87, 8, 3, 4]) print("tree done in: " + str(time() - start)) start = time() #print(tree) depth = depthFirst(tree, 999999) print(depth) print("Depth done in: " + str(time() - start)) start = time() breadth = breadthFirst(tree, 999999) print(breadth) print("breadth done in: " + str(time() - start)) start = time() # tree = permutations_tree([12, 87, 8, 3, 4, 8]) # print("tree done in: " + str(time() - start)) # start = time() <file_sep>product = 0 highest = 0 for i in range(100, 999): for k in range(100, 999): product = i * k productSTR = str(product) if len(productSTR) % 2 == 0: part1 = productSTR[:len(productSTR)//2] part2 = productSTR[len(productSTR)//2:len(productSTR)] part2 = part2[::-1] if part1 == part2: if product > highest: highest = product print("il numero è", highest) <file_sep> /** * Write a description of class CatsApp here. * * @author (your name) * @version (a version number or a date) */ public class CatsApp { public static void main (String[] args) { PersianCat Tom = new PersianCat(5.0, true, true, 13); System.out.println(Tom.jumpWhenStartled(200)); System.out.println(Tom.sleepCurledUp(200)); System.out.println(Tom.haveKittens(200)); System.out.println(Tom.getWeight()); System.out.println(Tom.likelihoodOfBitingGuest(50)); Cat Romeo = new PersianCat(7.0, true, true, 11); System.out.println(Romeo.jumpWhenStartled(200)); System.out.println(Romeo.sleepCurledUp(200)); System.out.println(Romeo.haveKittens(200)); } }<file_sep> /** * Illustrates equality behaviour due to chaching * * @author <NAME> * @version 1.0 */ import java.io.InputStreamReader; import java.io.BufferedReader; import java.io.IOException; public class EqualityExample { public static void main(String[] args) throws IOException { Integer a = 128; Integer b = 128; Integer c = Integer.parseInt(args[0]); Integer d = new Integer(args[0]); // behaviour of wrapper types with JVM caching System.out.println(a==b); System.out.println(a==c); System.out.println(a==d); // behaviour of String types with JVM caching String e = "7"; String f = "7"; System.out.println("7" == e); System.out.println("7" == f); System.out.println("7" == args[0]); } } <file_sep>i = 3 check = False s = 0 counter = 2 while 1 == 1: k = i - 1 while k > 1: if i % k == 0: k = 0 check = False else: k -= 1 check = True if check: if counter % 100 == 0: print(i, counter) elif counter == 10001: print(i, counter) break counter += 1 i += 1 s += 1 check = False print("Done") <file_sep>from exturtle import * from drawmaze import draw def read(filename): size = 0 forbidden = {} lines = open(filename, "r").readlines() for line in lines: line = line.strip() if len(line) == 1: size = int(line) elif len(line) == 3: forbidden[(int(line[0]), int(line[2]))] = 1 return size, forbidden def search(path, forbidden, shortest, longest): if path[-1] == (size - 1, size - 1): if len(path) == len(shortest[0]): for i in range(len(shortest)): try: if len(shortest[i]) > len(shortest[0]): shortest.pop(i) except IndexError: pass shortest.append(path) elif len(path) < len(shortest[0]): shortest = [path] return shortest position = path[-1] for neighbour in neighbours(position): if neighbour not in forbidden.keys() and neighbour not in path: nextpath = path[:] nextpath.append((neighbour[0], neighbour[1])) shortest[0] = search(nextpath, forbidden, shortest, [])[0] return shortest def neighbours(position): x, y = position valid_n = [] if y % 2 == 1: possible_n = [(x - 1, y - 1), (x - 1, y), (x - 1, y + 1), (x, y + 1), (x + 1, y), (x, y - 1)] else: possible_n = [(x, y - 1), (x - 1, y), (x, y + 1), (x + 1, y + 1), (x + 1, y), (x + 1, y - 1)] for coord in range(len(possible_n)): x, y = possible_n[coord] if x >= 0 and x < size and y >= 0 and y < size: valid_n.append((x, y)) return valid_n #A = Turtle() size, forbidden = read("small.txt") #draw(A, size, forbidden) path = [(0,0)] shortest = ["X"* size ** 2] shortests = search(path, forbidden, shortest, []) for pth in shortests: #if len(pth) == len(shortests[-1]): # print(pth) print(pth) #print(shortest_list) #print(search(path, forbidden, shortest)) #mainloop() <file_sep>from Q1 import * import csv def complexityTest(): """ The function tests the complexity of the algorithms breadthFirst and depthFirst by creating 5 random lists of length from 1 to 10 and calculating the average number of comparisons required to find the element n^2 for each length of the list. Returns two dictionaries with numbers n from 1 to 10 as keys and the average numbers of comparisons for a random list of length n (the number of the key). In order returns (<breadth dictionary>, <depth dictionary>) """ breadth = {} depth = {} for n in range(1, 11): for k in range(5): resetCounter() L = randomList(n) tree = build_sum_tree(L) breadthFirst(tree, n**2) try: breadth[n] += getCounter() except: breadth[n] = getCounter() resetCounter() depthFirst(tree, n**2) try: depth[n] += getCounter() except: depth[n] = getCounter() depth[n] /= 5 breadth[n] /= 5 return breadth, depth if __name__ == "__main__": breadth, depth = complexityTest() print("breadth: " + str(breadth)) print("depth: " + str(depth)) # saves the results in a csv file with open('output.csv', 'w', newline="") as output: writer = csv.writer(output) writer.writerows(breadth.items()) writer.writerow("") writer.writerows(depth.items()) <file_sep> /** * CachedRectangle class, manages the state of the Rectangle via caching data * generated by initial state. * * @author <NAME> * @version 1.1 */ public class CachedRectangle extends BasicRectangle { private double height; private double width; private double area; private double perimeter; /** * Constructor makes a rectangle with sides of unit length */ public CachedRectangle() { this.width = 1.0; this.height = 1.0; this.recomputePerimeterAndArea(); } /** * Costructor makes a rectangle with the width and height passed in * as arguments. Negative values are set to zero. * * @param width rectangle width * @param height rectangle height */ public CachedRectangle(double width, double height) { this.height = (height<0) ? 0 : height; this.width = (width<0) ? 0 : width; this.recomputePerimeterAndArea(); } /* * Sets perimeter and area state */ private void recomputePerimeterAndArea() { this.area = super.getArea(); this.perimeter = super.getPerimeter(); } /** * {@inheritDoc} */ public double getArea() { return this.area; } /** * {@inheritDoc} */ public double getPerimeter(){ return this.perimeter; } /** * {@inheritDoc} */ public void setHeight(double height){ super.setHeight(height); this.recomputePerimeterAndArea(); } /** * {@inheritDoc} */ public void setWidth(double width){ super.setWidth(width); this.recomputePerimeterAndArea(); } } <file_sep>import string from operator import itemgetter def counter(nome_file): D = {} File = open(nome_file, "r").readlines() for line in File: for word in line.split(" "): word = word.strip().lower() word = word.strip(string.punctuation) if word == "": continue try: D[word] += 1 except: D[word] = 1 return D parole = counter("bibbia.txt") sort = sorted(parole.items(), key=itemgetter(1), reverse=True) for k, v in sort: print(k, " ", v) print(parole["stranger"]) <file_sep>def bonus_check(L): total_bonus = 0 profit = 0 for i in range(len(L)): profit += float(L[i]) if profit >= 400000: # print(i) total_bonus += i profit = 0 return total_bonus def profit_ratio(L): plus = 0 minus = 0 for day in L: if float(day) >= 0: plus += 1 else: minus += 1 return plus/minus def average_per_year(L): work_years = len(L) / (5 / 7 * (365 - 28)) print("She worked for", work_years, "years") total_bonus = bonus_check(L) print("Getting", total_bonus, "bonus dollars") total = work_years * 100000 + total_bonus return total / work_years trader = open("trader.dat", "r").readlines() bonus_check(trader) print(profit_ratio(trader)) print("With an average of", average_per_year(trader), "dollars per year") <file_sep> /** * Write a description of class ConditionalTest here. * * @author (your name) * @version (a version number or a date) */ public class ConditionalTest { public static void main( String[] args ) { int a = false ? 5 : -7; System.out.println(a); float val1 = 0.8f, val2 = 80.7f, b; b = ( a < 3) ? val1 : val2; System.out.println(b); String size; size = ( b <= 50.0f ) ? small() : big(); System.out.println(size); // above three lines could be written as below, but not very readable! // System.out.println( (b <= 50.0f ) ? small() : big() ); } public static String big() { return "BIG"; } public static String small() { return "small"; } } <file_sep>def rsum(N): print("opened rsum with N = ", N) if N == 0: return 0 else: return N + rsum(N - 1) print(rsum(10)) <file_sep>from math import sqrt def is_divisible(n, primes): """ Checks wether a given number n is divisible by all the numbers in a list smaller than the square root of itself. Return True if n is divisible by at least one element and False if it's not divisible by any of them Arguments: n = given number to check primes = list of numbers to check the divisibility by """ check = False Max = sqrt(n) for i in primes: if i > Max: return False if n % i == 0: check = True break else: check = False return check def find_primes(N): """ Returns a list of prime numbers up to a given number N. It uses the is_divisible function to check, for every number between 3 and N, if it's divisible by any other prime in the list, if it doesn't it's appended to the 'primes' list """ if N < 2: ret = "There are no prime numbers smaller than " + str(N) return ret primes = [2] for i in range(3, N + 1, 2): if not is_divisible(i, primes): # not divisible by any other prime primes.append(i) # append it to the list return primes def brun(N): """ Returns the Brun's constant calculated used the primes up to a given N The Brun's constant is calculated as the sum of the reciprocal of all pairs of twin prime numbers (difference 2) """ sum = 0 lastP = 1 primes = find_primes(N) # creates the list of prime up to N for i in primes: if i - lastP == 2: # checks for two consecutive elements if they're twin primes sum = sum + (1/lastP + 1/i) lastP = i return sum # the returned sum is the Brun's constant requested print(find_primes(200)) print() print(brun(10**6)) <file_sep>from dsa import * from random import random from copy import deepcopy from time import time counter = 0 def build_sum_tree(lst, T = new_tree(0, [], "0")): #done #print(T) current_branch = deepcopy(T) for e in lst: #print(current_branch) current_branch = deepcopy(T) #print("cb: " + str(current_branch)) val = map_sum(current_branch, e) #print("val: " + str(val)) #print("T before: " + str(T)) T = add_child(T,val) #print("T after: " + str(T)) #print(T) #print(T) #print(T) return T def map_sum(T, num): # done #print(num) #print("in map sum with T = " + str(T)) if len(children(T)) == 0: #print(T[0]) #print(num) #print(T[0] + num) #print("base case" + str(num)) return new_tree(value(T) + num, [], str(label(T)) + " + " + str(num)) else: #print(T[0]) #print(num) T = new_tree(value(T) + num, children(T), str(label(T)) + " + " + str(num)) #print("not in base case") for c in range(len(children(T))): #print(c) children(T)[c] = map_sum(children(T)[c], num) #print(c) #print("gives T = " + str(T)) return T def compare(x, y): # done global counter counter += 1 return x == y def depthFirst(tree, item, verbose = False): # done stack = push(tree, []) current_node = top(stack) closestDifference = ((item*2)**2, tree) #print(current_node) k = 0 while not (not stack or compare(item, value(current_node))): #print(value(current_node)) #print("in while") #print(current_node) if abs(value(current_node) - item) < closestDifference[0] and not compare(value(current_node), 0): closestDifference = (abs(value(current_node) - item), label(current_node), value(current_node)) #print() #print(stack) #print("\n" * 3) stack = pop(stack) #print(stack) #print(tree) if children(current_node): #print("in if") for c in children(current_node): k += 1 # print(children(tree)) # print(c) stack = push(c, stack) # print(stack) # print() current_node = top(stack) if not stack: VerboseMsg = "Couldn't find the requested item, but the item closest to the target(" + str(item) + ") is: " + str(str(value(closestDifference[1]))) + ", found using: " + str(label(closestDifference[1])) NonVerboseMsg = (str((closestDifference[2])), str(closestDifference[1])) else: VerboseMsg = "Found the requested item (" + str(item) + "), using " + str(label(current_node)) NonVerboseMsg = (str(item), str(label(current_node))) if verbose: return VerboseMsg, k else: return NonVerboseMsg, k def breadthFirst(tree, item, verbose=False): # done queue = enqueue(tree, []) current_node = head(queue) closestDifference = ((item*2)**2, tree) k = 0 while not (not queue or compare(item, value(current_node))): if abs(value(current_node) - item) < closestDifference[0] and not compare(value(current_node), 0): closestDifference = (abs(value(current_node) - item), label(current_node), value(current_node)) queue.pop(0) if children(current_node): for c in children(current_node): k += 1 queue.append(c) current_node = head(queue) if not queue: VerboseMsg = "Couldn't find the requested item, but the item closest to the target(" + str(item) + ") is: " + str(str(value(closestDifference[1]))) + ", found using: " + str(label(closestDifference[1])) NonVerboseMsg = (str((closestDifference[2])), str(closestDifference[1])) else: VerboseMsg = "Found the requested item (" + str(item) + "), using " + str(label(current_node)) NonVerboseMsg = (str(item), str(label(current_node))) if verbose: return VerboseMsg, k else: return NonVerboseMsg, k def randomList(n): # done L = [] for i in range(n): num = int(random()*100//1) L.append(num) return L def resetCounter(): global counter counter = 0 def getCounter(): return counter if __name__ == "__main__": #print(build_sum_tree(range(1, 26))) counter = 0 start = time() tree = build_sum_tree(range(16)) depth = depthFirst(tree, 30000) print("depth: " + str(time() - start)) start = time() print(depth) print(counter) counter = 0 breadth = breadthFirst(tree, 30000) print("breadth: " + str(time() - start)) print(breadth) print(counter) <file_sep> /** * Write a description of class test here. * * @author (your name) * @version (a version number or a date) */ public class test { public static void main(String args[]) throws InvalidIDException, IDAlreadySetException, InvalidStageException, StaffNotInvolvedException, DuplicateStaffException, IDNotSetException, java.io.IOException { Staff[] noStaff = {}; Staff[] staff = new Staff[5]; staff[1] = new StaffClass("Gihan", "Marasingha"); staff[2] = new StaffClass("David", "Wakeling"); staff[3] = new StaffClass("Jonathan", "Fieldsend"); staff[4] = new StaffClass("Nicholas", "Pugeault"); staff[0] = new StaffClass("Philipp", "Pascal"); Student[] students = new Student[10]; students[0] = new StudentClass((byte)1, "Michael", "Tanzer"); students[1] = new StudentClass((byte)1, "David", "Dixon"); students[2] = new StudentClass((byte)1, "Oonagh", "Madden-Wells"); students[3] = new StudentClass((byte)3, "Adam", "Brocklehorst"); students[4] = new StudentClass((byte)4, "Maths", "Person"); students[5] = new StudentClass((byte)1, "Chris", "Tyson"); students[6] = new StudentClass((byte)1, "Gareth", "Iguasnia"); students[7] = new StudentClass((byte)1, "Evan", "Davy"); students[8] = new StudentClass((byte)3, "Alicia", "Daurignac"); students[9] = new StudentClass((byte)1, "Tom", "Shopland"); Module[] modules = new Module[5]; modules[0] = new ModuleClass("Advanced Calculus", (byte)1, noStaff, 4, 30); modules[1] = new ModuleClass("Fluid Dynamics", (byte)3, noStaff, 4, 60); modules[2] = new ModuleClass("Computers and the Internet", (byte)1, noStaff, 4, 40); modules[3] = new ModuleClass("Vectors and Matrices", (byte)1, noStaff, 4, 50); modules[4] = new ModuleClass("Something Complicated", (byte)4, noStaff, 4, 80); UniversityAllocationManager manager = new UniversityAllocationManager(staff, students, modules); manager.saveAllocationManager("Test1.uam"); } } <file_sep> /** * Write a description of class PersianCat here. * * @author (your name) * @version (a version number or a date) */ public class PersianCat implements Cat, FavouritePet { private double weight; //weight in kilos private boolean highlyStrung; //temperament private boolean awake; private int ageInMonths; // constructors, remember super() is implicitly called if I // don’t explicitly call any other supertype constructor on the // first line of a constructor method block public PersianCat(){ weight = 1.0; highlyStrung = false; awake = true; ageInMonths = 0; } public PersianCat( double weight, boolean highlyStrung, boolean awake, int ageInMonths ){ this.weight = weight; this.highlyStrung = highlyStrung; this.awake=awake; this.ageInMonths = ageInMonths; } // implement Cat methods to conform to declared interface public boolean meowWhenStroked(){ // if it can feel itself being stroked, it’ll meow if ( awake ) return true; return false; } public double jumpWhenStartled( double noiseVolume ){ // a simple relationship between volume, weight and // jump height double height = noiseVolume/weight; if ( height > 150 ) //a limit on height possible! height=150; return height; } public double sleepCurledUp( double amountEaten ){ // larger cats sleep longer, and bigger meals // cause longer sleeps double timeAsleep = amountEaten*weight; if ( highlyStrung ) // nervous cats sleep less timeAsleep /= 2.0; return timeAsleep; } public Cat[] haveKittens( double virility ) { int n; if ( virility <= 10.0 ) n = 1; else if ( virility <= 100.0 ) n = 2; else n=3; PersianCat[] kittens = new PersianCat[n]; for ( int i = 0; i < n; i++ ) kittens[i] = new PersianCat( 0.45, true, true, 0 ); return kittens; } // getter and setter methods for state public double getWeight() { return weight; } public boolean isHighlyStrung() { return highlyStrung; } public boolean getAwake() { return awake; } public void setWeight( double weight ) { this.weight = weight; } public void setHighlyStrung( boolean highlyStrung ) { this.highlyStrung = highlyStrung; } public void setAwake( boolean awake ) { this.awake= awake; } public void incrementAgeByOneMonth(){ this.ageInMonths++; } public boolean birthdayJustGone(){ if (ageInMonths % 12 <= 1){ return true; } else { return false; } } public double likelihoodOfBitingGuest(double importanceOfGuest){ double n = 1 / importanceOfGuest; if (!awake) { return 0; } if (highlyStrung) { return n * 3; } else { return n; } } public double likelihoodOfEatingSundayLunch(double heightOfMealFromFloor){ if (!awake) { return 0; } return 1 / (ageInMonths * 0.5 + weight + heightOfMealFromFloor * 2); } }<file_sep># import the necessary packages import numpy as np import argparse import imutils imp ort cv2 # construct the argument parser and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-p", "--puzzle", required = True, help = "Path to the puzzle image") ap.add_argument("-w", "--waldo", required = True, help = "Path to the waldo image") args = vars(ap.parse_args()) # load the puzzle and waldo images puzzle = cv2.imread(args["puzzle"]) waldo = cv2.imread(args["waldo"]) (waldoHeight, waldoWidth) = waldo.shape[:2] <file_sep>Student no. 660001833 & 660042108. 11 - 12:30 Continued work on the UniversityAllocationManager class, going through the interface and writing concrete methods for all of the abstract ones. Throughout the session we have had issues where by tjings needed to be cast to some concrete version of itself only to be returned as a abstract version. Issues were arisen when we got to the enrol method and as we do not store the list of modules the student is enrolled in, in the student object, it took a lot of overhead to find all of the modules the student was enrolled in.We may need to change how we are managing the storage of students enrolled to different modules as having the information stored in the mdoules prevents having to search every single student, the situation where one needs to get a list of all students is so far rare. 01/03 - 10:30, 1:00. 2:00, 2:30 Concluded initial work on the Module class and then went about fixing errors that had arrisen within testing of each module that followed. ObjectArrayList is not as simple to use as originally thought and will require a lot of casting to allow for the use of specfically typed output from it. This isn't too large of an issue in retrospect but took a while to solve at the time. Work for the final UnversityManager will begin next session. 27/02 - 11:30, 13:30 We begin by creating the StaffClass, a class that inherited from the Staff interface. Through this all of the predefined methods were implemented. The same was done with the StudentClass and was begun with the Module class.<file_sep>a = 1 b = 1 c = 0 Sum = 0 while c < 4*10**6: c = a + b a = b b = c if c % 2 == 0: Sum = Sum + c print(c) print("Somma = ", Sum) <file_sep>i = 3 Sum = 2 while i < 2*10**6: k = i - 1 while k > 1: if i % k == 0: k = 0 check = False else: k -= 1 check = True if check: Sum += i print(i) i += 1 check = False print(Sum) <file_sep>/** Rectangle class Object to contain data pertaining to Rectangles, along with some methods to access the data Code does not perform any type checking or exception handling author: <NAME> date: 14/01/12 */ public class Rectangle { // attributes/fields private int width; private int height; public static final int NUMBER_OF_SIDES = 4; //declared & assigned // constructors public Rectangle() { //default values create unit square width = 5; height = 10; } public Rectangle( int w, int h ) { width = w; height = h; } public Rectangle( Rectangle r1 ) { width = r1.getWidth(); height = r1.getHeight(); } // method to return the width of this rectangle public int getWidth() { return width; } // method to return the height of this rectangle public int getHeight() { return height; } // method to calculate and return the area of this rectangle public int getArea() { return width*height; } // method to rotate the rectangle 90 degrees public void rotateRectangle() { int temp = width; width = height; height = temp; } } <file_sep>from exturtle import * from drawmaze import draw def read(filename): size = 0 forbidden = {} lines = open(filename, "r").readlines() for line in lines: line = line.strip() if len(line) == 1: size = int(line) elif len(line) == 3: forbidden[(int(line[0]), int(line[2]))] = 1 return size, forbidden def search(path, forbidden, shortest, longest): if path[-1] == (size -1, size -1): if len(path) < len(shortest): shortest = path return shortest, longest elif len(path) > len(longest): longest = path return shortest, longest position = path[-1] for neighbour in neighbours(position): if neighbour not in forbidden and neighbour not in path: nextpath = path[:] nextpath.append(neighbour) shortest, longest = search(nextpath, forbidden, shortest, longest) return shortest, longest def neighbours(position): x, y = position valid_n = [] if y % 2 == 1: possible_n = [(x - 1, y - 1), (x - 1, y), (x - 1, y + 1), (x, y + 1), (x + 1, y), (x, y - 1)] else: possible_n = [(x, y - 1), (x - 1, y), (x, y + 1), (x + 1, y + 1), (x + 1, y), (x + 1, y - 1)] for coord in range(len(possible_n)): x, y = possible_n[coord] if x >= 0 and x < size and y >= 0 and y < size: valid_n.append((x, y)) return valid_n #A = Turtle() size, forbidden = read("small.txt") #draw(A, size, forbidden) path = [(0,0)] shortest = ["X"] * size ** 2 longest = ["X"] shortest, longest = search(path, forbidden, shortest, longest) print(shortest, " ", longest) #print(shortest_list) #print(search(path, forbidden, shortest)) #mainloop() <file_sep>package university; import java.io.IOException; /** * BadAllocationManager * <p> * Compiling but poorly functioning subtype of the AllocationManager interface * * @author <NAME> * @version 1.0 */ public class BadAllocationManager implements AllocationManager { public String addStudent(String forename, String surname, byte stage) throws InvalidStageException { return null; } public void addStudent(Student student) throws IDAlreadySetException { } public String addModule(String name, byte credits, byte stage, int capacity, Staff[] staff) throws InvalidStageException, InvalidCreditsException, InvalidCapacityException, DuplicateStaffException, StaffNotInSystemException { return null; } public void addModule(Module module) throws IDAlreadySetException { } public String addStaff(String forename, String Surname) { return null; } public void addStaff(Staff staff) throws IDAlreadySetException { } public void discontinue(String moduleCode) throws InvalidIDException, IDNotRecognisedException { } public void enrol(String studentID, String moduleCode) throws InvalidIDException, IDNotRecognisedException, ModuleAtCapacityException, InsufficientAvailableCreditsException, ModuleDiscontinuedException, ModuleStageTooHighException, EnrollingWouldPreventHonoursException { } public void loadAllocationManager(String filename) throws IOException, ClassNotFoundException { } public int getNumberOfStaff() { return 0; } public int getNumberOfStudents() { return 0; } public int getNumberOfModules() { return 0; } public Staff[] getStaff() { return null; } public Staff[] getStaff(String moduleCode) throws InvalidIDException, IDNotRecognisedException { return null; } public Student[] getStudents() { return null; } public Student[] getStudents(String moduleCode) throws InvalidIDException, IDNotRecognisedException { return null; } public Module[] getModules() { return null; } public Module[] getRunningModules() { return null; } public Module[] getAvailableModules() { return null; } public Module[] getModules(String studentID) throws InvalidIDException, IDNotRecognisedException { return null; } public int getNumberOfFullyAllocatedStudents() { return 0; } public int getNumberOfModulesAtCapacity() { return 0; } public Module[] remove(Staff staff) throws InvalidIDException, IDNotRecognisedException, IDNotSetException { return null; } public void remove(Student student) throws InvalidIDException, IDNotRecognisedException, IDNotSetException { } public void saveAllocationManager(String filename) throws IOException { } public boolean unEnrol(String studentID, String moduleCode) throws InvalidIDException, IDNotRecognisedException { return false; } } <file_sep>message = "hello" name = "Michael the unready" print(message, name) <file_sep>public class Competition { static LongDistanceRunner runner1 = new LongDistanceRunner("red", 1, 10.0); static LongDistanceRunner runner2 = new LongDistanceRunner("blue", 2, 13.0); static String winner; public static void main( String[] args ) { headStart(runner2); printer(11.0); printer(9.0); printer(10.0); printer(30.0); printer(60.0); } public static void headStart(LongDistanceRunner runner) { runner.increaseTimeTravelled( - 10.0 ); } public static void runFor(double minutes, LongDistanceRunner runner1, LongDistanceRunner runner2) { runner1.increaseTimeTravelled( minutes ); runner2.increaseTimeTravelled( minutes ); } public static void printer(double minutes) { System.out.println("Second round: " + (runner1.getTimeTravelled() + minutes) + " minutes long"); runFor(minutes, runner1, runner2); System.out.println("the runner with the " + runner1.getVestColour() + " vest ran " + runner1.getDistanceTravelled() + " miles"); System.out.println("the runner with the " + runner2.getVestColour() + " vest ran " + runner2.getDistanceTravelled() + " miles"); winner = (runner1.getDistanceTravelled() > runner2.getDistanceTravelled()) ? runner1.getVestColour() : runner2.getVestColour(); System.out.println(winner + " won"); System.out.println(LongDistanceRunner.getMantra() + "\n"); } } <file_sep>from dsa import * from Q1 import depthFirst, breadthFirst from itertools import permutations from time import time from copy import deepcopy def build_tree(lst, T=new_tree(0, [], "0")): """ Creates and returns a tree-like structure containing the result of all the operations on all the possible subsets of a given list. lst = list of numbers used in the construction of the tree """ for e in lst: val = [] for op in [add, sub, mul, div]: current_branch = deepcopy(T) # prevents mutability of lists val.append(map_tree(current_branch, e, op)) for t in val: T = add_child(T, t) return T def map_tree(T, num, operation): """ apply a given operation with a given number to all the nodes and leaves of a given tree recursively T = tree num = number to be added to all nodes returns a tree """ if children(T) == []: # base case: leaf return new_tree(operation(value(T), num)[0], [], "(" + str(label(T)) + operation(value(T), num)[1] + str(num) + ")") else: # general case: node T = new_tree(operation(value(T), num)[0], children(T), "(" + str(label(T)) + operation(value(T), num)[1] + str(num) + ")") for c in range(len(children(T))): # recursive call children(T)[c] = map_tree(children(T)[c], num, operation) return T def add(n1, n2): """ Adds two given numbers, returns a tuple (<sum>, " + ") n1, n2 = numbers to be summed """ return (n1 + n2, " + ") def sub(n1, n2): """ Subtract two given numbers, returns a tuple (<subtraction>, " - ") n1, n2 = numbers to be subtracted """ return (n1 - n2, " - ") def mul(n1, n2): """ Multiply two given numbers, returns a tuple (<multiplication>, " x ") n1, n2 = numbers to be multiplied """ return (n1 * n2, " x ") def div(n1, n2): """ Divide two given numbers, returns a tuple (<division>, " / ") n1, n2 = numbers to be divided """ return (n1 / n2, " / ") def build_countdown_tree(L, T=new_tree(0, [], "0")): """ Creates a tree made of all the trees generated by build_countdown_tree() with all possible permutations of the given list L = list of numbers used to build the tree returns a tree """ L = list(permutations(L)) trees = [] for l in range(len(L)): trees.append(clean_tree(build_tree(L[l][1:], T=new_tree(L[l][0], [], str(L[l][0]))))) for t in trees: T = add_child(T, t) return T def clean_tree(tree): """ Given a tree returns a tree without all the nodes that have a negative or rational value and all children of such nodes tree = tree to be cleaned """ if children(tree) == []: # base case: leaf if value(tree) > 0 and value(tree) == int(value(tree)): return tree else: return new_tree(0, [], "0") else: # general case: node if value(tree) >= 0 and value(tree) == int(value(tree)): for c in range(len(children(tree))): children(tree)[c] = clean_tree(children(tree)[c]) else: return new_tree(0, [], "0") return tree if __name__ == "__main__": L1 = [12, 87, 8, 3, 4, 8] i1 = 724 t1 = build_countdown_tree(L1) print("List = " + str(L1)) print("Item: " + str(i1)) print("Result found with breadthFirst: ") print("Found by doing the following operations: " + str(breadthFirst(t1, i1)[1])) print() print("Result found with depthFirst: ") print("Found by doing the following operations: " + str(depthFirst(t1, i1)[1])) print() print() L2 = [62, 12, 7, 1, 5, 10] i2 = 130 t2 = build_countdown_tree(L2) print("List = " + str(L2)) print("Item: " + str(i2)) print("Result found with breadthFirst: ") print("Found by doing the following operations: " + str(breadthFirst(t2, i2)[1])) print() print("Result found with depthFirst: ") print("Found by doing the following operations: " + str(depthFirst(t2, i2)[1])) <file_sep>from dsa import * from random import random from copy import deepcopy counter = 0 def build_sum_tree(lst): """ Creates and returns a tree-like structure containing the sums of all the possible subsets of a given list. lst = list of numbers used in the construction of the tree """ T = new_tree(0, [], "0") for e in lst: current_branch = deepcopy(T) # needed to prevent mutabilty of lists in python val = map_sum(current_branch, e) T = add_child(T,val) return T def map_sum(T, num): """ sum a given number to all the nodes and leaves of a given tree recursively T = tree num = number to be added to all nodes returns a tree """ if len(children(T)) == 0: # base case: leaf return new_tree(value(T) + num, [], str(label(T)) + " + " + str(num)) else: # general case: node T = new_tree(value(T) + num, children(T), str(label(T)) + " + " + str(num)) for c in range(len(children(T))): children(T)[c] = map_sum(children(T)[c], num) # recursive call return T def compare(x, y): """ Returns the equality comparison between two given variables, increases a global variable by 1 for each call of the function. Used to calculate complexity using the number of comparison as parameter x, y = items to be compared """ global counter counter += 1 return x == y def depthFirst(tree, item): """ Searches a tree using a "depth first" algorithm, implemented using the stack data structure. Returns the element and its parent nodes if the given item is in the tree, returns the closest element (and parent nodes) to the given item otherwise. tree = tree used in the search item = item searched in the tree caveats: since the function is designed to search in a tree of numbers, an error will occur if a different tree in passed as argument, this is due to the fact that it tries to return the "closest" element defined as numerically closest to the given item. returns a tuple (<item found>, <path used to find the item>) """ stack = push(tree, []) # push tree on empty stack current_node = top(stack) closestDifference = (9999999, label(tree), value(tree)) # initialises a closestDifference variable with an arbitrarily big number while not (not stack or compare(item, value(current_node))): # if the item has not been found or if the function hasn't gone through all the nodes of tree if abs(value(current_node) - item) < closestDifference[0] and not compare(value(current_node), 0): closestDifference = (abs(value(current_node) - item), label(current_node), value(current_node)) stack = pop(stack) if children(current_node): # if the node has children for c in children(current_node): # adds all the children on top of the stack stack = push(c, stack) current_node = top(stack) if not stack: # couldn't find the item return (str(closestDifference[2]), str(closestDifference[1])) else: # the item was found return (str(item), str(label(current_node))) def breadthFirst(tree, item): """ Searches a tree using a "breadth first" algorithm, implemented using the stack data structure. Returns the element and its parent nodes if the given item is in the tree, returns the closest element (and parent nodes) to the given item otherwise. tree = tree used in the search item = item searched in the tree caveats: since the function is designed to search in a tree of numbers, an error will occur if a different tree in passed as argument, this is due to the fact that it tries to return the "closest" element defined as numerically closest to the given item. returns a tuple (<item found>, <path used to find the item>) """ queue = enqueue(tree, []) # enqueue tree on empty queue current_node = head(queue) closestDifference = (9999999, label(tree), value(tree)) # initialises a closestDifference variable with an arbitrarily big number while not (not queue or compare(item, value(current_node))): # if the item has not been found or if the function hasn't gone through all the nodes of tree if abs(value(current_node) - item) < closestDifference[0] and not compare(value(current_node), 0): closestDifference = (abs(value(current_node) - item), label(current_node), value(current_node)) queue.pop(0) # works the same way as queue = tail(queue), but it's much faster because of how python deals with lists if children(current_node): # if the node has children for c in children(current_node): # adds all the children on top of the stack queue.append(c) # same as enqueue, but faster. current_node = head(queue) if not queue: # couldn't find the item return (str(closestDifference[2]), str(closestDifference[1])) else: # the item was found return (str(item), str(label(current_node))) def randomList(n): """ Generates a random list of numbers of length n given as parameter. The numbers are taken from the interval [1, 100] n = length of the list generated returns a list of length n """ L = [] for i in range(n): num = int(random()*100//1 + 1) L.append(num) return L def resetCounter(): """ Resets the global variable used for complexity calculations """ global counter counter = 0 def getCounter(): """ Returns the global variable used for complexity calculations """ return counter <file_sep> /** * Write a description of interface Tiger here. * * @author (your name) * @version (a version number or a date) */ public interface Tiger { int countStripes(); boolean isMale(); } <file_sep>def make_anagram_dict(words): """ Given a list of words it returns a dictionary where the keys are the letters of a word in alphabetical order and the values are lists of all the words that are made of such letters in some order. i.e. all the words corresponding to a certain key are anagrams words = list of words All words in the list are lower-cased, meaning that some of them were removed if duplicates """ D = {} for word in words: word = word.strip().lower() key = "".join(sorted(word)) # the key is the letters of the word in alphabetical order try: if word not in D[key]: D[key].append(word) except KeyError: D[key] = [word] return D if __name__ == "__main__": # when run as a program File = open("words.txt", "r").readlines() Dict = make_anagram_dict(File) max_anagrams = 0 # number of anagrams of the letters with most anagrams max_length = 0 # length of longest words that are anagrams for k, v in Dict.items(): # k = key, v = value if len(v) > max_anagrams: max_anagrams = len(v) word_variants = [v] elif len(v) == max_anagrams: word_variants.append(v) if len(k) > max_length and len(v) >= 2: # the letters must have at least 2 values: 2 words that are anagrams of each other max_length = len(k) longest_words = [v] elif len(k) == max_length and len(v) >= 2: longest_words.append(v) print("The words with most anagrams have %s anagrams and are: " % max_anagrams) for words in range(len(word_variants)): print(" ".join(word_variants[words])) print("\n" * 2) # 2 rows space between the prints print("The longest words that have an anagram are %s characters long and are: " % max_length) for words in range(len(longest_words)): print(" ".join(longest_words[words])) <file_sep>from exturtle import * from drawmaze import draw, hexagon def read(filename): """ Given a file with the information necessary to build a maze (size of the maze on the first line and forbidden cells in the other lines) the function initialize the variables: size: cells for each side forbidden: dictionary of forbidden cells filename = name of the file used to create the dictionary """ size = 0 forbidden = {} lines = open(filename, "r").readlines() for line in lines: line = line.strip() if len(line) <= 2: size = int(line) elif len(line) > 2: line = line.split( ) forbidden[(int(line[0]), int(line[1]))] = 1 return size, forbidden def search(path, forbidden, shortest, longest): """ Using a recursive method it calculates all the shortest paths and all the longest paths to get from the cell (0,0) to the last cell (opposite corner) The base case is reached when the program gets to the end of the maze and with each step it gets closer to the end (since it cannot go to a cell where it was already been) path = current path forbidden = dictionary of forbidden cells shortest = list of shortest paths longest = list of longest paths """ if path[-1] == (size -1, size -1): # base case - then checks the length of the path used and compare it with longest and shortest if len(path) == len(shortest[0]): shortest.append(path) elif len(path) == len(longest[0]): longest.append(path) elif len(path) < len(shortest[0]): shortest = [path] return shortest, longest elif len(path) > len(longest[0]): longest = [path] return shortest, longest position = path[-1] for neighbour in neighbours(position): if neighbour not in forbidden.keys() and neighbour not in path: # the cell must not be a forbidden cell and must not be an already-used cell nextpath = path[:] # copies path nextpath.append((neighbour[0], neighbour[1])) values = search(nextpath, forbidden, shortest, longest) shortest.insert(0, values[0][0]) longest.insert(0, values[1][0]) # "cleans" the lists shortest and longest and removes everything that is not as long as the longest/shortest used = [] longest = [i for i in longest if len(i) == len(longest[0]) and i not in used and (used.append(i) or True)] shortest = [i for i in shortest if len(i) == len(shortest[0]) and i not in used and (used.append(i) or True)] return shortest, longest def neighbours(coordinates): """ Given a position (x,y) in the maze it returns all the valid neighbours cells to the given cells coordinates = coordinate of the cell as a tuple (x, y) """ x, y = coordinates valid_n = [] # depending on whether the y coordinate is even or odd the possible neighbour cells are different if y % 2 == 1: # if odd possible_n = [(x - 1, y - 1), (x - 1, y), (x - 1, y + 1), (x, y + 1), (x + 1, y), (x, y - 1)] else: # if even possible_n = [(x, y - 1), (x - 1, y), (x, y + 1), (x + 1, y + 1), (x + 1, y), (x + 1, y - 1)] for coord in range(len(possible_n)): # checks which of the possible cells are valid (inside the maze) x, y = possible_n[coord] if x >= 0 and x < size and y >= 0 and y < size: valid_n.append((x, y)) return valid_n def draw_path(turtle, path, sep=40, colour="green"): """ The function draws one path in a given list of paths by drawing the hexagons corresponding to each coordinate in the path filled with a given colour turtle = turle to be used for drawing path = list paths sep = size of each hexagon, 40 by default colour = colour used to fill the hexagons, green by default """ for x, y in path[0]: x_coord = (x-(y % 2) / 2)*sep y_coord = y*3**(1/2)*sep/2 hexagon(turtle, x_coord, y_coord, hw=sep/2, fill=colour, text='%d,%d' % (x,y)) if __name__ == "__main__": A = Turtle() speed(A, 0) size, forbidden = read("small.txt") draw(A, size, forbidden) path = [(0,0)] # initializes starting point in the maze shortest = ["X" * size ** 2] # initializes the shortest list longest = ["X"] # initializes the longest list shortest, longest = search(path, forbidden, shortest, longest) for pth in shortest: # prints all the shortest paths print(pth) print(len(pth)) for pth in longest: # prints all longest paths print(pth) print(len(pth)) draw_path(A, shortest) draw_path(A, longest, colour="orange") mainloop() <file_sep>from dsa import * from random import random counter = 0 tree = [] def build_sum_tree(lst): L = [] if len(lst) == 1: return lst else: lenlist = len(lst) for i in range(lenlist): L = [] for k in range(lenlist - i - 1): L.append(lst[i] + lst[-k - 1]) L.insert(0, lst[i]) lst[i] = L print(lst) return(lst) def compare(x, y): # counter += 1 return x == y def depthFirst(tree, item): return def breadthFirst(tree, item): return def randomList(n): # L = [] for i in range(n): num = int(random()*100//1) L.append(num) return L print(build_sum_tree(build_sum_tree(["a", "b", "c"]))) <file_sep>from Q1 import randomList, depthFirst, breadthFirst, build_sum_tree def searchdemo(n): L = randomList(n) tree = build_sum_tree(L) print("L = " + str(L)) print() print("Using DepthFirst:") print(depthFirst(tree, n**2, verbose=True)) print() print("Using BreadthFirst:") print(breadthFirst(tree, n**2, verbose=True)) print("\n" * 3) if __name__ == "__main__": for n in [3, 5, 7]: searchdemo(n) <file_sep>def Fib(n): print("passing n = ", n) if n > 1: k = Fib(n - 1) + Fib(n - 2) print("k is = ", k) return k elif n == 1: return 1 elif n == 0: return 0 def Fib2(n, D): print(n) print(D) try: k = D[n] except: k = Fib2(n - 1, D) + Fib2(n - 2, D) D[n] = k return k D = {0: 0, 1: 1} # print(Fib(12)) print(Fib2(12, D)) print(D) <file_sep>def word_count(L): words = len(L) chars = 0 for i in L: chars += len(i) return words, chars rhyme = ["Mary", "had", "a", "little", "lamb", "whose", "fleece", "was", "white", "as", "snow"] print(word_count(rhyme)) <file_sep>package cards; import java.util.*; import java.util.stream.*; /** * Write a description of class PontoonApp here. * * @author (your name) * @version (a version number or a date) */ public class PontoonApp { static Scanner input = new Scanner(System.in); static boolean gameOver = false; static boolean HSwing = false; static boolean CSwing = false; public static void main(String[] args){ Card[] deck = Card.getDeck(); deck = shuffle(deck, 50); Card[] humanDeck = new Card[15]; Card[] computerDeck = new Card[15]; int cardsUsedH = 0; int cardsUsedC = 0; while ((!gameOver) && (cardsUsedH + cardsUsedC < 50)){ System.out.print("Your "); printDeck(humanDeck); System.out.print("Computer "); printDeck(computerDeck); System.out.println(); System.out.print("Do you want another card? (y/n)"); String yesOrNo = input.next(); if (yesOrNo.equals("y")){ humanDeck[cardsUsedH++] = deck[cardsUsedH + cardsUsedC]; HSwing = true; } int humanSum = 0; for (Card c: humanDeck){ if (c != null){ humanSum += (int)c.rank.getCardNumericalValue(); } } if (humanSum > 21){ System.out.println("You lost!"); gameOver(); } if (toSwingOrNotToSwing(deck, computerDeck, humanDeck[0], cardsUsedH + cardsUsedC)){ computerDeck[cardsUsedC++] = deck[cardsUsedH + cardsUsedC]; CSwing = true; } int computerSum = 0; for (Card c: computerDeck){ if (c != null){ computerSum += (int)c.rank.getCardNumericalValue(); } } if (computerSum > 21 && !gameOver){ System.out.println("You won!"); gameOver(); } isOver(humanSum, computerSum); System.out.println(); System.out.println(); } System.out.println("Final Decks"); printDeck(humanDeck); printDeck(computerDeck); } private static Card[] shuffle(Card[] deck, int shuffles){ int counter = 0; Random r = new Random(); while (counter < shuffles){ int swapIndex1 = r.nextInt(52); int swapIndex2 = r.nextInt(52); Card tempCard = deck[swapIndex1]; deck[swapIndex1] = deck[swapIndex2]; deck[swapIndex2] = tempCard; counter++; } return deck; } private static void gameOver(){ gameOver = true; } private static void printDeck(Card[] deck){ System.out.print("deck is ["); for (Card c: deck){ if (c != null){ System.out.print(c.rank.toString() + "-" + c.suit.toString() + " "); } } System.out.println("] "); } private static boolean toSwingOrNotToSwing(Card[] wholeDeck, Card[] pcCards, Card visibleHumanCard, int cardsUsed){ int sum = 0; for (Card c: pcCards){ if (c != null){ sum += (int)c.rank.getCardNumericalValue(); } } double averageNextPick = (380 - sum - visibleHumanCard.rank.getCardNumericalValue()) / (52 - cardsUsed); if (sum + averageNextPick > 21){ return false; } return true; } private static void isOver(int humanSum, int compSum){ if (!HSwing && !CSwing){ if((21 - humanSum) < (21 - compSum)){ System.out.println("You Won"); } else if ((21 - humanSum) == (21 - compSum)){ System.out.println("Draw"); } else { System.out.println("You Lost"); } gameOver(); } HSwing = false; CSwing = false; } } <file_sep>from random import random from draw import Draw word = "" used_letters = [] lives = 10 def check_new_letter(letter): global used_letters if letter in used_letters: return False used_letters.append(letter) return True def check_letter(letter): positions = [] if not check_new_letter(letter): print("You already tried this letter") positions.append(3) return [] for i in range(len(word)): if letter == word[i]: positions.append(i) if positions == []: global lives print("The letter is not in the word") Draw(lives) lives -= 1 return positions def pick_a_word(): Open = open("words.txt", "r") Lines = Open.readlines() chosen = Lines[int(random() * len(Lines))] return chosen.strip() def play(two_players=True): global word if two_players: word = input("Write a word: ").lower() else: word = pick_a_word() guessed = ["_"] * len(word) print() while "_" in guessed: for l in guessed: print(l, end=" ") print() print(lives, "lives left") print("\n" * 2) lett = "" while len(lett) != 1: lett = input("Guess ONE letter: ").lower() for position in check_letter(lett): guessed[position] = lett if lives == 0: print("You lost!!") quit() to_print = "".join([str(x) for x in guessed]) print("You Won, the word was: ", '"', to_print, '"') quit() play(False) mainloop() <file_sep>from exturtle import * from math import cos, sin, pi # General note: X-axis and Y-axis are inverted so that all the stars point # up and not right def get_coord(n, Cx, Cy, points, R, r): """ The function returns for a given n (natural number) the coordinates of the point and the corner associated to that n in a for loop Arguments: n = iterating variable Cx, Cy = coordinates of the centre of the star points = number of points of the star R = outer radius (radius of the circle passing by the points) r = inner radius (radius of the circle passing by the corners) The function can be used to find the coordinates of the centres of the stars in a ring of stars by using the coordinates of the points """ delta = 2*pi/points PointY = R*cos(delta*(n + 1)) + Cy PointX = R*sin(delta*(n + 1)) + Cx CornerY = r*cos((n + 1/2) * delta) + Cy CornerX = r*sin((n + 1/2) * delta) + Cx return PointX, PointY, CornerX, CornerY def star(turtle, x, y, points, R, r): """ The function draws a single star, it uses the function get_coord to find the coordinates of all the points and corners Takes as arguments: turtle = the name of the turtle x, y = centre of the star points = number of points of the star R = outer radius (radius of the circle passing by the points) r = inner radius (radius of the circle passing by the corners) """ startY = y + R penup(turtle) goto(turtle, x, startY) # moves the turtle to the first point of the star pendown(turtle) for n in range(points): Px, Py, Cx, Cy = get_coord(n, x, y, points, R, r) goto(turtle, Cx, Cy) goto(turtle, Px, Py) def ring(turtle, cx, cy, Nstars, radius, points, R, r): """ The function draws a circle of stars by using the function star to draws every single star and the function get_coord to find the centre of each star Takes as arguments: turtle = the name of the turtle cx, cy = centre of the ring of stars Nstars = number of stars in the ring radius = radius of the ring points = number of points in each star R = outer radius of each star (radius of the circle passing by the points) r = inner radius of each star (radius of the circle passing by the corners) """ for i in range(Nstars): fillcolor(turtle, "yellow") # fill stars with yellow begin_fill(turtle) Cx, Cy, nn, NN = get_coord(i, cx, cy, Nstars, radius, r) # the variables nn and NN are not used in this function, they just # contain the two value returned by get_coord which are not needed here star(turtle, Cx, Cy, points, R, r) end_fill(turtle) bob = Turtle() star(bob, -300, 250, 5, 25, 12.5) star(bob, -250, 250, 6, 25, 12.5) star(bob, -200, 250, 7, 25, 12.5) star(bob, -150, 250, 8, 25, 12.5) ring(bob, 0, 0, 12, 200, 5, 25, 10) mainloop() <file_sep>public class RaceTestApp { public static void main(String[] args) { // Declare array to hold two RaceParticpant objects RaceParticipant[] racers = new RaceParticipant[2]; // Instantiate zeroth element as an EggAndSpoonRaver racers[0] = new EggAndSpoonRacer("Barney", "Rubble", "<NAME>", 51.2, true); // Instantiate oneth element as a SackRacer racers[1] = new SackRacer("Wilma", "Flintsone", "<NAME>", 1.1); /* print racer's details to the screen, using the overrided printInfo methods */ racers[0].printInfo(); racers[1].printInfo(); } }<file_sep>from bisect import * def insert(key, value, D, hasher=hash): """ Adds to a dictionary-like list a tuple (hashed key, key, value) if an entry with the same key already exists its value is replaced with the the new one The addition in performed in place, the function returns 'None' key = key of the entry value = value corresponding to the key D = list of tuples, non built-in dictionary hasher = function to use to hash the key, built-in hasher by default """ try: pop(key, D, hasher) # tries to pop except KeyError: pass entry = (hasher(key), key, value) insort(D, entry) #inserts an element leaving the list sorted return None def get(key, D, hasher=hash): """ Returns the value corresponding to a given key key = used to search for the value requested D = dictionary-list used for the search hasher = function to use to hash the key, built-in hasher by default raises KeyError if the specified key is not in the dictionary """ try: i = find_index(D, (hasher(key), key)) # finds the index of the first (and only) entry in D with given key return D[i][2] except: raise KeyError def pop(key, D, hasher=hash): """ Removes the entry corresponding to a given key from the dictionary and returns the tuple (key, value) key = used to search for the value requested D = dictionary-list used for the search hasher = function to use to hash the key, built-in hasher by default raises KeyError if the specified key in not in the dictionary """ try: index = find_index(D, (hasher(key), key)) # finds the index of the first (and only) entry in D with given key popped = D.pop(index) return (popped[1], popped[2]) except: raise KeyError def keys(D): """ Returns a list of all the keys in a given dictionary D D = dictionary-list """ keys = [] for element in D: keys.append(element[1]) return keys def values(D): """ Returns a list of all the values in a given dictionary D D = dictionary-list """ values = [] for element in D: values.append(element[2]) return values def items(D): """ Returns a list of all the tuples (key, value) in a given dictionary D D = dictionary-list """ items = [] for element in D: items.append((element[1], element[2])) return items def poorhash(x): """ A worse version of the built-in hash function, it can only return 10 numbers x = value to hash """ return hash(x) % 10 def test_keys(D): """ A function built to test the proper functioning of the "keys" function. It checks the following conditions, if all of them are verified it returns True, otherwise it returns False: - every tuple in the dictionary must return a key (same length) - every key in the dictionary must be in the keys returned by "keys" D = dictionary used for the test """ keys_list = keys(D) if len(keys_list) != len(D): # length return False for entry in D: # 2nd condition if entry[1] not in keys_list: return False return True def test_values(D): """ A function built to test the proper functioning of the "values" function. It checks the following conditions, if all of them are verified it returns True, otherwise it returns False: - every tuple in the dictionary must return a value (same length) - every value in the dictionary must be in the values returned by "values" D = dictionary used for the test """ values_list = values(D) if len(values_list) != len(D): #length return False for entry in D: # 2nd condition if entry[2] not in values_list: return False return True def test_items(D): """ A function built to test the proper functioning of the "items" function. It checks the following conditions, if all of them are verified it returns True, otherwise it returns False: - every tuple in the dictionary must return a tuple (same length) - every tuple (key, value) in the dictionary must be in the elements returned by "items" D = dictionary used for the test """ items_list = items(D) if len(items_list) != len(D): #length return False for entry in D: # second condition if (entry[1], entry[2]) not in items_list: return False return True def test_pop(D, hasher=hash): """ A function devised to test the correct functioning of the "pop" function. It tries to pops, key by key, all the elements in a given dictionary, if it encounters a KeyError it returns False, otherwise it returns True D = dictionary used for the test hasher = function to use to hash the key, built-in hasher by default """ Dc = D[:] keys_list = keys(D) try: for key in keys_list: # tries to pop all the keys pop(key, Dc, hasher) except KeyError: return False return True def test_get(D, hasher=hash): """ A function devised to test the correct functioning of the "get" function. It tries to get all the values in the dictionary using the function get, if it encounters a KeyError or the value doesn't correspond to the right key it returns False, otherwise it returns True D = dictionary used for the test hasher = function to use to hash the key, built-in hasher by default """ items_list = items(D) try: for key, value in items_list: # tries to get all the values and checks if they correspond to each key if get(key, D, hasher) != value: return False except KeyError: return False return True def test_insert(D, hasher=hash): """ Given a dictionary-like list D the function tries to insert an entry to it, if the entry is really in the dictionary and the dictionary is properly sorted it returns True, otherwise it returns False D = dictionary used for the test hasher = function to use to hash the key, built-in hasher by default """ key = "a key" value = "some value" Dc = D[:] insert(key, value, Dc, hasher) if (hasher(key), key, value) not in Dc: # checks the presence return False if sorted(Dc) != Dc: # checks sorting return False return True def find_index(D, element): """ the function returns the index in a list D of tuples (a, b, c) starting with (a, b) L = list of elements element = element used for the search, in the form (a, b) (as a tuple) if no such element can be found in D a KeyError error is raised """ entry = (element[0], element[1], 0) index = bisect_left(D, entry) in_D = D[index] if index != len(D) and in_D[0] == entry[0] and in_D[1] == entry[1]: return index raise KeyError if __name__ == "__main__": test_dict = sorted([(poorhash("key 1"), "key 1", 1), (poorhash("key 2"), "key 2", 2), (poorhash("key 3"), "key 3", 3), (poorhash("key 4"), "key 4", 4), (poorhash("key 5"), "key 5", 5)]) functions_1 = keys, values, items functions_2 = get, pop print("Dictionary used for the test:") for e in test_dict: # prints the dictionary print(e) print("\n" * 2) for func in functions_1: # runs the test of each function and prints their output name = func.__name__ print("testing '%s':" % name) print(" test function response = ", "Positive" if eval("test_" + name + "(test_dict)") else "Negative") print(name + ":") for e in func(test_dict): print(" " + str(e)) print("\n" * 2) print("testing 'insert':") # tests inserting a new value and shows the process print(" test function response = ", "Positive" if test_insert(test_dict, poorhash) else "Negative") print() print("inserting a new entry: ('key 6', 6)") insert("key 6", 6, test_dict, poorhash) for e in test_dict: print(" ", e) print() print("('key 6', 6) is now in the dictionary and the dictionary is still correctly sorted") print("\n" * 2) for func in functions_2: # runs the test of each function and prints their output on each key name = func.__name__ print("testing '%s':" % name) print(" test function response = ", "Positive" if eval("test_" + name + "(test_dict, poorhash)") else "Negative") print() for key in keys(test_dict): print(" " + name + name[-1] + "ing '%s' returns '%s'" % (key, func(key, test_dict, poorhash))) print("\n" * 2) <file_sep>class Histogram(): def __init__(self, L, resolution=0.3): self.L = L self.resolution = resolution def histogram(self, x, percentage, resolution=1): resolution = 1 / resolution for i in x: percent = int(percentage[i] * resolution) print(i, "*" * percent, " " * 4, percent/resolution) def histogram_lenghts(self): H = [] for i in self.L: if len(i) > len(H): H.extend([0] * (len(i) - len(H))) H[len(i) - 1] += 1 return H def heights_percent(self, Heights): P = [] P.extend([0] * (len(Heights))) counter = 0 for i in Heights: P[counter] = i / sum(Heights) * 100 counter += 1 return P def Heights_draw(self): x = range(len(self.L)) percent = self.heights_percent(self.L) self.histogram(x, percent, self.resolution) <file_sep>from dsa import * from random import random tree = new_tree(0,[]) counter = 0 def build_sum_tree(lst, T = new_tree(0, [], "base node")): global tree if len(lst) == 0: #print("base case") return T for e in lst: #print(str(tree)) try: T = add_child(T, new_tree(T[0] + e, [])) except: return tree #print("tree after child added: " + str(T)) for child in range(len(children(T))): #print (children(T)) #print(lst[child + 1:]) tree = add_child(tree, build_sum_tree(lst[child + 1:], children(T)[child])) return T def compare(x, y): # counter += 1 return x == y def depthFirst(tree, item): return def breadthFirst(tree, item): return def randomList(n): # L = [] for i in range(n): num = int(random()*100//1) L.append(num) return L print(build_sum_tree([1, 2, 3, 4])) <file_sep> /** * This is the Suits Example taken from Nino and Hosch p220. * It is deliberately misleading, in that the execution "falls * through" (cascades) to subsequant statements when we don't want * it to * * Needs single integer argument if run at the command line * after compilation, e.g. * * java SuitsExample 3 * * @author <NAME> (plus Nino and Hosch) * @version 1.0 */ public class SuitsExample { public static final int CLUB = 1; public static final int DIAMOND = 2; public static final int HEART = 3; public static final int SPADE = 4; public static void main( int[] args ) { // int suit = Integer.parseInt(args[0]); int suit = args[0]; int redCardCount = 0, spadeCount = 0, blackCardCount = 0, cardCount = 0; switch (suit) { case DIAMOND : case HEART : redCardCount = redCardCount + 1; break; case SPADE : spadeCount = spadeCount + 1; case CLUB : blackCardCount = blackCardCount + 1; break; default: cardCount--; System.out.println("The program will only count suited cards, not any piece of paper!"); } cardCount = cardCount + 1; System.out.println("number of red cards " + redCardCount); System.out.println("number of spades " + spadeCount); System.out.println("number of black cards " + blackCardCount); System.out.println("number of cards " + cardCount); System.out.println(); } } <file_sep>// MultiArgumentPrintingApp application // Your name or student number here // The date class MultiArgumentPrintingAppFOREACH { public static void main(String[] args){ for ( String s : args ) { System.out.println(s); } } } <file_sep>def zipper(a, b): if len(a) != len(b): return "LISTS ARE NOT OF THE SAME LENGHT" NL = [] for i in range(len(a)): NL.append([a[i], b[i]]) return NL l1 = [3, 4, 5, 6] l2 = ["a", "b", "c", "d"] print(zipper(l1, l2)) <file_sep> /** * Write a description of class TestApp here. * * @author (your name) * @version (a version number or a date) */ public class TestApp { public static void main(String[] args){ testConstructor(); } public static void testConstructor(){ System.out.println("constructing"); BasicRectangle[] basic = new BasicRectangle[10000]; CachedRectangle[] cached = new CachedRectangle[10000]; LazyRectangle[] lazy = new LazyRectangle[10000]; long t0 = System.nanoTime(); for (int i = 0; i < 10000; i++){ basic[i] = new BasicRectangle(2*i, 3+i); } long t1 = System.nanoTime(); for (int i = 0; i < 10000; i++){ cached[i] = new CachedRectangle(2*i, 3+i); } long t2 = System.nanoTime(); for (int i = 0; i < 10000; i++){ lazy[i] = new LazyRectangle(2*i, 3+i); } long t3 = System.nanoTime(); System.out.println("basic 10000 times: " + (t1-t0)); System.out.println("cached 10000 times: " + (t2-t1)); System.out.println("lazy 10000 times: " + (t3-t2)); System.out.println(); } public static void testGetArea1(){ //no changes in sizes System.out.println("getting same area without changing anything"); BasicRectangle basic = new BasicRectangle(); CachedRectangle cached = new CachedRectangle(); LazyRectangle lazy = new LazyRectangle(); long t0 = System.nanoTime(); for (int i = 0; i < 10000; i++){ basic.getArea(); } long t1 = System.nanoTime(); for (int i = 0; i < 10000; i++){ cached.getArea(); } long t2 = System.nanoTime(); for (int i = 0; i < 10000; i++){ lazy.getArea(); } long t3 = System.nanoTime(); System.out.println("basic 10000 times: " + (t1-t0)); System.out.println("cached 10000 times: " + (t2-t1)); System.out.println("lazy 10000 times: " + (t3-t2)); System.out.println(); } public static void testGetArea2(){ //change sizes and get area System.out.println("getting area changing sizes"); BasicRectangle basic = new BasicRectangle(); CachedRectangle cached = new CachedRectangle(); LazyRectangle lazy = new LazyRectangle(); long t0 = System.nanoTime(); for (int i = 0; i < 10000; i++){ basic.setWidth(3*i); basic.setHeight(3+i); basic.getArea(); } long t1 = System.nanoTime(); for (int i = 0; i < 10000; i++){ cached.setWidth(3*i); cached.setHeight(3+i); cached.getArea(); } long t2 = System.nanoTime(); for (int i = 0; i < 10000; i++){ lazy.setWidth(3*i); lazy.setHeight(3+i); lazy.getArea(); } long t3 = System.nanoTime(); System.out.println("basic 10000 times: " + (t1-t0)); System.out.println("cached 10000 times: " + (t2-t1)); System.out.println("lazy 10000 times: " + (t3-t2)); System.out.println(); } }<file_sep>sumSquare = 0 squareSum = 0 for i in range(1, 101): sumSquare = sumSquare + i**2 squareSum = squareSum + i print(i) print("somma quadrati = ", sumSquare, "quadrato somma = ", squareSum**2, "differenza = ", (squareSum**2 - sumSquare)) <file_sep>from anagram import make_anagram_dict import string from sys import argv def blanagram(word, anagramdict): """ Given a word and dictionary of anagrams it returns all the blanagrams of the given word. a blanagram is an anagram where a single letter is replaced by any other letter in the alphabet word = word to be used to find all the blanagrams anagramdict = dictionary of anagrams """ letters = string.ascii_lowercase blanagrams = [] used_keys = [] for i in range(len(word)): for letter in letters: new_word = word[0:i] + letter + word[i + 1:] #creates a new word by replacing one letter key = "".join(sorted(new_word)) # the key is the letters of the word in alphabetical order if "".join(sorted(word)) != key and key not in used_keys: # prevents that anagrams are considered blanagrams and repetitions try: blanagrams.extend(anagramdict[key]) except KeyError: continue used_keys.append(key) return sorted(blanagrams) # all the blanagrams in alphabetical order if __name__ == "__main__": if len(argv) < 2: # guardian statement print("please give information in the following order:") print("python blanagram.py <length of blanagrams>") quit() # calculate the word with given length with most blanagram D = make_anagram_dict(open("words.txt", "r")) max_length = 0 blanagram_list = [] keys = [] for k, v in D.items(): if len(k) == int(argv[1]): blanagrams = blanagram(k, D) if len(blanagrams) > max_length: keys = v max_length = len(blanagrams) blanagram_list = [blanagrams] elif len(blanagrams) == max_length: keys.extend(v) blanagram_list.append(blanagrams) print("The words that are %s characters long and are blanagrams to each other are %s:" % (argv[1], max_length), "\n") for blan in range(len(blanagram_list)): print("word: ", keys[blan]) print(" ".join(blanagram_list[blan])) print() <file_sep>from exturtle import * T = Turtle() tries = 10 def Draw(tries): if tries ==10: T.fd(50) T.backward(100) T.fd(50) if tries ==9: T.lt(90) T.fd(150) if tries ==8: T.rt(90) T.fd(80) if tries ==7: T.backward(40) T.rt(135) T.fd(57) penup(T) T.goto(80,150) pendown(T) T.lt(45) if tries ==6: T.fd(20) if tries ==5: T.rt(90) circle(T, 15) T.lt(90) penup(T) T.fd(30) pendown(T) if tries ==4: T.lt(90) T.fd(50) T.backward(100) T.fd(50) T.rt(90) if tries ==3: T.fd(30) if tries ==2: T.lt(45) T.fd(50) T.backward(50) T.rt(90) if tries ==1: T.fd(50) <file_sep>def lsum(L): print("using L = ", L) if len(L) == 1: return L[0] else: return L.pop(0) + lsum(L) L = [10, 10, 10, 100] print(lsum(L)) <file_sep> PROJECT TITLE: ConditionalExamples PURPOSE OF PROJECT: Collection of classes used when demonstrating conditionals VERSION or DATE: 1.0 HOW TO START THIS PROJECT: Each class is a program, can be run by the command line, or right-clicking and selecting main method if using the BlueJ IDE in workshops AUTHORS: <NAME> (some classes based on textbook code by <NAME> and <NAME>) USER INSTRUCTIONS: Please refer to source of individual programs <file_sep>package university; import java.io.FileInputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.Serializable; import java.io.ObjectOutputStream; import java.io.FileOutputStream; /** * Implementation of the interface @see AllocationManager. *<p> * The class defines the UniversityAllocationManager object, * designed to manage a university, linking students, staff and modules * and helping to have an overview of the running modules, staff involved in * every module and students that already have sufficient credits. * Is also possible to save and load an instance of the object * </p> * * @author 660042108 & 660001833 * @version 1.1 */ public class UniversityAllocationManager implements AllocationManager, Serializable { private ObjectArrayList studentsArray; private ObjectArrayList staffArray; private ObjectArrayList modulesArray; private ObjectArrayList connectionsArray; /** * Default constructor of the class, generates and instance without any * students, staff members or modules */ public UniversityAllocationManager () { this.studentsArray = new ObjectArrayList(); this.staffArray = new ObjectArrayList(); this.modulesArray = new ObjectArrayList(); this.connectionsArray = new ObjectArrayList(); } /** * Constructor of the class that accepts arrays of prebuilt staff, students and modules: * * @param staff An array of staff member of type Staff * @param students An array of students of type Student * @param modules An array of modules of type Module */ public UniversityAllocationManager (Staff[] staff, Student[] students, Module[] modules, Connection[] connectionsArray) { this.studentsArray = new ObjectArrayList(); this.staffArray = new ObjectArrayList(); this.modulesArray = new ObjectArrayList(); this.connectionsArray = new ObjectArrayList(); // adding all the elements of the arrays to the manager for (Staff s: staff) { try{ this.addStaff(s); } catch(IDAlreadySetException e) { assert false; //Should not reach point: method assume correct prebuilt arrays } } for (Student s: students) { try{ this.addStudent(s); } catch(IDAlreadySetException e) { assert false; //Should not reach point: method assume correct prebuilt arrays } } for (Module m: modules) { try{ this.addModule(m); } catch(IDAlreadySetException e) { assert false; //Should not reach point: method assume correct prebuilt arrays } } for (Connection c: connectionsArray){ this.addConnection(c); } } /** * @inheritDoc */ public String addStudent(String forename, String surname, byte stage) throws InvalidStageException { Student s = new StudentClass(stage, forename, surname); try { addStudent(s); }catch (IDAlreadySetException e){ assert false; //Student object just created. No ID should be set } return s.getID(); } /** * @inheritDoc */ public void addStudent(Student student) throws IDAlreadySetException { String lastID; // Generates the ID for the student (10 digits long int) try { lastID =((Student) studentsArray.get(studentsArray.size() - 1)).getID(); } catch(NullPointerException e){ lastID = "0000000000"; } // puts it in a 10 digits long string String newID = String.format("%1$010d", (Integer.parseInt(lastID) + 1)); try { student.setID( newID ); } catch(InvalidIDException e ){ assert false; //ID just programmatically created, should never be invalid } studentsArray.add(student); } /** * @inheritDoc */ public String addModule(String name, byte credits, byte stage, int capacity, Staff[] staff) throws InvalidStageException, InvalidCreditsException, InvalidCapacityException, DuplicateStaffException, StaffNotInSystemException { if (credits < 0 || credits > 120){ throw new InvalidCreditsException("Invalid number of credits, not in range 0-120"); } if (capacity < 1){ throw new InvalidCapacityException("Capacity invalid (negative or 0)"); } for(Staff s: staff){ if (! contains(this.getStaff(), s)){ throw new StaffNotInSystemException("One member of the staff is not in the system"); } } ModuleClass m = new ModuleClass(); try{ m = new ModuleClass(name, stage, staff, capacity, credits); addModule(m); }catch(IDAlreadySetException | IDNotSetException e){ assert false; //IDAlreadySetException: new module object declared, no ID should be set //IDNotSetException: checked earlier if all staff members are a part of the system. All // members of the system should have IDs } return m.getCode(); } /** * @inheritDoc */ public void addModule(Module module) throws IDAlreadySetException { String lastCode; // generates the code for the module (5 digits long int) try { lastCode =((Module) modulesArray.get(modulesArray.size() - 1)).getCode(); } catch(NullPointerException e){ lastCode = "00000"; } // formats the code in a 5 digits long string String newCode = String.format("%1$05d", (Integer.parseInt(lastCode) + 1)); try { module.setCode( newCode ); } catch(InvalidIDException e ){ assert false; //ID generated programmatically, should never be invalid. Execution should not reach this point } modulesArray.add(module); } /** * @inheritDoc */ public String addStaff(String forename, String surname) { Staff s = new StaffClass(forename, surname); try { addStaff(s); }catch (IDAlreadySetException e){ assert false; //Staff object newly created earlier in method, no ID ever set. Execution should not reach this point } return s.getID(); } /** * @inheritDoc */ public void addStaff(Staff staff) throws IDAlreadySetException { if (staff.getID() != null) { throw new IDAlreadySetException("ID is already set"); } String lastID; //generates the id for the staff added (5 digits long hex) try { lastID =((Staff) staffArray.get(staffArray.size() - 1)).getID(); } catch(NullPointerException e){ lastID = "00000"; } //formats the ID to be a 5 digits long hex String newID = String.format("%1$05X", (Integer.parseInt(lastID) + 1)); try { staff.setID( newID ); } catch(InvalidIDException | IDAlreadySetException e ){ assert false; //IDAlreadySetException: new staff object declared, no ID should be set //InvalidIDException: ID generated programmatically, should never be invalid } staffArray.add(staff); } /** * @inheritDoc */ public void discontinue(String moduleCode) throws InvalidIDException, IDNotRecognisedException { Module m = getModule(moduleCode); for (Object c: connectionsArray.contents()){ if (((Connection)c).getModuleID().equals(moduleCode)) { connectionsArray.remove(c); break; } } m.discontinue(); } /** * @inheritDoc */ public void enrol(String studentID, String moduleCode) throws InvalidIDException, IDNotRecognisedException, ModuleAtCapacityException, InsufficientAvailableCreditsException, ModuleDiscontinuedException, ModuleStageTooHighException, EnrollingWouldPreventHonoursException { Module m = getModule(moduleCode); Student s = getStudent(studentID); if (m.isDiscontinued()){ throw new ModuleDiscontinuedException("The module is discontinued"); } if (m.getCapacity() == this.getStudents(moduleCode).length){ //checks if the module is at capacity throw new ModuleAtCapacityException("The module is at capacity"); } if (((m.getCredits() + getCredits(studentID)) > 120)){ // checks if, taking the module, the student would have more than 120 credits throw new InsufficientAvailableCreditsException("The student would have more than 120 credits enrolling in this module"); } if (s.getStage() < m.getStage()){ throw new ModuleStageTooHighException("The module stage is too high for this student"); } // checks if the students is taking more than 30 credits of the previous stage if (s.getStage() > m.getStage()){ int sum = m.getCredits(); for (Module mod : getModules(s.getID())){ if (mod.getStage() < s.getStage()){ sum += mod.getCredits(); } } if (sum > 30){ throw new EnrollingWouldPreventHonoursException("The student already has too many modules of the previous stage"); } } addConnection(moduleCode,studentID); } /** * @inheritDoc */ public void loadAllocationManager(String filename) throws IOException, ClassNotFoundException { FileInputStream fileInput = new FileInputStream( filename ); ObjectInputStream objectInput = new ObjectInputStream( fileInput ); this.studentsArray = (ObjectArrayList) objectInput.readObject(); this.staffArray = (ObjectArrayList) objectInput.readObject(); this.modulesArray = (ObjectArrayList) objectInput.readObject(); this.connectionsArray = (ObjectArrayList) objectInput.readObject(); objectInput.close (); } /** * @inheritDoc */ public int getNumberOfStaff() { return staffArray.size(); } /** * @inheritDoc */ public int getNumberOfStudents() { return studentsArray.size(); } /** * @inheritDoc */ public int getNumberOfModules() { return modulesArray.size(); } /** * Creates a new connection between a module and a student * <p> * @param moduleID Code of the module for the link * @param studentID ID of the student for the link */ private void addConnection(String moduleID, String studentID){ for (Object o: this.connectionsArray.contents()){ if (((Connection)o).getModuleID().equals(moduleID)){ ((Connection)o).addStudentID(studentID); return; } } ObjectArrayList list = new ObjectArrayList(); list.add(studentID); Connection connection = new Connection(moduleID, list); this.connectionsArray.add(connection); } /** * Adds a new connection to the system */ private void addConnection(Connection c){ for (Object o: this.connectionsArray.contents()){ if (((Connection)o).getModuleID().equals(c.getModuleID())){ for (String s: c.getStudentsIDs()){ ((Connection)o).addStudentID(s); } return; } } this.connectionsArray.add(c); } /** * @inheritDoc */ public Staff[] getStaff() { int size = this.staffArray.size(); Staff[] temp = new Staff[size]; Object[] staffList = this.staffArray.contents(); for (int i = 0; i < size; i++) { temp[i] = (Staff)staffList[i]; } return temp; } /** * @inheritDoc */ public Staff[] getStaff(String moduleCode) throws InvalidIDException, IDNotRecognisedException { Module m = getModule(moduleCode); return m.getTeachingStaff(); } /** * @inheritDoc */ public Student[] getStudents() { int size = this.studentsArray.size(); Student[] temp = new Student[size]; Object[] studList = this.studentsArray.contents(); for (int i = 0; i < size; i++) { temp[i] = (Student)studList[i]; } return temp; } /** * @inheritDoc */ public Student[] getStudents(String moduleCode) throws InvalidIDException, IDNotRecognisedException { String[] IDs = new String[0]; // iterates through all the module connections and returns an array of // the codes of all the students taking that module when found for (Object c: (this.connectionsArray.contents())){ if ((((Connection)c).getModuleID()).equals(moduleCode)){ IDs = ((Connection)c).getStudentsIDs(); break; } } Student[] students = new Student[IDs.length]; // given the array of IDs returns an associated array of Student(s) for (int i = 0; i < IDs.length; i++) { students[i] = getStudent(IDs[i]); } return students; } /** * @inheritDoc */ public Module[] getModules() { int size = this.modulesArray.size(); Module[] temp = new Module[size]; Object[] modulesList = this.modulesArray.contents(); for (int i = 0; i < size; i++) { temp[i] = (Module)modulesList[i]; } return temp; } /** * @inheritDoc */ public Module[] getRunningModules() { ObjectArrayList running = new ObjectArrayList(); Module[] allModules = this.getModules(); for (Module m: allModules) { if (!m.isDiscontinued()) running.add(m); } return this.arrayListToArray(running); } /** * @inheritDoc */ public Module[] getAvailableModules() { ObjectArrayList available = new ObjectArrayList(); Module[] runningModules = this.getRunningModules(); for (Module m: runningModules) { try { if (!(m.getCapacity() == this.getStudents(m.getCode()).length)) available.add(m); }catch (IDNotRecognisedException | InvalidIDException e) { assert false; //InvalidIDException: code called from objects in system rather than from user input, codes // should all be of valid format. //IDNotRecognisedException: code called from objects in system, will be recognised. } } return this.arrayListToArray(available); } /** * @inheritDoc */ public Module[] getModules(String studentID) throws InvalidIDException, IDNotRecognisedException { ObjectArrayList modulesList = new ObjectArrayList(); for (Object c: connectionsArray.contents()){ for (String s: ((Connection)c).getStudentsIDs()){ if (s.equals(studentID)){ modulesList.add(getModule(((Connection)c).getModuleID())); break; } } } return arrayListToArray(modulesList); } /** * Small method that returns the number of credits taken by a student. */ private int getCredits(String studentID) throws InvalidIDException, IDNotRecognisedException { int credits = 0; for (Module m: this.getModules(studentID)){ credits += m.getCredits(); } return credits; } /** * @inheritDoc */ public int getNumberOfFullyAllocatedStudents() { Student[] students = this.getStudents(); int count = 0; for (Student s: students) { try { if (getCredits(s.getID()) == 120) count++; } catch (InvalidIDException | IDNotRecognisedException e) { assert false; //InvalidIDException: code called from objects in system rather than from user input, codes // should all be of valid format. //IDNotRecognisedException: code called from objects in system, will be recognised. } } return count; } /** * @inheritDoc */ public int getNumberOfModulesAtCapacity() { Module[] runningModules = this.getRunningModules(); int count = 0; for (Module m: runningModules) { try { if (m.getCapacity() == this.getStudents(m.getCode()).length) count++; } catch (InvalidIDException | IDNotRecognisedException e) { assert false; //InvalidIDException: code called from objects in system rather than from user input, codes // should all be of valid format. //IDNotRecognisedException: code called from objects in system, will be recognised. } } return count; } /** * @inheritDoc */ public Module[] remove(Staff staff) throws InvalidIDException, IDNotRecognisedException, IDNotSetException { ObjectArrayList emptyModules = new ObjectArrayList(); for (Module module : this.getModules()){ try { module.removeStaff(staff); if (module.getTeachingStaff().length == 0) emptyModules.add(module); } catch (StaffNotInvolvedException e){ //expected to fail sometimes } } this.staffArray.remove(staff); return arrayListToArray(emptyModules); } /** * @inheritDoc */ public void remove(Student student) throws InvalidIDException, IDNotRecognisedException, IDNotSetException { //check has ID String ID = student.getID(); if (ID == null) { throw new IDNotSetException("ID of student not set"); } for (Object c : this.connectionsArray.contents()){ ((Connection)c).removeStudentID(student.getID()); } this.studentsArray.remove(student); } /** * @inheritDoc */ public void saveAllocationManager(String filename) throws IOException { FileOutputStream outputFile = new FileOutputStream ( filename ); ObjectOutputStream outputObject = new ObjectOutputStream (outputFile); outputObject.writeObject(this.studentsArray); outputObject.writeObject(this.staffArray); outputObject.writeObject(this.modulesArray); outputObject.writeObject(this.connectionsArray); outputObject.close(); } /** * @inheritDoc */ public boolean unEnrol(String studentID, String moduleCode) throws InvalidIDException, IDNotRecognisedException { for (Object connection : this.connectionsArray.contents()){ if (((Connection) connection).getModuleID().equals(moduleCode)){ for (String student : ((Connection) connection).getStudentsIDs()){ if (student.equals(studentID)){ ((Connection) connection).removeStudentID(studentID); return true; } } } } return false; } /** * Method used to determine whether an element is contained by a Staff[] array * without implementing anything that is not of the java.lang or java.io package. * * @param arr Array of staff members being searched. Will be unsorted. * @param target Element being searched for. * * @return <tt>true</tt> if target is contained within arr */ private boolean contains(Object[] arr, Staff target) { for(Object s: arr){ if(s.equals(target)) { return true; } } return false; } /** * Returns a Module given a module code * @param moduleCode code of the module to be searched */ private Module getModule(String moduleCode) throws InvalidIDException, IDNotRecognisedException { if (moduleCode.length() != 5){ throw new InvalidIDException("The given ID for the module is not valid (5 digit)"); } try { int t = Integer.parseInt(moduleCode, 10); } catch (NumberFormatException e) { throw new InvalidIDException("The given ID for the module is not valid (5 digit)"); } for (Module m: getModules()){ String t = m.getCode(); if (m.getCode().equals(moduleCode)){ return m; } } throw new IDNotRecognisedException("ID not recognised"); } /** * Returns a Student given a student ID * @param studentID ID of the student to be searched */ private Student getStudent(String studentID) throws InvalidIDException, IDNotRecognisedException { if (studentID.length() != 10){ throw new InvalidIDException("The given ID for the student is not valid (10 digit)"); } try { long t = Long.parseLong(studentID, 10); } catch (NumberFormatException e) { throw new InvalidIDException("The given ID for the student is not valid (10 digit)"); } for (Student s: getStudents()){ if (s.getID().equals(studentID)){ return s; } } throw new IDNotRecognisedException("ID not recognised"); } /** * converts an ObjectArrayList filled with Module(s) to * and array of Module(s) */ private Module[] arrayListToArray(ObjectArrayList l){ int size = l.size(); Module[] temp = new Module[size]; Object[] modList = l.contents(); for (int i = 0; i < size; i++) { temp[i] = (Module)modList[i]; } return temp; } } <file_sep>def dot(a, b): mul = [] newlist = [] for i in a: newlist.append([i, b.pop(0)]) print(newlist) for A, B in newlist: mul.append(A * B) return mul l1 = [1, 2, 3, 4, 5] l2 = [3, 4, 5, 6, 7] print(dot(l1, l2)) <file_sep>words = open("lowercasewords.txt", "r") List = words.readlines() for word in List: word = word.strip() if word == word[::-1]: print(word) <file_sep>def dot(a, b): if len(a) != len(b): return "LISTS ARE NOT OF THE SAME LENGHT" S = [] for i in range(len(a)): S.append(a[i] + b[i]) return S a = [1, 2, 3, 4, 5, 12, 128] b = [2, 3, 4, 5, 6, 83, 133] print(dot(a, b)) <file_sep>package university; import java.io.Serializable; /** * Implementation of the {@link Student} interface * * @author 660001833 & 660042108 * @version 1.0 */ public class StudentClass implements Student, Serializable { private byte stage; private final String FORENAME; private final String SURNAME; private String ID = null; /** * Default constructor, generates a Student without a name and a code */ public StudentClass() { this.stage = 0; this.FORENAME = null; this.SURNAME = null; this.ID = null; } /** * Constructor for the {@link StudentClass} class * <p> * @param stage stage of the student, must be between 1 and 4 * @param forename forename of the student * @param surname surname of the student * @param ID ID of the student, must be in a valid format, 10 digits decimal * @throws InvalidIDException thrown if the ID is in the wrong format * @throws InvalidStageException thrown if the stage is not between 1 and 4 */ public StudentClass( byte stage, String forename, String surname, String ID)throws IDAlreadySetException, InvalidIDException, InvalidStageException { setStage(stage); this.FORENAME = forename; this.SURNAME = surname; setID(ID); } /** * Constructor for the {@link StudentClass} class * <p> * @param stage stage of the student, must be between 1 and 4 * @param forename forename of the student * @param surname surname of the student * @throws InvalidStageException thrown if the stage is not between 1 and 4 */ public StudentClass( byte stage, String forename, String surname)throws InvalidStageException { setStage(stage); this.FORENAME = forename; this.SURNAME = surname; this.ID = null; } /** * @inheritDoc */ public String getForename() { return this.FORENAME; } /** * @inheritDoc */ public String getSurname() { return this.SURNAME; } /** * @inheritDoc */ public String getID() { return this.ID; } /** * @inheritDoc */ public byte getStage() { return this.stage; } /** * @inheritDoc */ public void setID(String ID) throws IDAlreadySetException, InvalidIDException { if (this.ID != null) { throw new IDAlreadySetException("This student already has an ID"); } if (ID.length() != 10 || ! this.checkDec(ID)) { throw new InvalidIDException("The given ID is not in the right formal (10 characters decimal)"); } this.ID = ID; } /** * Sets the stage of the student after checking the stage is valid (in range 1-4) * @param stage stage to be set * @throws InvalidStageException thrown if the stage is not valid */ private void setStage(byte stage) throws InvalidStageException { if (stage > 0 && stage < 5) { this.stage = stage; } else { throw new InvalidStageException("Invalid stage"); } } /** * Method used to determine whether inputted string is a legal decimal number * * @param dec string tested if it is legal decimal value when converted from * string * * @return <tt>true</tt> if input is legal decimal value */ private boolean checkDec(String dec) { try { long t = Long.parseLong(dec, 10); return true; } catch (NumberFormatException e) { return false; } } } <file_sep>def diagonal(text, right_to_left=False): """ The function prints a given text diagonally, can write text from right to left or from left to right. Takes as arguments: text = input text right_to_left = a boolean argument defining wether the text should be printed from right to left or not, set False by default The function prints every character of the given text on a different line preceded by a number of spaces equal to the number of character yet to be written Does not work passing a non-string value for the argument "text" """ if right_to_left: i = len(text) - 1 for l in text: print(" " * i + l) i = i - 1 # desceases the number of spaces before the next letter else: i = 0 # starting with 0 spaces before the first letter for l in text: print(" " * i + l) i = i + 1 diagonal("slantwise") print() diagonal("slantwise", right_to_left=True) <file_sep>def print_limerick(L): for i in range(len(L)): for k in range(len(L[i])): print(L[i][k], end=' ') print() def lenghts(L): words = 0 chars = 0 for i in range(len(L)): words += len(L[i]) for k in range(len(L[i])): chars += len(L[i][k]) return words, chars limerick = [ ['There', 'was', 'a', 'young', 'lady', 'named', 'Wright'], ['Whose', 'speed', 'was', 'much', 'faster', 'than', 'light'], ['She', 'left', 'home', 'one', 'day'], ['In', 'a', 'relative', 'way'], ['And', 'returned', 'on', 'the', 'previous', 'night'] ] print_limerick(limerick) print(lenghts(limerick)) <file_sep>sentence = "one fine day in the middle of the night" words = sentence.split(" ") print(words) print(words[5:]) print(words[:4:-1]) print(words[3:6]) print(words[::-1]) print(words[::3]) print(words[2::3]) print(words[-1:0:-3]) <file_sep>from exturtle import * def koch(t, n, L): if n == 0: forward(t, L / 3) else: koch(t, n - 1, L / 3) left(t, 60) koch(t, n - 1, L / 3) right(t, 120) koch(t, n - 1, L / 3) left(t, 60) koch(t, n - 1, L / 3) tur = Turtle() koch(tur, 4, 1000) mainloop() <file_sep>from dictionary import * def wordcount(file): """ It counts all the recurrences of all the words in a file (where there's one word per line) using the dictionary module. file = name of the file <name.txt> to be used """ try: # guardian statement if the file does not exist F = open(file, "r") counter = [] except FileNotFoundError: print(file, "is not a valid file") quit() for line in F: word = line.strip().lower() try: # if it already exists its value is increased by 1 value = get(word, counter) + 1 except KeyError: # otherwise a new entry is made and its value is set to 1 value = 1 insert(word, value, counter) return counter if __name__ == "__main__": words = wordcount("dracula.txt") words = sorted(items(words), key=lambda freq: freq[1], reverse=True) # sorted by recurrences for i in range(10): print(words[i][0], " ", words[i][1]) <file_sep>from math import sqrt def golden(N): ratios = [1] for i in range(1, N): ratios.append(sqrt(1 + ratios[i-1])) return ratios print((1+sqrt(5))/2) print(golden(10)) <file_sep>// MyByteOverflowApp application // Program does not do any Exception handling or type checking on input // Causes overflow in byte when passed integers outside valid range in args[0] // Your name or student number here // The date class MyByteOverflowApp { public static void main(String[] args) { System.out.println( (byte) Integer.parseInt(args[0]) ); } } <file_sep>from sys import argv def histogram(x, percentage, resolution=1): """ The function draws a vertical histogram using the list "x" for the left column and the list "percentage" for heights of each block x = list containing the content of the left column percentage = list with heights of each block resolution = percentage corresponding to each star in the histogram """ resolution = 1 / resolution if len(x) != len(percentage): # guardian statement print("'x' and 'percentage' must have the same length") return None for i in x: percent = int(percentage[i] * resolution) print(i, "*" * percent, " " * 4, round(percentage[i], 3)) def histogram_lenghts(L): """ Given a list of words it returns a list where at a given index is stored the number of words in L that have the same length as the index e.g. if in L there are three words that are four characters long, in the list returned by this function at index 4 we will find the value 3 L = List of words """ H = [] for i in L: i = i.strip() if len(i) > len(H) - 1: # so that the list is always as long as the longest word found H.extend([0] * (len(i) - len(H) + 1)) H[len(i)] += 1 return H def heights_percentage(H): """ Takes in a list of numbers H and returns a list where each element is the percentage of the corresponding element in H with respect to the sum of all values in H H = List of numbers """ P = [] P.extend([0] * (len(H))) # initialize the list for i in range(len(H)): P[i] = H[i] / sum(H) * 100 return P def draw_from_words(L, resolution=1): """ The function prints a histogram of the percentages of times that words of different lengths occur in the given list of words L L = List of words resolution = percentage corresponding to each star in the histogram """ H = histogram_lenghts(L) x = range(len(H)) percent = heights_percentage(H) histogram(x, percent, resolution) return if __name__ == "__main__": file = str(argv[1]) # accepts arguments from command line book = open(file, "r").readlines() draw_from_words(book, 0.25) <file_sep>from Q1 import randomList, depthFirst, breadthFirst, build_sum_tree def searchdemo(n): """ A function designed to test the correct functionality of - build_sum_tree - breadthFirst - depthFirst in question 1. the function generates a tree of length n, the searches such tree for n^2, prints out the item found and the path used to find it in the tree """ L = randomList(n) tree = build_sum_tree(L) print("L = " + str(L)) print("target = " + str(n**2)) print() print("Using DepthFirst:") depth = depthFirst(tree, n**2) print("Value found: " + depth[0]) print("Using the following operations: " + depth[1]) print() print("Using BreadthFirst:") breadth = breadthFirst(tree, n**2) print("Value found: " + breadth[0]) print("Using the following operations: " + breadth[1]) print() print("\n" * 3) if __name__ == "__main__": for n in [3, 5, 7]: # uses searchdemo with n = 3, 5, 7 searchdemo(n) <file_sep>from math import sqrt def check_prime(x, primes): r = int(sqrt(x))+1 for p in primes: if x % p == 0: return False if p > r: break return True def prime_list(x): primes = [2] for i in range(3, x, 2): if check_prime(i, primes): primes.append(i) return primes <file_sep> /** * BasicRectangle class, manages the state of the Rectangle in a basic * fashion. * * @author <NAME> * @version 1.0 */ public class BasicRectangle implements Rectangle { private double height; private double width; /** * Constructor makes a rectangle with sides of unit length */ public BasicRectangle() { this.width = 1.0; this.height = 1.0; } /** * Costructor makes a rectangle with the width and height passed in * as arguments. Negative values are set to zero. * * @param width rectangle width * @param height rectangle height */ public BasicRectangle(double width, double height) { this.setHeight(height); this.setWidth(width); } /** * {@inheritDoc} */ public double getWidth() { return this.width; } /** * {@inheritDoc} */ public double getHeight() { return this.height; } /** * {@inheritDoc} */ public double getArea() { return this.height*this.width; } /** * {@inheritDoc} */ public double getPerimeter(){ return 2*this.height + 2*this.width; } /** * {@inheritDoc} */ public void setHeight(double height){ if (height<0) { this.height = 0; } else { this.height = height; } } /** * {@inheritDoc} */ public void setWidth(double width){ if (width<0) { this.width = 0; } else { this.width = width; } } } <file_sep>i = 1 Sum = 0 while i < 1000: if i % 3 == 0 or i % 5 == 0: Sum += i i += 1 print(Sum) <file_sep>Student no. 660001833 & 660042108. 29/03 -- 10:45 - 14:00 Prepared everything for submission refactored code and improved javadocs 27/03 -- 16:30 - 19:30 Found a problem in our OO design, had to rewrite some methods in UniversityAllocationManager and introduced the new object Connection to solve the issue. 26/03 -- 14:30 - 18:00 Done all documentation Finished test app and tested everything 24/03 -- worked for small time slots throughout the day Intensive work on the test function 13/03 -- 11:30 - 15:00 Improved readability of ModuleClass - finished it Improved readability of StaffClass - finished it Improved readability of StudentClass - finished Continued the work on the test app Continued the work with UniversityAllocationManager, added methods and javadocs, encountered problems with serialising objects, solved in the end - probably finished 08/03 -- 10:30 - 12:30 Minor changes to ModuleClass to fit in UniversityAllocationManager Minor changes to StudentClass to fit in UniversityAllocationManager Started working to a test app Continued the work on UniversityAllocationManager, added methods 06/03 -- 14:30 - 16:30 Minor changes in ModuleClass to fit in UniversityAllocationManager Minor changes to StaffClass to fit in UniversityAllocationManager Continued the work on UniversityAllocationManager, we have done most of the class by now, in particular, added methods and javadocs 03/03 -- 11:00- 12:30 Continued work on the UniversityAllocationManager class, going through the interface and writing concrete methods for all of the abstract ones. Throughout the session we have had issues where by things needed to be cast to some concrete version of itself only to be returned as a abstract version. Issues were arisen when we got to the enrol method and as we do not store the list of modules the student is enrolled in, in the student object, it took a lot of overhead to find all of the modules the student was enrolled in.We may need to change how we are managing the storage of students enrolled to different modules as having the information stored in the mdoules prevents having to search every single student, the situation where one needs to get a list of all students is so far rare. 01/03 -- 10:30 - 1:00, 2:00 - 2:30 Concluded initial work on the Module class and then went about fixing errors that had arrisen within testing of each module that followed. ObjectArrayList is not as simple to use as originally thought and will require a lot of casting to allow for the use of specfically typed output from it. This isn't too large of an issue in retrospect but took a while to solve at the time. Work for the final UnversityManager will begin next session. 27/02 -- 11:30 -- 13:30 We begin by creating the StaffClass, a class that inherited from the Staff interface. Through this all of the predefined methods were implemented. The same was done with the StudentClass and was begun with the Module class.<file_sep>from math import sqrt for a in range(1, 1001): for b in range(1, 1001): c2 = a**2 + b**2 c = sqrt(c2) if c % 1 == 0 and (a + b + c) == 1000: print(a, b, c) print(a * b * c) <file_sep>def sqroot(S, N=6): """ For a given number S it returns its square root using a recursive method after N iterations Takes as arguments: S = given number N = number of iterations """ if S < 0: # guardian statement, checks that given number is positive ret = "Given number is negative" return ret x = S/2 for i in range(N): x = 1/2*(x + S/x) # recursive method return x def print_quality(target, Nmax): """ Prints the accuracy of the function sqroot for each number of iteration less or equal than Nmax by calculating the difference between the given number and the value returned by sqroot(target**2) after N iterations. The bigger the difference, the more inaccurate sqroot Takes as arguments: target = the number used to test the accuracy of sqroot Nmax = the maximum number of iterations to be used for the test """ for i in range(Nmax): approx = sqroot(target**2, i + 1) diff = approx - target print("The given number is", target) print("after", i + 1, "iterations, the approximate value is", approx) print("the difference between this value and the correct one is", diff) print("\n" * 2) print_quality(17, 5) print_quality(200, 10) print_quality(57, 12) <file_sep>from bisect import * def insert(key, value, D, hasher=hash): """ Adds to a dictionary-like list a tuple (hashed key, key, value) if an entry with the same key already exists its value is replaced with the the new one key = key connected to the value value = value corresponding to the key D = list of tuples, non built-in dictionary hasher = function to use to hash the key, built-in hasher by default """ try: pop(key, D, hasher) except KeyError: pass entry = (hasher(key), key, value) insort(D, entry) return None def get(key, D, hasher=hash): """ Returns the value corresponding to a given key key = used to search for the value requested D = dictionary-list used for the search hasher = function to use to hash the key, built-in hasher by default """ try: i = find_index(D, (hasher(key), key, 0)) # finds the index of the first (and only) entry in D with given key return D[i][2] except: raise KeyError def pop(key, D, hasher=hash): """ Removes the entry corresponding to a given key from the dictionary and returns the tuple (key, value) key = key corresponding """ try: index = find_index(D, (hasher(key), key, 0)) popped = D.pop(index) return (popped[1], popped[2]) except: raise KeyError def keys(D): """ Returns a list of all the keys in a given dictionary D D = dictionary-list """ keys = [] for element in D: keys.append(element[1]) return keys def values(D): """ Returns a list of all the values in a given dictionary D D = dictionary-list """ values = [] for element in D: values.append(element[2]) return values def items(D): """ Returns a list of all the tuples (key, value) in a given dictionary D = dictionary-list """ items = [] for element in D: items.append((element[1], element[2])) return items def poorhash(x): """ A worse version of the built-in hash function, it can only return 19 numbers x = value to hash """ return hash(x) % 10 def test_keys(D): """ A function built to test the proper functioning of the "keys" function. It checks the following conditions, if all of them are verified it returns True, otherwise it returns False: - every tuple in the dictionary must return a key (same length) - every key in the dictionary must be in the keys returned by "keys" D = dictionary used for the test """ check = False keys_list = keys(D) if len(keys_list) == len(D): for key in keys_list: check = False for element in D: if key == element[1]: check = True if not check: return False else: return False return True def test_values(D): """ A function built to test the proper functioning of the "values" function. It checks the following conditions, if all of them are verified it returns True, otherwise it returns False: - every tuple in the dictionary must return a value (same length) - every value in the dictionary must be in the values returned by "values" D = dictionary used for the test """ check = False values_list = values(D) if len(values_list) == len(D): for value in values_list: check = False for element in D: if value == element[2]: check = True if not check: return False else: return False return True def test_items(D): """ A function built to test the proper functioning of the "items" function. It checks the following conditions, if all of them are verified it returns True, otherwise it returns False: - every tuple in the dictionary must return a tuple (same length) - every tuple (key, value) in the dictionary must be in the elements returned by "items" D = dictionary used for the test """ check = False items_list = items(D) if len(items_list) == len(D): for key, value in items_list: check = False for element in D: if key == element[1] and value == element[2]: check = True if not check: return False else: return False return True def test_pop(D, hasher=hash): """ A function devised to test the correct functioning of the "pop" function. It tries to pops, key by key, all the elements in a given dictionary, if it encounters a KeyError it returns False, otherwise it returns True D = dictionary used for the test """ Dc = D[:] keys_list = keys(D) try: for key in keys_list: pop(key, Dc, hasher) except KeyError: return False return True def test_get(D, hasher): """ A function devised to test the correct functioning of the "get" function. It tries to get all the values in the dictionary using the function get, if it encounters a KeyError it returns False, otherwise it returns True D = dictionary used for the test """ keys_list = keys(D) try: for key in keys_list: get(key, D, hasher) except KeyError: return False return True def find_index(L, element): index = bisect_left(L, element) in_L = L[index] if index != len(L) and in_L[0] == element[0] and in_L[1] == element[1]: return index raise KeyError <file_sep>def cumulative(numbers): cum = [] sum = 0 for i in range(len(numbers)): sum += numbers[i] cum.append(sum) return cum L = range(20) print(L) print(cumulative(L)) <file_sep> /** * Write a description of interface Lion here. * * @author (your name) * @version (a version number or a date) */ public interface Lion { boolean attackWhenMet(double aggressivity); boolean hasEatenRecently(double daysSinceLastMeal); void hunt(); void eat(); } <file_sep>import string def nopunct(line): for s in string.punctuation: line = line.replace(s, " ") return line def counter(book): f = open(book) D = {} head = 0 for line in f: try: li = line.split() if li[0] == "***": head += 1 except: pass line = nopunct(line) line = line.split() if head == 1: for word in line: if word.strip() in D: D[word] += 1 else: D[word] = 1 return D def printer(D): L = sorted(D, key=D.get, reverse=True) for word in L: print(word, ": ", D[word]) printer(counter("dracula-full.txt")) <file_sep>from exturtle import penup, goto, pendown, begin_fill, end_fill, color, write, speed, hideturtle, Turtle, mainloop from math import cos, sin, sqrt, pi def hexagon(turtle, cx, cy, fill=None, hw=50, text=None): """ Draw a hexagon centred at (cx,cy) with the given size, hw. hw is the half-width, the shortest distance from the centre to a side. The hexagon can be coloured with the given fill colour. The string text is written in the centre of the hexagon. """ radius = hw*2/sqrt(3) penup(turtle) goto(turtle, cx+radius*cos(pi/6), cy+radius*sin(pi/6)) pendown(turtle) if fill is not None: begin_fill(turtle) color(turtle, "black", fill) for n in range(7): x = cx + radius*cos((n+0.5)*2*pi/6) y = cy + radius*sin((n+0.5)*2*pi/6) goto(turtle, x, y) if fill is not None: end_fill(turtle) if text is not None: penup(turtle) goto(turtle, cx, cy) pendown(turtle) write(turtle, text, align='center', font=('Arial', 8, 'bold')) def draw(turtle, N, forbidden, sep=40, c=(0,0)): """Draw a square maze of interlocking hexagons. Arguments: turtle -- the turtle to do the darwing N -- size of the maze forbidden -- if the hexagon with coordinates (i,j) is a key in this dictionary, the hexagon is forbidden and is coloured red. sep -- sets the size and separation of the hexagons; it is the horisontal separation between centres. The hexagons (0, 0) and (N-1, N-1) are coloured grey. """ vsep = sqrt(3)*sep/2 # Vertical distance between centres for i in range(0, N): for j in range(0, N): if i == j and i in (0, N-1): colour = 'gray' elif (i,j) in forbidden: colour = 'red' else: colour = None hexagon(turtle, (i-(j%2)/2)*sep + c[0], j*vsep + c[1], hw=sep/2, fill=colour, text='%d,%d' % (i,j)) if __name__ == '__main__': forbidden = {(0, 1): 1, (1, 2): 1, (3, 3): 1, (4, 1): 1, (4, 4): 1, (2, 1): 1, (1, 5): 1, (): 1, (5, 0): 1, (0, 3): 1, (3, 5): 1, (5, 2): 1, (2, 5): 1, (4, 0): 1} N = 6 bob = Turtle() speed(bob, 10) hideturtle(bob) draw(bob, N, sep=40, forbidden=forbidden) mainloop() <file_sep> /** * Write a description of class Liger here. * * @author (your name) * @version (a version number or a date) */ public class Liger implements Tiger, Lion { private double weight; private double age; private int numberOfStripes; private double hunger; private boolean gender; public Liger(){ this.weight = 50.0; this.age = 3.0; this.numberOfStripes = 42; this.hunger = 0.5; this.gender = true; } public Liger(double weight, double age, int numberOfStripes, double hunger, boolean gender){ this.weight = weight; this.age = age; this.numberOfStripes = numberOfStripes; this.hunger = hunger; this.gender = gender; } public boolean attackWhenMet(double aggressivity){ if (aggressivity * hunger < 50.0){ return false; } else { return true; } } public boolean hasEatenRecently(double daysSinceLastMeal){ this.hunger = daysSinceLastMeal * 2.5; if (daysSinceLastMeal < 3){ return false; }else{ return true; } } public void hunt(){ this.hunger = 0; } public void eat(){ this.hunger = 0; } public int countStripes(){ return this.numberOfStripes; } public boolean isMale(){ return !gender; } } <file_sep>import oracle def highlow(tolerance): """ The function calculates the number generated by the oracle by guessing a value and asking it whether the guess is bigger or smaller than the number and then changing the guess accordingly. The function calculates the value within a given tolerance tolerance = maximum acceptable difference between the number found by the function and the value generated by the oracle The function works as follows: given a range of values (0,100) guesses a number in the middle of the range and asks the oracle wehther that number is bigger than the oracle's number. If it is, the bigger extreme takes the value of the guess, otherwise the lower extreme does. The process is repeated until the number found is within the tolerance """ if tolerance <= 0: # guardian statement print("Tolerance should be bigger than zero") return None guess_range = [0, 100] # initialize the range while (guess_range[1] - guess_range[0]) / 2 > tolerance: guess = guess_range[0] + (guess_range[1] - guess_range[0]) / 2 if Oracle.is_greater(guess): guess_range[0] = guess else: guess_range[1] = guess return guess for i in range(3): # prints 3 different examples of the function at work Oracle = oracle.Oracle() print("case", i + 1, ":") print("The value created by the oracle is", Oracle.reveal()) print("The value found with approximation to 0.001 is", highlow(10**-3)) print("") <file_sep>from random import shuffle from histogram import heights_percentage, histogram def add_to_11(visible): """ It checks if in the given list of numbers "visible" two elements add to 11. It then returns a tuple containing the indexes of the first two elements that add to 11. If it can't find the elements it returns an empty tuple visible = List of numbers """ for card1 in range(len(visible)): for card2 in range(card1, len(visible)): if visible[card1] + visible[card2] == 11: return (card1, card2) return () # if nothing is found def jqk(visible): """ It checks if in the given list of numbers "visible", are present at the same time an 11, a 12 and a 13. It then returns a tuple containing the indexes of the first three elements. If it can't find the elements it returns an empty tuple. visible = List of numbers """ if 11 in visible and 12 in visible and 13 in visible: Jack = visible.index(11) Queen = visible.index(12) King = visible.index(13) return (Jack, Queen, King) return () # if nothing is found def play(deck, verbose=False): """ The function plays a game of "patience" Each turn is done as follows: - if there are two cards whose sum is 11 they are replaced by two new cards from the deck - if a jack, a queen and a king are visible at the same time thay are replaced with new cards - if none of the previous things happen a new card is shown (added to the visible list) The game is over when either there are more than 9 visible card (loss), or when the deck is empty (win). The function returns the number of cards remaining in the deck at the end of the game, if the number is 0 the game was won, otherwise it was lost deck = given deck of cards. cards must be represented as numbers verbose = if True it shows every step of the game, False by default """ deck = deck[:] # copies the original deck to prevent it to be emptied by .pop() shuffle(deck) visible = [] while len(deck) != 0 and len(visible) < 10: if verbose: # prints every step of the game if True print("The visible cards are: ", end="") print(*visible, sep=" ") check_11 = add_to_11(visible) check_jqk = jqk(visible) if len(deck) != 1: # check if there are numbers that sums to 11 or j,q,k. If so they are replaced for position in check_11: visible[position] = deck.pop() else: return 0 if len(deck) > 2: for position in check_jqk: visible[position] = deck.pop() else: return 0 if check_11 == () and check_jqk == (): # if there are no elements that sums to 11 or jqk, it appends a new card visible.append(deck.pop()) return len(deck) def many_plays(N): """ Using the function "play" simulates N games of patience and collects in a list the number of cards remaining at the end of each game (each index contains the number of games ended with "index" number of cards) N = Number of games to simulate """ deck = list(range(1, 14)) * 4 # creates a standard deck of 52 cards remaining = [0] * 52 for plays in range(N): left = play(deck) remaining[left] += 1 return remaining if __name__ == '__main__': List = many_plays(10**4) # The probability of winning a game is around 10.5% x = range(len(List)) list_percentage = heights_percentage(List) histogram(x, list_percentage, 0.1) # The following lines were used to print a won game and a lost game # deck = list(range(1, 14)) * 4 # play(deck, True) # print(play(deck)) <file_sep>def PRNG(j, a=106, c=1283, m=6075): j = (j * a + c) % m return j def check_PRNG(N): checks = [] for i in range(N): checks.append(PRNG(i+1)) if checks[0] == checks[i]: print("FOUND IT") print(checks[0], checks[i]) return None check_PRNG(100000) <file_sep>from random import random from copy import deepcopy grid = [] def create_grid(size): global grid grid = [] for row in range(size): grid.append([]) for col in range(size): grid[row].append(1) return grid def jump_right(grid, row, col, rng): if col < len(grid[row]) - 1: grid[row][col] -= 1 grid[row][col + 1] += 1 else: if rng < 0.3333333: jump_down(grid, row, col, rng) elif rng < 0.6666666: jump_left(grid, row, col, rng) else: jump_up(grid, row, col, rng) return grid def jump_left(grid, row, col, rng): if col != 0: grid[row][col] -= 1 grid[row][col - 1] += 1 else: if rng < 0.3333333: jump_up(grid, row, col, rng) elif rng < 0.6666666: jump_right(grid, row, col, rng) else: jump_down(grid, row, col, rng) return grid def jump_up(grid, row, col, rng): if row != 0: grid[row][col] -= 1 grid[row - 1][col] += 1 else: if rng < 0.3333333: jump_right(grid, row, col, rng) elif rng < 0.6666666: jump_down(grid, row, col, rng) else: jump_left(grid, row, col, rng) return grid def jump_down(grid, row, col, rng): if row < len(grid) - 1: grid[row][col] -= 1 grid[row + 1][col] += 1 else: if rng < 0.3333333: jump_left(grid, row, col, rng) elif rng < 0.6666666: jump_up(grid, row, col, rng) else: jump_right(grid, row, col, rng) return grid def print_grid(grid): for i in range(len(grid)): print(grid[i]) def one_jump(grid): grid2 = deepcopy(grid) for row in range(len(grid2)): for col in range(len(grid2[row])): for flea in range(grid2[row][col]): # print_grid(grid) rng = random() # print() # print("random number: ", rng) # print("position: ", "(", row, ",", col, ")") if rng < 0.25: jump_up(grid, row, col, rng) elif rng < 0.5: jump_right(grid, row, col, rng) elif rng < 0.75: jump_down(grid, row, col, rng) else: jump_left(grid, row, col, rng) # print_grid(grid) return def play(grid, rings): for i in range(rings): one_jump(grid) return grid def statistics(size, games, rings): counter = 0 for game in range(games): grid = create_grid(size) play(grid, rings) for row in range(len(grid)): for col in range(len(grid[row])): if grid[row][col] == 0: counter += 1 return counter / games print(statistics(30, 50, 50)) <file_sep>def histogram(x, percentage, resolution=1): """ x = what is written on the left percentage = height of blocks """ resolution = 1 / resolution for i in x: percent = int(percentage[i] * resolution) print(i, "*" * percent, " " * 4, percent/resolution) def histogram_lenghts(L): H = [] for i in L: i = i.strip() if len(i) > len(H) - 1: H.extend([0] * (len(i) - len(H) + 1)) H[len(i)] += 1 return H def heights_percent(L, H): P = [] P.extend([0] * (len(H))) for i in range(len(H)): P[i] = H[i] / sum(H) * 100 return P def draw(L, resolution=1): H = histogram_lenghts(L) x = range(len(H)) percent = heights_percent(L, H) histogram(x, percent, resolution) return None
759991bf4e7723f480f55c3bc162a9dda655182f
[ "Java", "Python", "Text" ]
89
Python
mtmushu/CS-and-Math---Update
cce03f2fa20572f764a4a14b3b0766d86439e5e1
8ecef2e79f75fb69b047c95d7826deb55bd832b3
refs/heads/master
<file_sep>import tkinter as tk import tkinter.font as tkFont root = tk.Tk() root.title("Calculator") decimal = False memory = 0 def click_number(number): if screen.get() == "ERROR": clear() screen.insert(tk.END, str(number)) def clear(): screen.delete(0, tk.END) def backspace(): current = screen.get() clear() screen.insert(0, current[0:-1]) def decimal_case(): if screen.get() == "ERROR": clear() if "." in screen.get(): clear() screen.insert(0, "ERROR") else: screen.insert(tk.END, ".") def add(): if screen.get() == "": clear() screen.insert(0, "ERROR") else: try: current = int(screen.get()) except: current = float(screen.get()) global memory memory = current global operator operator = "+" clear() def subtraction(): if screen.get() == "": clear() screen.insert(0, "ERROR") else: try: current = int(screen.get()) except: current = float(screen.get()) global memory memory = current global operator operator = "-" clear() def multiplication(): if screen.get() == "": clear() screen.insert(0, "ERROR") else: try: current = int(screen.get()) except: current = float(screen.get()) global memory memory = current global operator operator = "*" clear() def division(): if screen.get() == "": clear() screen.insert(0, "ERROR") else: try: current = int(screen.get()) except: current = float(screen.get()) global memory memory = current global operator operator = "/" clear() def result(): try: current = int(screen.get()) except: current = float(screen.get()) if operator == "+": answer = memory + current if operator == "-": answer = memory - current if operator == "*": answer = memory * current if operator == "/": if current == 0.0: clear() answer = "ERROR" else: answer = memory / current clear() screen.insert(0, str(answer)) # Screen screen = tk.Entry(width=25) screen.grid(row=0, column=0, columnspan=4) # Number buttons button_0 = tk.Button(text="0", padx=20, pady=15, command=lambda: click_number(0)) button_0.grid(row=4, column=1) button_1 = tk.Button(text="1", padx=20, pady=15, command=lambda: click_number(1)) button_1.grid(row=3, column=0) button_2 = tk.Button(text="2", padx=20, pady=15, command=lambda: click_number(2)) button_2.grid(row=3, column=1) button_3 = tk.Button(text="3", padx=20, pady=15, command=lambda: click_number(3)) button_3.grid(row=3, column=2) button_4 = tk.Button(text="4", padx=20, pady=15, command=lambda: click_number(4)) button_4.grid(row=2, column=0) button_5 = tk.Button(text="5", padx=20, pady=15, command=lambda: click_number(5)) button_5.grid(row=2, column=1) button_6 = tk.Button(text="6", padx=20, pady=15, command=lambda: click_number(6)) button_6.grid(row=2, column=2) button_7 = tk.Button(text="7", padx=20, pady=15, command=lambda: click_number(7)) button_7.grid(row=1, column=0) button_8 = tk.Button(text="8", padx=20, pady=15, command=lambda: click_number(8)) button_8.grid(row=1, column=1) button_9 = tk.Button(text="9", padx=20, pady=15, command=lambda: click_number(9)) button_9.grid(row=1, column=2) # Operation buttons button_add = tk.Button(text="+", padx=20, pady=15, command=add) button_add.grid(row=4, column=3) button_subtract = tk.Button(text="-", padx=20, pady=15, command=subtraction) button_subtract.grid(row=3, column=3) button_multiply = tk.Button(text="x", padx=20, pady=15, command=multiplication) button_multiply.grid(row=2, column=3) button_division = tk.Button(text="÷", padx=20, pady=15, command=division) button_division.grid(row=1, column=3) # Other buttons button_equals = tk.Button(text="=", padx=40, pady=15, command=result) button_equals.grid(row=5, column=2, columnspan=2) button_dot = tk.Button(text=".", padx=20, pady=15, command=decimal_case) button_dot.grid(row=4, column=2) button_del = tk.Button(text="<", padx=20, pady=15, command=backspace) button_del.grid(row=5, column=0) button_clear = tk.Button(text="C", padx=20, pady=15, command=clear) button_clear.grid(row=5, column=1) root.mainloop() <file_sep># Simple GUI Calculator Simple Calculator with GUI made with Python. There is nothing special, it is to learn tkinker. ## Operators It includes addition, subtraction, multiplication, and division. Besides the division, if the inputs are integer then the result is also an integer. If at least of of the inputs is a float, then the result is a float. For division the result is always a float. ## Other functions There is backspace and clear. ## Error handling It shows "ERROR" on the screen in case an operator is press before any number to save into the memory. It also diplays ERROR if division by zero is tried. ## TO DO - Remove the interation of the user with the screen - Improve desing
f9277d86fec508de6ad7feaa3126bc11f46107ee
[ "Markdown", "Python" ]
2
Python
gabrielhsc95/simple-gui-calculator
2b3af206f394534a0f4517840258f003e7c9334d
ccd129fa956f51ef549cdd6a6ff80ad1c10ae367
refs/heads/master
<file_sep>var request = require('request'); var async = require('async'); module.export = { getRestaurants: getRestaurants, getRestaurantsByID: getRestaurantsByID }; function getRestaurants (req, res) { request('https://api.usergrid.com/zforeman/sandbox/restaurants', function (err, response, body) { if (err){ res.send(err); } else { res.send(body); } }) } function getRestaurantsByID (req, res){ var restID = req.swagger.params.restID.value; async.parallel([ function(callback) { request('http://api.usergrid.com/zforeman/sandbox/restaurants?ql=restID=' + restID, function (err, response, body) { if (err){ res.send(err); } else { body = JSON.parse(body); body = body.entities[0]; callback(null, body); } }) }, function(callback) { request('http://api.usergrid.com/zforeman/sandbox/reviews?ql=restID=' + restID, function (err, response, body) { if (err){ res.send(err); } else { body = JSON.parse(body); body = body.entities[0]; callback(null, body); } }) } ], function(err, results) { res.send(results); } ); }
369cd74681fbedd2647f63797e06e6dc1794ffc3
[ "JavaScript" ]
1
JavaScript
foremanz/WebAPIHW2
56548fb9c02384f4d14bf1c30ef1e3cf4eca61fe
fbaeacf0acf2599b93dc3fef44c27c8278857978
refs/heads/master
<repo_name>kaalm1/flatiron-bnb-methods-web-060517<file_sep>/app/models/reservation.rb class Reservation < ActiveRecord::Base attr_accessor :delete_file belongs_to :listing belongs_to :guest, :class_name => "User" has_one :review validates :checkin, presence:true validates :checkout, presence:true #validates :checkin, numericality: {less_than: :checkout} #validates :listing_id, uniqueness: {scope: :guest_id} before_validation :start_must_be_before_end_date before_validation :can_not_make_reservation_on_own_listing before_validation :checks_checkin before_validation :checks_checkout def checks_checkin if !checkin.nil? && !checkout.nil? listing.reservations.select do |reservation| if checkin < reservation.checkin || checkin > reservation.checkout false else true end end.empty? end end def checks_checkout if !checkin.nil? && !checkout.nil? listing.reservations.select do |reservation| if checkout < reservation.checkin || checkout > reservation.checkout false else true end end.empty? end end def can_not_make_reservation_on_own_listing guest_id != listing.host.id end def start_must_be_before_end_date if !checkin.nil? && !checkout.nil? checkin < checkout end end def duration self.checkout - self.checkin end def total_price self.listing.price*self.duration end end <file_sep>/app/models/review.rb class Review < ActiveRecord::Base belongs_to :reservation belongs_to :guest, :class_name => "User" validates :rating, presence:true validates :description, presence:true validates :reservation_id, presence:true before_validation :checkout_has_happened def checkout_has_happened if !reservation.nil? Date.today > reservation.checkout end end end <file_sep>/app/models/city.rb class City < ActiveRecord::Base has_many :neighborhoods has_many :listings, :through => :neighborhoods def city_openings(date_beg,date_end) self.listings.select do |listing| listing.reservations.select do |reservation| if reservation.checkin > date_end.to_date || reservation.checkout < date_beg.to_date false else true end end.empty? end end def self.highest_ratio_res_to_listings self.all.max_by do |city| all_listings = city.listings.length all_reservations = city.listings.inject(0) do |sum,listing| sum + listing.reservations.length end all_reservations / all_listings end end def self.most_res self.all.max_by do |city| total = city.listings.inject(0) do |sum,listing| sum + listing.reservations.length end end end end <file_sep>/app/models/listing.rb class Listing < ActiveRecord::Base belongs_to :neighborhood belongs_to :host, :class_name => "User" has_many :reservations has_many :reviews, :through => :reservations has_many :guests, :class_name => "User", :through => :reservations validates :address, presence:true validates :listing_type, presence:true validates :title, presence:true validates :description, presence:true validates :price, presence:true validates :neighborhood_id, presence:true after_create :change_user_host_status after_destroy :change_user_host_status_to_false def change_user_host_status host.host = true host.save end def change_user_host_status_to_false if host.listings.empty? host.host = false host.save end end def average_review_rating 1.0*self.reviews.inject(0) do |sum, review| sum + review.rating end / self.reviews.length end end <file_sep>/app/models/neighborhood.rb class Neighborhood < ActiveRecord::Base belongs_to :city has_many :listings def neighborhood_openings(date_beg,date_end) self.listings.select do |listing| listing.reservations.select do |reservation| if reservation.checkin > date_end.to_date || reservation.checkout < date_beg.to_date false else true end end.empty? end end def self.highest_ratio_res_to_listings self.all.max_by do |neighborhood| all_listings = neighborhood.listings.length all_reservations = neighborhood.listings.inject(0) do |sum,listing| sum + listing.reservations.length end if all_listings != 0 all_reservations / all_listings else 0 end end end def self.most_res self.all.max_by do |neighborhood| neighborhood.listings.inject(0) do |sum,listing| sum + listing.reservations.length end end end end <file_sep>/app/models/user.rb class User < ActiveRecord::Base has_many :listings, :foreign_key => 'host_id' has_many :reservations, :through => :listings has_many :trips, :foreign_key => 'guest_id', :class_name => "Reservation" has_many :reviews, :foreign_key => 'guest_id' def guests reservations.map do |reservation| reservation.guest end.uniq end def hosts reviews.map do |review| review.reservation.listing.host end.uniq end def host_reviews guests.map do |guest| guest.reviews end.flatten end # def guests # User.all.select do |user| # !user.host # end # end # # def hosts # User.all.select do |user| # user.host # end # end # # def host_reviews # binding.pry # self.guests.select do |guest| # guest.reviews # end # end end
3ea4a3f38369d2d29cde65d46c5fdb62aee86b23
[ "Ruby" ]
6
Ruby
kaalm1/flatiron-bnb-methods-web-060517
253064e39e305204fd189fc8177cce5a2223eae0
954af32bc945f9f3e3984bc7130883a2b13cc4e9
refs/heads/main
<file_sep>version: '3' services: rabbitmq: image: rabbitmq:3-management environment: RABBITMQ_DEFAULT_USER: rabbitmq RABBITMQ_DEFAULT_PASS: <PASSWORD> RABBITMQ_DEFAULT_VHOST: rabbitmq-study ports: - "5672:5672" - "15672:15672" # network_mode: host <file_sep>package com.s2u2m.study.mq.rabbitmq.basic; import com.rabbitmq.client.ConnectionFactory; public class RabbitMqConfig { public static final String HOST = "localhost"; public static final String USERNAME = "rabbitmq"; public static final String PASSWORD = "<PASSWORD>"; public static final String VHOST = "rabbitmq-study"; public static final String BASIC_DEMO_EX = "basic-ex"; public static final String BASIC_DEMO_AE = "basic-alternate-exchange"; public static final String BASIC_DEMO_QUEUE = "basic-queue"; public static final String BASIC_DEMO_QUEUE_2 = "basic-queue-2"; public static ConnectionFactory connectionFactory() { ConnectionFactory factory = new ConnectionFactory(); factory.setHost(RabbitMqConfig.HOST); factory.setUsername(RabbitMqConfig.USERNAME); factory.setPassword(<PASSWORD>); factory.setVirtualHost(RabbitMqConfig.VHOST); return factory; } } <file_sep>package com.s2u2m.study.mq.rabbitmq.practice; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeoutException; import com.rabbitmq.client.BuiltinExchangeType; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; public class BrokerConfigDemo { public void init() throws IOException, TimeoutException { var factory = RabbitMQConfig.connectionFactory(); try (Connection connection = factory.newConnection(); Channel channel = connection.createChannel()) { // AE声明 channel.exchangeDeclare(RabbitMQConfig.AE, BuiltinExchangeType.FANOUT, false, false, true, null); channel.queueDeclare(RabbitMQConfig.AE_QUEUE, true, false, false, null); channel.queueBind(RabbitMQConfig.AE_QUEUE, RabbitMQConfig.AE, ""); // Exchange和Queue声明 Map<String, Object> args = new HashMap<>(); args.put("alternate-exchange", RabbitMQConfig.AE); channel.exchangeDeclare(RabbitMQConfig.EX, BuiltinExchangeType.DIRECT, true, false, false, args); channel.queueDeclare(RabbitMQConfig.EX_QUEUE, true, false, false, null); channel.queueBind(RabbitMQConfig.EX_QUEUE, RabbitMQConfig.EX, RabbitMQConfig.EX_QUEUE_ROUTE_KEY); } } public static void main(String[] args) throws IOException, TimeoutException { new BrokerConfigDemo().init(); } }
15723262dd5ac594fc61978f5cd4c5796d92b678
[ "Java", "YAML" ]
3
YAML
xiayy860612/study
ffa31054219d1c807ce461f6c5e871fdd39446e1
2869a91b217a74a7c5436144c2d8e38cb9498e55
refs/heads/master
<file_sep>require_relative('../models/movie') require_relative('../models/star') require_relative('../models/casting') require( 'pry-byebug' ) require( 'pry-byebug' ) Casting.delete_all() Movie.delete_all() Star.delete_all() actor1 = Star.new('first_name' => 'Bobby', 'last_name' => 'Cannavale' ) actor2 = Star.new('first_name' => 'Ms', 'last_name' => 'Divine' ) actor3 = Star.new('first_name' => '<NAME>', 'last_name' => '<NAME>') actor1.save actor2.save actor3.save movie1 = Movie.new('title' => 'Laurence of Arabia of Australia: Port of Call New Orleans', 'genre' => 'a good bit of fun', 'budget' => '4') movie2 = Movie.new('title' => 'Spiders, Lice, Children of the Corn: The Revenge of Ned', 'genre' => 'children', 'budget' => '6') movie3 = Movie.new('title' => '<NAME>', 'genre' => 'coming of age', 'budget' => '2') movie1.save movie2.save movie3.save casting1 = Casting.new('fee' => '3', 'movie_id' => movie1.id, 'star_id' => actor3.id) casting2 = Casting.new('fee' => '1', 'movie_id' => movie1.id, 'star_id' => actor1.id) casting3 = Casting.new('fee' => '4', 'movie_id' => movie2.id, 'star_id' => actor2.id) casting4 = Casting.new('fee' => '3', 'movie_id' => movie2.id, 'star_id' => actor1.id) casting5 = Casting.new('fee' => '2', 'movie_id' => movie2.id, 'star_id' => actor3.id) casting6 = Casting.new('fee' => '1', 'movie_id' => movie3.id, 'star_id' => actor2.id) casting1.save casting2.save casting3.save casting4.save casting5.save casting6.save binding.pry nil <file_sep>require_relative('../db/sql_runner') require_relative('star') class Movie attr_accessor :title, :genre, :id, :budget def initialize(options) @title = options['title'] @genre = options['genre'] @id = options['id'].to_i if options['id'] @budget = options['budget'] end def save() sql = "INSERT INTO movies ( title, genre, budget ) VALUES ( $1, $2, $3 ) RETURNING id" values = [@title, @genre, @budget] @id = SqlRunner.run( sql, values )[0]["id"].to_i() end def self.all() sql = "SELECT * FROM movies" values = [] movies = SqlRunner.run(sql, values) result = movies.map { |movie| Movie.new( movie) } return result end def self.delete_all() sql = "DELETE FROM movies" values = [] SqlRunner.run(sql, values) end def stars sql = "SELECT stars.* FROM stars INNER JOIN castings ON stars.id = castings.star_id WHERE castings.movie_id = $1" values = [@id] star_hashes = SqlRunner.run(sql, values) return star_hashes.map {|star| Star.new(star)} end def budget sql = "SELECT castings.* FROM castings INNER JOIN movies ON movies.id = castings.movie_id WHERE castings.movie_id = $1" values = [@id] fees_hash = SqlRunner.run(sql, values) return fees_hash.map {|fee| Casting.new(fee)} end end
5608086633c45686cdad79201dbc3971c45b5eea
[ "Ruby" ]
2
Ruby
laceywalker/week_03_imdb_lab
834fa5131cf4a47bf55251ae3974866508778725
460ca93471c143960738a770eb62200440e6f963
refs/heads/main
<file_sep>import os, time, sys import configparser import psycopg2 import logging logging.basicConfig(level=logging.DEBUG, filename='logging.log', datefmt='%Y/%m/%d %H:%M:%S', format='%(asctime)s - %(levelname)s - %(message)s') logger = logging.getLogger(__name__) if len(sys.argv) < 2 or len(sys.argv) > 4: logger.error("没有输入参数") print("请输入参数") exit(0) elif len(sys.argv) > 3: logger.error("参数输入错误") print("参数个数错误") exit(0) else: sqlName = sys.argv[1] sqlCommand = sys.argv[2] def replace_data(sqlName): with open("{}.sql".format(sqlName), "rt") as file: x = file.read() with open("{}.sql".format(sqlName), "wt") as file: x = x.replace("hlink-saas-manage", sqlName) file.write(x) def run_bash(cmd): with open("run1.sh", "w")as f: f.write(cmd) os.system("bash run1.sh >/dev/null 2>&1") run_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) if "-q -W -f" in cmd: logger.info("数据库写入成功") print(run_time, "数据库写入成功") if "-n" in cmd: logger.info("数据库备份成功") print(run_time, "数据库备份成功") if "SELECT" in cmd: logger.info("数据库队列刷新成功") print(run_time, "数据库队列刷新成功") def tables_list(database, user, password, host, port): try: conn = psycopg2.connect(database=database, user=user, password=<PASSWORD>, host=host, port=port) except: print("连接失败,请检查配置文件") exit(1) cur = conn.cursor() # 执行查询命令 cur.execute("select * from pg_tables") # print("正确链接数据库") rows = cur.fetchall() tablesList = [] for i in rows: if i[0] not in tablesList: tablesList.append(i[0]) return tablesList def insert_sql(database, user, password, host, port): sqlStatement = """INSERT INTO {}.user ( account_id, name, active_flag, delete_flag, is_tenant_admin, update_by, update_time, create_by, create_time) VALUES ({}, 'admin', 1, 0, 1, 1, 1, 1, 1);""".format(sqlName, sqlCommand) try: conn = psycopg2.connect(database=database, user=user, password=<PASSWORD>, host=host, port=port) cur = conn.cursor() # 执行查询命令 cur.execute(sqlStatement) conn.commit() conn.close() logger.info("") except Exception as e: print("连接失败 {}".format(e)) def main(database, user, password, host, port, schema): if sys.argv[1] in tables_list(database, user, password, host, port): logger.critical("数据中的{}表已存在".format(sys.argv[1])) print("{}已经存在,请检查后运行".format(sys.argv[1])) exit(1) # database,user,password,host,port分别对应要连接的PostgreSQL数据库的数据库名、数据库用户名、用户密码、主机、端口信息,请根据具体情况自行修改 copyOutCmd = """#!/bin/bash expect <(cat <<'END' set password "{}" spawn pg_dump -h {} -p {} -U {} -W -d {} -n {} -f {}.sql expect "Password:" send "$password\r" interact END )""".format(password, host, port, user, database, schema, sqlName) copyInCmd = """#!/bin/bash expect <(cat <<'END' set password "{}" spawn psql -h {} -p {} -U {} -d {} -q -W -f {}.sql expect "Password:" send "$password\r" interact END)""".format(password, host, port, user, database, sqlName) refreshseqCmd = """#!/bin/bash expect <(cat <<'END' set password "{}" spawn psql -h {} -p {} -U {} -d {} -q -W -c "SELECT \"public\".\"set_sequence\"({})" expect "Password:" send "$password\r" interact END )""".format(password, host, port, user, database, sqlName) try: start_time = time.time() run_bash(copyOutCmd) replace_data(sqlName) run_bash(copyInCmd) run_bash(refreshseqCmd) os.system("rm run1.sh {}.sql".format(sqlName)) insert_sql(database, user, passwd, host, port) logger.info("{}插入数据库完成".format(sqlCommand)) print("共计用时{:.2f}秒".format(time.time() - start_time)) except PermissionError: logger.warning("没有在root用户下运行") print("请在root用户下运行") if __name__ == '__main__': config = configparser.ConfigParser() config.read("/app/createSql/config.ini") host = config['postgresql']['host'] user = config['postgresql']['user'] passwd = config['postgresql']['password'] db = config['postgresql']['database'] schema = config['postgresql']['schema'] port = config['postgresql']['port'] main(db, user, passwd, host, port, schema) <file_sep>使用方法: 1. 运行run.sh 安装依赖文件 2. 在config.ini配置文件中设置相关参数 3. 在/app/createSql目录下运行 例: python3 /app/createSql/main.py 新数据库名称 插入数据库的内容 4. 运行日志输出到logging.log文件中 <file_sep>[postgresql] host = 192.168.0.8 port = 5432 database = hlink-saas-manage user = saas password = <PASSWORD> schema = hlink-saas-manage <file_sep># 安装 expect apt install expect # 安装最高版本的postgresql sudo sh -c 'echo "deb http://apt.postgresql.org/pub/repos/apt $(lsb_release -cs)-pgdg main" > /etc/apt/sources.list.d/pgdg.list' wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add - sudo apt-get update sudo apt-get install postgresql # 升级pip3 pip3 install --upgrade setuptools -i https://pypi.douban.com/simple pip3 install --upgrade pip -i https://pypi.douban.com/simple # 安装psycopg2依赖包 pip3 install psycopg2==2.7.3.2 -i https://pypi.douban.com/simple
505e392a8730b9711e838171b918eda729881177
[ "Shell", "Python", "Text", "INI" ]
4
Python
qwhsdwd/AutomationPostgresql
4dda8e0a4d01a30e039cd4d414220048e9159771
039989c251a96a92572d4853d2419fde9a0c78dc
refs/heads/master
<repo_name>slavril/VodiLanguageTools<file_sep>/src/readXLC/sAdvanceHelper.java package readXLC; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Iterator; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class sAdvanceHelper { private static XSSFWorkbook wb; // new reader public static ArrayList<String> readPlainFile(String filePath, boolean log) throws IOException { if (log) { System.out.println(filePath); } Path path = Paths.get(filePath); ArrayList<String> lines = new ArrayList<String>(); lines.addAll(Files.readAllLines(path, StandardCharsets.UTF_8)); for (String string : lines) { if (log) { System.out.println(string); } } return lines; } // new writer public static void writePlainFile(String filePath, ArrayList<String> contents, boolean log) throws IOException { Path path = Paths.get(filePath); if (log) { for (String string : contents) { System.out.println(string); } } Files.write(path, contents, StandardCharsets.UTF_8); } // new XLS reader public static ArrayList<ArrayList<String>> readXLSFile(String file) throws IOException { InputStream ExcelFileToRead = new FileInputStream(file); wb = new XSSFWorkbook(ExcelFileToRead); XSSFSheet sheet = wb.getSheetAt(0); XSSFRow row; XSSFCell cell; Iterator<?> rows = sheet.rowIterator(); ArrayList <ArrayList<String>> values = new ArrayList<ArrayList<String>>(); while (rows.hasNext()) { row = (XSSFRow) rows.next(); Iterator<?> cells = row.cellIterator(); Integer rowIndex = row.getRowNum(); while (cells.hasNext()) { cell=(XSSFCell) cells.next(); Integer columnIndex = cell.getColumnIndex(); String cellString = "empty value"; if (cell.getCellType() == XSSFCell.CELL_TYPE_STRING) { if (cell.getStringCellValue().length() > 0) { cellString = cell.getStringCellValue(); } } if (rowIndex == 0) { // first, create list ArrayList <String> listValues = new ArrayList<String>(); listValues.add(cellString); values.add(listValues); } else { ArrayList <String> listValues = values.get(columnIndex); listValues.add(cellString); } } } return values; } } <file_sep>/src/readXLC/main.java package readXLC; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; public class main { static String pathString; public static void createUI() { JFrame frame = new JFrame("Vodi Language Tool 1.13"); final JLabel label = new JLabel("Status: no file choosen"); //frame.getContentPane().add(label); JButton button = new JButton("Select Folder"); JButton processButton = new JButton("RUN"); //button.setBounds(0, 0, 100, 40); JPanel panel = new JPanel(); panel.setBounds(0, 0, 120, 200); panel.add(label); panel.add(button); panel.add(processButton); frame.getContentPane().add(panel); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); //frame.setSize(320, 160); frame.setLocationRelativeTo(null); frame.setVisible(true); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { JFileChooser fc = new JFileChooser("D:\\LANGUAGE"); fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); int returnVal = fc.showDialog(null, "Open"); if (returnVal == JFileChooser.APPROVE_OPTION) { label.setText(fc.getSelectedFile().getAbsolutePath()); pathString = fc.getSelectedFile().getAbsolutePath(); } else { label.setText(fc.getSelectedFile().getAbsolutePath()); pathString = fc.getSelectedFile().getAbsolutePath(); } } }); processButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { label.setText("Running.."); try { sVodiHelper vodiExtend = new sVodiHelper(pathString+"\\"); vodiExtend.process(); label.setText("Done"); } catch (IOException e) { e.printStackTrace(); label.setText("Error"); } } }); } public static void main(String[] args) throws IOException { //createUI(); sVodiHelper.printKey("D:\\LANGUAGE\\2.2\\text.txt"); } }
4237a4d70bb1d809ef363de843649489776ab39d
[ "Java" ]
2
Java
slavril/VodiLanguageTools
c38495be60f9c00e24329d3d3aa06a2293d58039
45d5b8582eb7bcfb7be2c602a9dd269cc1e17487
refs/heads/main
<file_sep>canvas = document.getElementById("myCanvas"); ctx = canvas.getContext("2d"); background_image = "racing.gif"; car1_image = "car1.png"; car1_width = 120; car1_height = 70; car1_x = 10; car1_y = 10; car2_image = "car2.png"; car2_width = 120; car2_height = 70; car2_x = 10; car2_y = 100; function add(){ bg_img = new Image(); bg_img.onload = uploadBackground; bg_img.src = background_image; car1_img = new Image(); car1_img.onload = uploadCar1; car1_img.src = car1_image; car2_img = new Image(); car2_img.onload = uploadCar2; car2_img.src = car2_image; } function uploadBackground(){ ctx.drawImage(bg_img,0,0,canvas.width,canvas.height); } function uploadCar1(){ ctx.drawImage(car1_img,car1_x,car1_y,car1_width,car1_height); } function uploadCar2(){ ctx.drawImage(car2_img,car2_x,car2_y,car2_width,car2_height); } window.addEventListener("keydown",my_keydown); function my_keydown(e){ keyPressed = e.keyCode; console.log(keyPressed); if(keyPressed == "38"){ console.log("up arrow key"); up1(); } if(keyPressed == "40"){ console.log("down arrow key"); down1(); } if(keyPressed == "37"){ console.log("left arrow key"); left1(); } if(keyPressed == "39"){ console.log("right arrow key"); right1(); } if(keyPressed == "87"){ console.log("up key W"); up2(); } if(keyPressed == "83"){ console.log("down key S"); down2(); } if(keyPressed == "65"){ console.log("left key A"); left2(); } if(keyPressed == "68"){ console.log("right key D"); right2(); } } function up1(){ if(car1_y > 0){ car1_y = car1_y - 10; console.log("when up arrow is pressed for car 1, x = "+car1_x+"| y = "+car1_y); uploadBackground(); uploadCar1(); uploadCar2(); } } function down1(){ if(car1_y < 500){ car1_y = car1_y + 10; console.log("when down arrow is pressed for car 1, x = "+car1_x+"| y = "+car1_y); uploadBackground(); uploadCar1(); uploadCar2(); } } function left1(){ if(car1_x > 0){ car1_x = car1_x - 10; console.log("when left arrow is pressed for car 1, x = "+car1_x+"| y = "+car1_y); uploadBackground(); uploadCar1(); uploadCar2(); } } function right1(){ if(car1_x < 680){ car1_x = car1_x + 10; console.log("when right arrow is pressed for car 1, x = "+car1_x+"| y = "+car1_y); uploadBackground(); uploadCar1(); uploadCar2(); } } function up2(){ if(car2_y > 0){ car2_y = car2_y - 10; console.log("when W is pressed for car 2, x = "+car2_x+"| y = "+car2_y); uploadBackground(); uploadCar1(); uploadCar2(); } } function down2(){ if(car2_y < 500){ car2_y = car2_y + 10; console.log("when S is pressed for car 2, x = "+car2_x+"| y = "+car2_y); uploadBackground(); uploadCar1(); uploadCar2(); } } function left2(){ if(car2_x > 0){ car2_x = car2_x - 10; console.log("when A is pressed for car 2, x = "+car2_x+"| y = "+car2_y); uploadBackground(); uploadCar1(); uploadCar2(); } } function right2(){ if(car2_x < 680){ car2_x = car2_x + 10; console.log("when D is pressed for car 2, x = "+car2_x+"| y = "+car2_y); uploadBackground(); uploadCar1(); uploadCar2(); } }
cc4e535dba0891dbfaf55f6ce975d5177c23bf0c
[ "JavaScript" ]
1
JavaScript
manan-liao/Project-84-85
9c1f133c5df35fda87fffbec71330881d4e04680
7e54963c0607701438219bd9475c4e6ff4cdecaa
refs/heads/master
<file_sep>####################################################### ####################DATA IMPORT######################## ####################################################### BMIFemale = read.table("BMIFemale.csv", header = TRUE, sep = ";", dec = ",") BMIMale = read.table("BMIMale.csv", header = TRUE, sep = ";", dec = ",") ####################################################### ######################PART 1########################### ####################################################### BMIFAYears = BMIFemale[BMIFemale$Continent == 2, c("X1980","X2008")] #Mean of raw data Mean1980 = mean(BMIFAYears$X1980) Mean2008 = mean(BMIFAYears$X2008) #Standard deviation of raw data SD1980 = sd(BMIFAYears$X1980) SD2008 = sd(BMIFAYears$X2008) Mean1980 Mean2008 SD1980 SD2008 #Histogram of raw data hist(BMIFAYears$X1980) hist(BMIFAYears$X2008) #Boxplot of raw data Boxplot(BMIFAYears$X1980) Boxplot(BMIFAYears$X2008) #Normality test of raw data shapiro.test(BMIFAYears$X1980) shapiro.test(BMIFAYears$X2008) #Graphical Normality test of raw data qqnorm(BMIFAYears$X1980, main="Normalitytest America, 1980") qqline(BMIFAYears$X1980) qqnorm(BMIFAYears$X2008, main="Normalitytest America, 2008") qqline(BMIFAYears$X2008) #T-Test of the data t.test(BMIFAYears$X1980, BMIFAYears$X2008, paired = FALSE) t.test(BMIFAYears$X1980, BMIFAYears$X2008, alternative="less", paired = FALSE) t.test(BMIFAYears$X1980, BMIFAYears$X2008, alternative="greater", paired = FALSE) ####################################################### ######################PART 2########################### ####################################################### #Data Albania BMIFAlbania = BMIFemale[BMIFemale$Country == "Albania",] BMIMAlbania = BMIMale[BMIMale$Country == "Albania",] BMIFAlbaniaYears = BMIFAlbania[-c(1, 2)] BMIMAlbaniaYears = BMIMAlbania[-c(1, 2)] #Transposed Data BMIFAYT <- t(BMIFAlbaniaYears) BMIMAYT <- t(BMIMAlbaniaYears) #NormalityTests Albania shapiro.test(BMIFAYT) shapiro.test(BMIMAYT) #Graphical NormalityTest Albania qqnorm(BMIFAYT, main="Normalitytest Albania, Females") qqline(BMIFAYT) qqnorm(BMIMAYT, main="Normalitytest Albania, Males") qqline(BMIMAYT) #PropTest counterF = 0 for(i in 1:length(BMIFAYT)) { if(BMIFAYT[i] > 25.3) { counterF = counterF + 1 } } counterM = 0 for(i in 1:length(BMIMAYT)) { if(BMIMAYT[i] > 25.3) { counterM = counterM + 1 } } prop.test(c(counterF, counterM), c(length(BMIFAYT), length(BMIMAYT)), correct = FALSE) prop.test(c(counterF, counterM), c(length(BMIFAYT), length(BMIMAYT)), alternative = "less", correct = FALSE)<file_sep># SEDA Project Statistiek en Data Analyse 2015-2016 KUL Project Repository for Statistics and Data Analysis during the 2nd phase of the Bachelors in Informatics at KU Leuven Authors: <NAME>, <NAME>
7eac3d1394982b582b81902d2a4a9698600fda93
[ "Markdown", "R" ]
2
R
jonahbellemans/SEDA
c796ae5527dcd5862455d3f312b3fd799260031b
4db38a563443cfb83697e1197a8213c7e833d1d6
refs/heads/master
<file_sep># import some common libraries import numpy as np import cv2 import os import argparse parser = argparse.ArgumentParser() parser.add_argument('--dataroot', help='foo help', required=True) parser.add_argument('--name', help='foo help', required=True) args = parser.parse_args() root_name = args.dataroot name = args.name # make folder if not os.path.exists(os.path.join('segment_data', root_name)): os.makedirs(os.path.join('segment_data', root_name)) for filename in os.listdir(root_name): if '_fake' in filename: print(filename) first, second = os.path.splitext(filename) im = cv2.imread(os.path.join(root_name, filename)) im = cv2.resize(im, dsize=(349, 640)) filename.replace("_fake", "") im_point = np.zeros((640, 349, 4), np.uint8) first, _ = os.path.splitext(filename) w, h = np.loadtxt(os.path.join('coordinate', name, "size_" + first + ".txt")) coor_point = np.loadtxt(os.path.join('coordinate', name, "coor_" + first + ".txt")) # print(im.shape[0]) b_channel, g_channel, r_channel = cv2.split(im) alpha_channel = np.ones(b_channel.shape, dtype=b_channel.dtype) * 255 # creating a dummy alpha channel image im_point = cv2.merge((b_channel, g_channel, r_channel, alpha_channel)) for i in range(640): for j in range(349): if coor_point[i][j] == 1: im_point[i][j] = im_point[i][j] else: im_point[i][j] = [0, 0, 0, 1] # cv2.imshow("", im_point) # cv2.waitKey(0) # to PNG img_BGRA = cv2.resize(im_point, dsize=(int(w), int(h))) cv2.imwrite(os.path.join('segment_data', root_name, 'seg_' + filename), img_BGRA) <file_sep># You may need to restart your runtime prior to this, to let your installation take effect # Some basic setup: # Setup detectron2 logger import detectron2 from detectron2.utils.logger import setup_logger setup_logger() # import some common libraries import numpy as np import cv2 import torch # import some common detectron2 utilities from detectron2 import model_zoo from detectron2.engine import DefaultPredictor from detectron2.config import get_cfg from detectron2.utils.visualizer import Visualizer, ColorMode from detectron2.data import MetadataCatalog coco_metadata = MetadataCatalog.get("coco_2017_val") # import PointRend project import sys; sys.path.insert(1, "projects/PointRend") import point_rend import os import argparse parser = argparse.ArgumentParser() parser.add_argument('--dataroot', help='foo help', required=True) args = parser.parse_args() root_name = args.dataroot # dataroot = os.p cfg = get_cfg() cfg.merge_from_file(model_zoo.get_config_file("COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml")) cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.5 # set threshold for this model cfg.MODEL.WEIGHTS = model_zoo.get_checkpoint_url("COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml") mask_rcnn_predictor = DefaultPredictor(cfg) cfg = get_cfg() # Add PointRend-specific config point_rend.add_pointrend_config(cfg) # Load a config from file cfg.merge_from_file("projects/PointRend/configs/InstanceSegmentation/pointrend_rcnn_R_50_FPN_3x_coco.yaml") cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.5 # set threshold for this model # Use a model from PointRend model zoo: https://github.com/facebookresearch/detectron2/tree/master/projects/PointRend#pretrained-models cfg.MODEL.WEIGHTS = "detectron2://PointRend/InstanceSegmentation/pointrend_rcnn_R_50_FPN_3x_coco/164955410/model_final_3c3198.pkl" predictor = DefaultPredictor(cfg) # make folder if not os.path.exists(os.path.join('coordinate', root_name)): os.makedirs(os.path.join('coordinate', root_name)) for filename in os.listdir(root_name): print(filename) im = cv2.imread(os.path.join(root_name, filename)) # cv2.imshow("",im) # cv2.waitKey(0) w = im.shape[1] h = im.shape[0] im = cv2.resize(im, dsize=(349, 640)) # print(w,h) mask_rcnn_outputs = mask_rcnn_predictor(im) outputs = predictor(im) # print(outputs) # Show and compare two predictions: v = Visualizer(im[:, :, ::-1], coco_metadata, scale=1.2, instance_mode=ColorMode.IMAGE_BW) mask_rcnn_result = v.draw_instance_predictions(mask_rcnn_outputs["instances"].to("cpu")).get_image() # cv2.imshow(mask_rcnn_result) v = Visualizer(im[:, :, ::-1], coco_metadata, scale=1.2, instance_mode=ColorMode.IMAGE_BW) point_rend_result = v.draw_instance_predictions(outputs["instances"].to("cpu")).get_image() # cv2.imshow("", np.concatenate((point_rend_result, mask_rcnn_result), axis=0)[:, :, ::-1]) # cv2.waitKey(0) true_coor = [[True for col in range(w)] for row in range(h)] # pointrend coordinates if (len(outputs["instances"]) != 0): for i in range(len(outputs["instances"])): if outputs["instances"].pred_classes[i] == 17 or outputs["instances"].pred_classes[i] == 16: coor_point = outputs["instances"].pred_masks[0].cpu().detach().numpy() name, _ = os.path.splitext(filename) # print(coor_point[0]) np.savetxt(os.path.join('coordinate', root_name, "coor_" + name + ".txt"), coor_point) np.savetxt(os.path.join('coordinate', root_name, "size_" + name + ".txt"), [w, h]) else: np.savetxt(os.path.join('coordinate', root_name, "coor_" + name + ".txt"), true_coor) np.savetxt(os.path.join('coordinate', root_name, "size_" + name + ".txt"), [w, h]) else: np.savetxt(os.path.join('coordinate', root_name, "coor_" + name + ".txt"), true_coor) np.savetxt(os.path.join('coordinate', root_name, "size_" + name + ".txt"), [w, h]) # torch.save(coor_point, 'file.pt') <file_sep># Graduation_Work ## Project Title > Dog + Emoji = **Dogji** ## Project Description > It is a project that emotionalizes actual puppy pictures.<br> > 실제 강아지 사진을 이모티콘화 해서 보여주는 프로젝트입니다. ## Collaborators | ID | Name | Email | | ---------- | :------------------- | :------------------------- | | 201736055 | Han-Jian(한지안) | <EMAIL> | | 201835415 | Kim-Doyeon(김도연) | <EMAIL> | | 201835538 | Choi-Jiwon(최지원) | <EMAIL> | ## Experimental Environment & API > Intel i7-5960X CPU, Nvidia GTX 1080 GPU <br> epoch: 400 <br> > Python Version: 3.7.3 > > Real dog images with unpair data: 684 data <br> > Watercolor puppy illustration image: 419 data > > Sources <br> > --- > https://pixabay.com/illustrations/ <br> > MIRFLICKR Download <br> > Etc </br> > > How To Install Experimental Environment <br> > --- > Refer to the files in the [Installation Environment](https://github.com/hjw705/GraduationWork/tree/master/Installation%20Environment) folder for execution preferences, code execution instructions, and dataset information. <br> > You can find train dataset in the [Datasets](https://github.com/hjw705/GraduationWork/tree/master/Datasets) folder. > ## Our Paper >"CycleGAN 과 Mask R-CNN 을 활용한 수채화 스타일 이모티콘 생성" -> You can see on [Our Paper](https://github.com/hjw705/GraduationWork/tree/master/Our%20Paper) folder. <br> > 제 30회 신호처리합동학술대회 https://30spc2020.creatorlink.net/ >
d8c1b312c9c527d833fa1f46d07da1a365aeb1d0
[ "Markdown", "Python" ]
3
Python
hjw705/GraduationWork
2e770d9d836dc98452a8b5c0170a72257b750798
970625ab97b6f72387396d0028eac65741eb35d5
refs/heads/master
<file_sep>#include "fonction.h" #include <stdio.h> int main() { printf("%i\n", produit()); return 0; } <file_sep>//éleve au carré //@param int OpA int carre(int); //fonction de soustraction, addition //@param int OpA, int OpB int addsous(int, int); //fonction de multiplication, division //@param int OpA, int OpB int multidiv(int, int); //fonction addition, soustraction, multiplication, division mélangé //@param int OpA, int OpB float adsodimu(float, float); <file_sep>float division(int opA, int opB) { return opA / opB; } <file_sep>#include "fonction.h" int produit() { int a, b, c; a = 12; //b = 3; c = a * 4; return c; } <file_sep>CC = gcc CFLAGS = -Wall -fPIC -shared OBJFILE = addition.o soustraction.o division.o multiplication.o LINKERNAME = arithmetique LIBSTATIC = lib$(LINKERNAME).a LIBDYNA = lib$(LINKERNAME).so STATICEXE = $(LINKERNAME).static DYNAEXE = $(LINKERNAME).dyna LIBMAJOR = 0 LIBMINOR = 0 LIBPATCH = 4 $(OBJFILE): $(LIBSTATIC): $(OBJFILE) ar rcs $@ $^ $(LIBDYNA): $(OBJFILE) $(CC) $(CFLAGS) -Wl,-soname,$@.$(LIBMAJOR) -o $@.$(LIBMAJOR).$(LIBMINOR).$(LIBPATCH) $^ -lc ln -sf $@.$(LIBMAJOR).$(LIBMINOR).$(LIBPATCH) $@ ln -sf $@.$(LIBMAJOR).$(LIBMINOR).$(LIBPATCH) $@.$(LIBMAJOR) $(STATICEXE): main.o $(LIBSTATIC) $(CC) -o $@ $^ ./$@ $(DYNAEXE): main.o $(LIBDYNA) $(CC) -o $@ main.o -L. -l$(LINKERNAME) LD_LIBRARY_PATH=.:$LD_LIBRARY_PATH ./$@ clean: rm *.o *$(LINKERNAME)* clear <file_sep>#include "fonction.h" #include <stdio.h> int main() { int a = 9; int b = 4.5; printf("%i\n", addition(a, b)); //printf("%i\n", soustraction(a, b)); printf("%i\n", multiplication(a, b)); //printf("%f\n", division(a, b)); return 0; } <file_sep>float division(float opA, float opB) { return opA / opB; } <file_sep>int addition(int, int); int soustraction(int, int); int multiplication(int, int); float division(int, int); <file_sep>int produit(); <file_sep>int main() { int a, b, c; a = 12; b = 3; c = a * 4; return c; } <file_sep>int addition(int, int); int soustraction(int, int); int multiplication(int, int); float division(float, float); <file_sep>#include <stdio.h> #include "fonction.h" int main() { int a = 5; int b = 9; printf("%i\n",carre(a)); printf("%i\n",addsous(a,b)); printf("%i\n",multidiv(a,b)); printf("%f\n",adsodimu(a,b)); } <file_sep>int multiplication(int opA, int opB) { int c = 99; return c; }
db478aa4934bc804bffbceebb489506aa6e06b57
[ "C", "Makefile" ]
13
C
JordanMoulin/Slam-5
2b883bbadb157e7fcd436d001a914e09354bc9e1
71f538fc0409cb76c57c822777184fcddd90f14f
refs/heads/duplex-13
<file_sep>/* * Copyright (c) 2009, Sun Microsystems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - Neither the name of Sun Microsystems, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* * This is the rpc server side idle loop * Wait for input, call server program. */ #include <config.h> #if !defined(_WIN32) #include <sys/select.h> #include <err.h> #endif #include <string.h> #include <unistd.h> #include <signal.h> #include <rpc/types.h> /* before portable.h */ #include <misc/portable.h> #include <rpc/rpc.h> #include "rpc_com.h" #include "clnt_internal.h" #include "svc_internal.h" #include "svc_xprt.h" #include "rpc_dplx_internal.h" #include <rpc/svc_rqst.h> extern struct svc_params __svc_params[1]; bool __svc_clean_idle2(int timeout, bool cleanblock); #if defined(TIRPC_EPOLL) void svc_getreqset_epoll(struct epoll_event *events, int nfds); /* static */ void svc_run_epoll(void) { (void)svc_rqst_thrd_run(__svc_params->ev_u.evchan.id, SVC_RQST_FLAG_NONE); } #endif /* TIRPC_EPOLL */ void svc_run(void) { switch (__svc_params->ev_type) { #if defined(TIRPC_EPOLL) case SVC_EVENT_EPOLL: svc_run_epoll(); break; #endif default: /* XXX formerly select/fd_set case, now placeholder for new * event systems, reworked select, etc. */ __warnx(TIRPC_DEBUG_FLAG_SVC, "svc_run: unsupported event type"); break; } /* switch */ } /* * This function causes svc_run() to exit by telling it that it has no * more work to do. */ void svc_exit() { switch (__svc_params->ev_type) { #if defined(TIRPC_EPOLL) case SVC_EVENT_EPOLL: /* signal shutdown backchannel */ (void) svc_rqst_thrd_signal(__svc_params->ev_u.evchan.id, SVC_RQST_SIGNAL_SHUTDOWN); break; #endif default: /* XXX formerly select/fd_set case, now placeholder for new * event systems, reworked select, etc. */ break; } /* switch */ } <file_sep>/* * Copyright (c) 2012-2014 CEA * <NAME> <<EMAIL>> * * DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE * Version 2, December 2004 * * Everyone is permitted to copy and distribute verbatim or modified * copies of this license document, and changing it is allowed as long * as the name is changed. * * DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE * TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION * * 0. You just DO WHAT THE FUCK YOU WANT TO. */ #include <rpc/rpc.h> #include <rpc/clnt.h> #include <rpc/xdr.h> #include <rpc/auth.h> #include <arpa/inet.h> #include <netdb.h> #include <unistd.h> #include <errno.h> #include <mooshika.h> #include "rpc/clnt.h" //#include "nfsv40.h" #include "nfs4.h" #include "fsal_nfsv4_macros.h" /* * Mooshika clnt create routine */ extern CLIENT *clnt_msk_create(msk_trans_t *, const rpcprog_t, const rpcvers_t, u_int); #define PROGNUM 100003 #define NFS_V4 4 #define SENDSIZE 32768 #define RECVSIZE 32768 #define CREDITS 20 inline void die(char* str, int i) { printf("%s: %s (%d)\n", str, strerror(i), i); exit(1); } void nfs4_list_to_bitmap4(bitmap4 * b, uint32_t plen, uint32_t * pval) { uint32_t i; int maxpos = -1; memset(b->bitmap4_val, 0, sizeof(uint32_t)*b->bitmap4_len); for(i = 0; i < plen; i++) { int intpos = pval[i] / 32; int bitpos = pval[i] % 32; if(intpos >= b->bitmap4_len) { printf("Mismatch between bitmap len and the list: " "got %d, need %d to accomodate attribute %d\n", b->bitmap4_len, intpos+1, pval[i]); continue; } b->bitmap4_val[intpos] |= (1U << bitpos); if(intpos > maxpos) maxpos = intpos; } b->bitmap4_len = maxpos + 1; } /* nfs4_list_to_bitmap4 */ void fsal_internal_proxy_create_fattr_readdir_bitmap(bitmap4 * pbitmap) { uint32_t tmpattrlist[20]; uint32_t attrlen = 0; pbitmap->bitmap4_len = 2; memset(pbitmap->bitmap4_val, 0, sizeof(uint32_t) * pbitmap->bitmap4_len); tmpattrlist[0] = FATTR4_TYPE; tmpattrlist[1] = FATTR4_CHANGE; tmpattrlist[2] = FATTR4_SIZE; tmpattrlist[3] = FATTR4_FSID; tmpattrlist[4] = FATTR4_FILEHANDLE; tmpattrlist[5] = FATTR4_FILEID; tmpattrlist[6] = FATTR4_MODE; tmpattrlist[7] = FATTR4_NUMLINKS; tmpattrlist[8] = FATTR4_OWNER; tmpattrlist[9] = FATTR4_OWNER_GROUP; tmpattrlist[10] = FATTR4_SPACE_USED; tmpattrlist[11] = FATTR4_TIME_ACCESS; tmpattrlist[12] = FATTR4_TIME_METADATA; tmpattrlist[13] = FATTR4_TIME_MODIFY; tmpattrlist[14] = FATTR4_RAWDEV; attrlen = 15; nfs4_list_to_bitmap4(pbitmap, attrlen, tmpattrlist); } /* fsal_internal_proxy_create_fattr_readdir_bitmap */ void fsal_internal_proxy_setup_readdir_fattr(fsal_proxy_internal_fattr_readdir_t * pfattr) { /* Just do the correct connection */ pfattr->owner.utf8string_val = pfattr->padowner; pfattr->owner_group.utf8string_val = pfattr->padgroup; pfattr->filehandle.nfs_fh4_val = pfattr->padfh; } int main() { int rc; CLIENT *rpc_client; msk_trans_t *trans; msk_trans_attr_t attr; memset(&attr, 0, sizeof(msk_trans_attr_t)); attr.server = 0; attr.rq_depth = CREDITS; attr.sq_depth = CREDITS; attr.max_send_sge = 4; attr.port = "20049"; attr.node = "127.0.0.1"; attr.debug = 1; if (msk_init(&trans, &attr)) die("couldn't init trans", ENOMEM); rpc_client = clnt_msk_create(trans, PROGNUM, NFS_V4, CREDITS); if (!rpc_client) die("no rpc client", errno); AUTH *auth = authunix_ncreate_default(); struct timeval timeout = TIMEOUTRPC; #if 0 rc = clnt_call(rpc_client, auth, NFSPROC4_NULL, (xdrproc_t) xdr_void, (caddr_t) NULL, (xdrproc_t) xdr_void, (caddr_t) NULL, timeout); if (rc != RPC_SUCCESS) printf("procnull went wrong (%d): %s", rc, clnt_sperrno(rc)); else printf("procnull success!\n"); #endif // 0 COMPOUND4args argnfs4; COMPOUND4res resnfs4; #define NB_OP_ALLOC 2 nfs_argop4 argoparray[NB_OP_ALLOC]; nfs_resop4 resoparray[NB_OP_ALLOC]; memset(argoparray, 0, sizeof(nfs_argop4)*NB_OP_ALLOC); memset(resoparray, 0, sizeof(nfs_resop4)*NB_OP_ALLOC); /* Setup results structures */ argnfs4.argarray.argarray_val = argoparray; resnfs4.resarray.resarray_val = resoparray; argnfs4.minorversion = 0; argnfs4.argarray.argarray_len = 0; /* argnfs4.tag.utf8string_val = "GANESHA NFSv4 Proxy: Lookup Root" ; */ argnfs4.tag.utf8string_val = NULL; argnfs4.tag.utf8string_len = 0; int nbreaddir = 256; proxyfsal_cookie_t start_position; start_position.data = 0; bitmap4 bitmap; uint32_t bitmap_val[2]; bitmap.bitmap4_len = 2; bitmap.bitmap4_val = bitmap_val; fsal_internal_proxy_create_fattr_readdir_bitmap(&bitmap); verifier4 verifier; memset(verifier, 0, sizeof(verifier)); #define IDX_OP_PUTROOTFH 0 #define IDX_OP_READDIR 1 COMPOUNDV4_ARG_ADD_OP_PUTROOTFH(argnfs4); COMPOUNDV4_ARG_ADD_OP_READDIR(argnfs4, start_position.data, nbreaddir, verifier, bitmap); struct proxy_entry4 { entry4 e4; char name[MAXNAMLEN]; fsal_proxy_internal_fattr_readdir_t attr; uint32_t bitmap[2]; } *pxy_e4; pxy_e4 = calloc(nbreaddir, sizeof(*pxy_e4)); if (!pxy_e4) die("calloc failed", ENOMEM); memset(pxy_e4, 0, sizeof(*pxy_e4)*nbreaddir); int i; for (i=0; i<nbreaddir; i++) { fsal_internal_proxy_setup_readdir_fattr(&pxy_e4[i].attr); pxy_e4[i].e4.name.utf8string_val = pxy_e4[i].name; pxy_e4[i].e4.name.utf8string_len = sizeof(pxy_e4[i].name); pxy_e4[i].e4.attrs.attr_vals.attrlist4_val = (char *)&(pxy_e4[i].attr); pxy_e4[i].e4.attrs.attr_vals.attrlist4_len = sizeof(pxy_e4[i].attr); pxy_e4[i].e4.attrs.attrmask.bitmap4_val = pxy_e4[i].bitmap; pxy_e4[i].e4.attrs.attrmask.bitmap4_len = 2; pxy_e4[i].e4.nextentry = &pxy_e4[i+1].e4; /* Last one cleared after the loop */ } pxy_e4[i-1].e4.nextentry = NULL; resnfs4.resarray.resarray_val[IDX_OP_READDIR].nfs_resop4_u.opreaddir.READDIR4res_u.resok4.reply.entries = & pxy_e4->e4; rc = clnt_call(rpc_client, auth, NFSPROC4_COMPOUND, (xdrproc_t) xdr_COMPOUND4args, (caddr_t) &argnfs4, (xdrproc_t) xdr_COMPOUND4res, (caddr_t) &resnfs4, timeout); if (rc != RPC_SUCCESS) printf("compound went wrong (%d): %s\n", rc, clnt_sperrno(rc)); else printf("compound: got status : %x\n", resnfs4.resarray.resarray_val[IDX_OP_PUTROOTFH].nfs_resop4_u.opputrootfh.status); // use %s? msk_destroy_trans(&trans); return 0; } <file_sep>GANESHA_BUILD=/opt/GANESHA/build-nfs CFLAGS=-g -Wall -Werror -I../ntirpc LDFLAGS=-L$(GANESHA_BUILD)/libntirpc/src all: nfs4_testmsk nfs4_server nfs4_testmsk: nfs4_testmsk.c nfs4_xdr.o gcc $(CFLAGS) $(LDFLAGS) nfs4_xdr.o nfs4_testmsk.c -o nfs4_testmsk -lntirpc -lmooshika -lrt -lpthread -lgssapi_krb5 nfs4_server: nfs4_server.c nfs4_xdr.o gcc $(CFLAGS) $(LDFLAGS) nfs4_xdr.o nfs4_server.c -o nfs4_server -lntirpc -lmooshika -lrt -lpthread -lgssapi_krb5 #ignore CFLAGS for that one... nfs4_xdr.o: nfs4_xdr.c gcc -g -I../tirpc -c nfs4_xdr.c clean: rm -f *.o nfs4_{testmsk,server} <file_sep>/* * Copyright (c) 2012 Linux Box Corporation. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR `AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef XDR_INREC_H #define XDR_INREC_H #include <stdint.h> #include <stdbool.h> /* XDR pseudo records for tcp */ extern void xdr_inrec_create(XDR *, u_int, void *, int (*)(XDR * xdrs, void *, void *, int)); extern bool xdr_inrec_readahead(XDR *xdrs, u_int maxfraglen); /* make end of xdr record */ extern bool xdr_inrec_endofrecord(XDR *, bool); /* move to beginning of next record */ extern bool xdr_inrec_skiprecord(XDR *); /* true if no more input */ extern bool xdr_inrec_eof(XDR *); /* intrinsic checksum (be careful) */ extern uint64_t xdr_inrec_cksum(XDR *); #endif /* XDR_INREC_H */ <file_sep>/* * Copyright (c) 2012 Linux Box Corporation. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR `AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TIRPC_SVC_RQST_H #define TIRPC_SVC_RQST_H #include <rpc/svc.h> /** ** Maintains a tree of all extant transports by event **/ #define SVC_RQST_FLAG_NONE SVC_XPRT_FLAG_NONE /* uint16_t actually used */ #define SVC_RQST_FLAG_CHAN_AFFINITY 0x1000 /* bind conn to parent chan */ #define SVC_RQST_FLAG_MASK (SVC_RQST_FLAG_CHAN_AFFINITY) /* uint32_t instructions */ #define SVC_RQST_FLAG_LOCKED SVC_XPRT_FLAG_LOCKED #define SVC_RQST_FLAG_UNLOCK SVC_XPRT_FLAG_UNLOCK #define SVC_RQST_FLAG_EPOLL 0x00080000 #define SVC_RQST_FLAG_PART_LOCKED 0x00100000 #define SVC_RQST_FLAG_PART_UNLOCK 0x00200000 #define SVC_RQST_FLAG_SREC_LOCKED 0x01000000 #define SVC_RQST_FLAG_SREC_UNLOCK 0x02000000 #define SVC_RQST_FLAG_XPRT_UREG 0x04000000 #define SR_REQ_RELEASE_KEEP_LOCKED 0x08000000 /* * exported interface: * * svc_rqst_init -- init module (optional) * svc_rqst_init_xprt -- init svc_rqst part of xprt handle * svc_rqst_new_evchan -- create event channel * svc_rqst_evchan_reg -- set {xprt, dispatcher} mapping * svc_rqst_foreach_xprt -- scan registered xprts at id (or 0 for all) * svc_rqst_thrd_run -- enter dispatch loop at id * svc_rqst_thrd_signal --request thread to run a callout function which * can cause the thread to return * svc_rqst_shutdown -- cause all threads to return * * callback function interface: * * svc_xprt_rendezvous -- called when a new transport connection is accepted, * can be used by the application to chose a correct request handler, or do * other adaptation */ void svc_rqst_init(); void svc_rqst_init_xprt(SVCXPRT *xprt); int svc_rqst_new_evchan(uint32_t *chan_id /* OUT */ , void *u_data, uint32_t flags); int svc_rqst_evchan_reg(uint32_t chan_id, SVCXPRT *xprt, uint32_t flags); int svc_rqst_rearm_events(SVCXPRT *xprt, uint32_t flags); int svc_rqst_xprt_register(SVCXPRT *xprt, SVCXPRT *newxprt); int svc_rqst_thrd_run(uint32_t chan_id, uint32_t flags); int svc_rqst_thrd_signal(uint32_t chan_id, uint32_t flags); /* xprt/connection rendezvous callout */ typedef int (*svc_rqst_rendezvous_t) (SVCXPRT *oxprt, SVCXPRT *nxprt, uint32_t flags); /* iterator callback prototype */ typedef void (*svc_rqst_xprt_each_func_t) (uint32_t chan_id, SVCXPRT *xprt, void *arg); int svc_rqst_foreach_xprt(uint32_t chan_id, svc_rqst_xprt_each_func_t each_f, void *arg); #define SVC_RQST_STATE_NONE 0x00000 #define SVC_RQST_STATE_ACTIVE 0x00001 /* thrd in event loop */ #define SVC_RQST_STATE_BLOCKED 0x00002 /* channel blocked */ #define SVC_RQST_STATE_DESTROYED 0x00004 #define SVC_RQST_SIGNAL_SHUTDOWN 0x00008 /* chan shutdown */ #define SVC_RQST_SIGNAL_MASK (SVC_RQST_SIGNAL_SHUTDOWN) #endif /* TIRPC_SVC_RQST_H */ <file_sep>/* * Copyright (c) 2009, Sun Microsystems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - Neither the name of Sun Microsystems, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* * Copyright (c) 1986 - 1991 by Sun Microsystems, Inc. */ /* * clnt_internal.h Internal client structures needed by some async * svc routines */ #ifndef _CLNT_INTERNAL_H #define _CLNT_INTERNAL_H struct ct_wait_entry { mutex_t mtx; cond_t cv; }; #include <misc/rbtree_x.h> #include <rpc/work_pool.h> #include <rpc/xdr_ioq.h> #include <misc/wait_queue.h> typedef struct rpc_dplx_lock { struct wait_entry we; int32_t lock_flag_value; /* XXX killme */ struct { const char *func; int line; } locktrace; } rpc_dplx_lock_t; #define MCALL_MSG_SIZE 24 #define CT_NONE 0x0000 #define CT_EVENTS_BLOCKED 0x0002 #define CT_EPOLL_ACTIVE 0x0004 #define CT_XPRT_DESTROYED 0x0008 /* * A client call context. Intended to enable efficient multiplexing of * client calls sharing a client channel. */ typedef struct rpc_call_ctx { struct opr_rbtree_node node_k; struct wait_entry we; uint32_t xid; uint32_t flags; struct rpc_msg *msg; struct rpc_err error; union { struct { struct rpc_client *clnt; struct x_vc_data *xd; struct timespec timeout; } clnt; struct { /* nothing */ } svc; } ctx_u; } rpc_ctx_t; static inline int call_xid_cmpf(const struct opr_rbtree_node *lhs, const struct opr_rbtree_node *rhs) { rpc_ctx_t *lk, *rk; lk = opr_containerof(lhs, rpc_ctx_t, node_k); rk = opr_containerof(rhs, rpc_ctx_t, node_k); if (lk->xid < rk->xid) return (-1); if (lk->xid == rk->xid) return (0); return (1); } /* unify client private data */ struct cu_data { XDR cu_outxdrs; int cu_fd; /* connections fd */ bool cu_closeit; /* opened by library */ struct sockaddr_storage cu_raddr; /* remote address */ int cu_rlen; struct timeval cu_wait; /* retransmit interval */ struct timeval cu_total; /* total time for the call */ struct rpc_err cu_error; u_int cu_xdrpos; u_int cu_sendsz; /* send size */ u_int cu_recvsz; /* recv size */ int cu_async; int cu_connect; /* Use connect(). */ int cu_connected; /* Have done connect(). */ /* formerly, buffers were tacked onto the end */ char *cu_inbuf; char *cu_outbuf; }; struct ct_serialized { union { char ct_mcallc[MCALL_MSG_SIZE]; /* marshalled callmsg */ u_int32_t ct_mcalli; } ct_u; u_int ct_mpos; /* pos after marshal */ }; struct ct_data { int ct_fd; bool ct_closeit; /* close it on destroy */ struct timeval ct_wait; /* wait interval in milliseconds */ bool ct_waitset; /* wait set by clnt_control? */ struct netbuf ct_addr; /* remote addr */ struct wait_entry ct_sync; /* wait for completion */ }; #ifdef USE_RPC_RDMA struct cm_data { XDR cm_xdrs; char *buffers; struct timeval cm_wait; /* wait interval in milliseconds */ struct timeval cm_total; /* total time for the call */ struct rpc_err cm_error; struct rpc_msg call_msg; //add a lastreceive? u_int cm_xdrpos; bool cm_closeit; /* close it on destroy */ }; #endif enum CX_TYPE { CX_DG_DATA, CX_VC_DATA, CX_MSK_DATA }; #define X_VC_DATA_FLAG_NONE 0x0000 #define X_VC_DATA_FLAG_SVC_DESTROYED 0x0001 /* new unified state */ struct rpc_dplx_rec { int fd_k; #if 0 mutex_t mtx; #else struct { mutex_t mtx; const char *func; int line; } locktrace; #endif struct opr_rbtree_node node_k; uint32_t refcnt; struct { rpc_dplx_lock_t lock; } send; struct { rpc_dplx_lock_t lock; } recv; struct { struct x_vc_data *xd; SVCXPRT *xprt; } hdl; }; #define REC_LOCK(rec) \ do { \ mutex_lock(&((rec)->locktrace.mtx)); \ (rec)->locktrace.func = __func__; \ (rec)->locktrace.line = __LINE__; \ } while (0) #define REC_UNLOCK(rec) mutex_unlock(&((rec)->locktrace.mtx)) struct cx_data { enum CX_TYPE type; union { struct cu_data cu; struct ct_data ct; #ifdef USE_RPC_RDMA struct cm_data cm; #endif } c_u; int cx_fd; /* connection's fd */ struct rpc_dplx_rec *cx_rec; /* unified sync */ }; struct x_vc_data { struct work_pool_entry wpe; /*** 1st ***/ struct rpc_dplx_rec *rec; /* unified sync */ uint32_t flags; uint32_t refcnt; struct { struct ct_data data; struct { uint32_t xid; /* current xid */ struct opr_rbtree t; } calls; } cx; struct { enum xprt_stat strm_stat; struct timespec last_recv; /* XXX move to shared? */ int32_t maxrec; } sx; struct { struct poolq_head ioq; bool active; bool nonblock; u_int sendsz; u_int recvsz; XDR xdrs_in; /* send queue */ XDR xdrs_out; /* recv queue */ } shared; }; #define CU_DATA(cx) (&(cx)->c_u.cu) #define CT_DATA(cx) (&(cx)->c_u.ct) #define CM_DATA(cx) (&(cx)->c_u.cm) /* compartmentalize a bit */ static inline struct x_vc_data * alloc_x_vc_data(void) { struct x_vc_data *xd = mem_zalloc(sizeof(struct x_vc_data)); TAILQ_INIT(&xd->shared.ioq.qh); return (xd); } static inline void free_x_vc_data(struct x_vc_data *xd) { mem_free(xd, sizeof(struct x_vc_data)); } static inline struct cx_data * alloc_cx_data(enum CX_TYPE type, uint32_t sendsz, uint32_t recvsz) { struct cx_data *cx = mem_zalloc(sizeof(struct cx_data)); cx->type = type; switch (type) { case CX_DG_DATA: cx->c_u.cu.cu_inbuf = mem_alloc(recvsz); cx->c_u.cu.cu_outbuf = mem_alloc(sendsz); case CX_VC_DATA: case CX_MSK_DATA: break; default: /* err */ __warnx(TIRPC_DEBUG_FLAG_MEM, "%s: asked to allocate cx_data of unknown type (BUG)", __func__); break; }; return (cx); } static inline void free_cx_data(struct cx_data *cx) { switch (cx->type) { case CX_DG_DATA: mem_free(cx->c_u.cu.cu_inbuf, cx->c_u.cu.cu_recvsz); mem_free(cx->c_u.cu.cu_outbuf, cx->c_u.cu.cu_sendsz); case CX_VC_DATA: case CX_MSK_DATA: break; default: /* err */ __warnx(TIRPC_DEBUG_FLAG_MEM, "%s: asked to free cx_data of unknown type (BUG)", __func__); break; }; mem_free(cx, sizeof(struct cx_data)); } void vc_shared_destroy(struct x_vc_data *xd); #endif /* _CLNT_INTERNAL_H */ <file_sep>/* * Copyright (c) 2012 Linux Box Corporation. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR `AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <config.h> #include <sys/types.h> #include <sys/poll.h> #include <stdint.h> #include <assert.h> #include <err.h> #include <errno.h> #include <unistd.h> #include <fcntl.h> #include <signal.h> #include <rpc/types.h> #include <misc/portable.h> #include <rpc/rpc.h> #ifdef PORTMAP #include <rpc/pmap_clnt.h> #endif /* PORTMAP */ #include <rpc/svc_rqst.h> #include "rpc_com.h" #include <rpc/svc.h> #include <misc/rbtree_x.h> #include <misc/opr_queue.h> #include "clnt_internal.h" #include "svc_internal.h" #include <rpc/svc_rqst.h> #include "svc_xprt.h" /* * The TI-RPC instance should be able to reach every registered * handler, and potentially each SVCXPRT registered on it. * * Each SVCXPRT points to its own handler, however, so operations to * block/unblock events (for example) given an existing xprt handle * are O(1) without any ordered or hashed representation. */ #define SVC_RQST_PARTITIONS 7 static bool initialized; struct svc_rqst_set { mutex_t mtx; struct rbtree_x xt; uint32_t next_id; }; static struct svc_rqst_set svc_rqst_set = { MUTEX_INITIALIZER, /* mtx */ { 0, /* npart */ RBT_X_FLAG_NONE, /* flags */ 23, /* cachesz */ NULL /* tree */ }, /* xt */ 0 /* next_id */ }; extern struct svc_params __svc_params[1]; #define cond_init_svc_rqst() { \ do { \ if (!initialized) \ svc_rqst_init(); \ } while (0); \ } struct svc_rqst_rec { struct opr_rbtree_node node_k; TAILQ_HEAD(evq_head, rpc_svcxprt) xprt_q; /* xprt handles */ pthread_mutex_t mtx; void *u_data; /* user-installable opaque data */ uint64_t gen; /* generation number */ int sv[2]; uint32_t id_k; /* chan id */ uint32_t states; uint32_t signals; uint32_t refcnt; uint16_t flags; /* * union of event processor types */ enum svc_event_type ev_type; union { #if defined(TIRPC_EPOLL) struct { int epoll_fd; struct epoll_event ctrl_ev; struct epoll_event *events; u_int max_events; /* max epoll events */ } epoll; #endif struct { fd_set set; /* select/fd_set (currently unhooked) */ } fd; } ev_u; }; static inline int rqst_thrd_cmpf(const struct opr_rbtree_node *lhs, const struct opr_rbtree_node *rhs) { struct svc_rqst_rec *lk, *rk; lk = opr_containerof(lhs, struct svc_rqst_rec, node_k); rk = opr_containerof(rhs, struct svc_rqst_rec, node_k); if (lk->id_k < rk->id_k) return (-1); if (lk->id_k == rk->id_k) return (0); return (1); } /* forward declaration in lieu of moving code {WAS} */ static int svc_rqst_evchan_unreg(uint32_t chan_id, SVCXPRT *xprt, uint32_t flags); static int svc_rqst_unhook_events(SVCXPRT *, struct svc_rqst_rec *); static int svc_rqst_hook_events(SVCXPRT *, struct svc_rqst_rec *); static inline void SetNonBlock(int fd) { int s_flags = fcntl(fd, F_GETFL, 0); (void)fcntl(fd, F_SETFL, (s_flags | O_NONBLOCK)); } void svc_rqst_init() { int ix, code = 0; mutex_lock(&svc_rqst_set.mtx); if (initialized) goto unlock; code = rbtx_init(&svc_rqst_set.xt, rqst_thrd_cmpf, SVC_RQST_PARTITIONS, RBT_X_FLAG_ALLOC | RBT_X_FLAG_CACHE_RT); if (code) __warnx(TIRPC_DEBUG_FLAG_SVC_RQST, "%s: rbtx_init failed", __func__); /* init read-through cache */ for (ix = 0; ix < SVC_RQST_PARTITIONS; ++ix) { struct rbtree_x_part *xp = &(svc_rqst_set.xt.tree[ix]); xp->cache = mem_calloc(svc_rqst_set.xt.cachesz, sizeof(struct opr_rbtree_node *)); } initialized = true; unlock: mutex_unlock(&svc_rqst_set.mtx); } void svc_rqst_init_xprt(SVCXPRT *xprt) { /* reachable */ svc_xprt_set(xprt, SVC_XPRT_FLAG_UNLOCK); /* !!! not checking for duplicate xp_fd ??? */ } /** * @brief Lookup a channel * @note Locking * - SVC_RQST_FLAG_PART_UNLOCK - Unlock the tree partition before returning. * Otherwise, it is returned locked. * - SVC_RQST_FLAG_SREC_LOCKED - The sr_rec is already locked; don't lock it * again. * - SVC_RQST_FLAG_SREC_UNLOCK - Unlock the sr_rec before returning. Otherwise, * it is returned locked. */ static inline struct svc_rqst_rec * svc_rqst_lookup_chan(uint32_t chan_id, struct rbtree_x_part **ref_t, uint32_t flags) { struct svc_rqst_rec trec; struct rbtree_x_part *t; struct opr_rbtree_node *ns; struct svc_rqst_rec *sr_rec = NULL; cond_init_svc_rqst(); trec.id_k = chan_id; t = rbtx_partition_of_scalar(&svc_rqst_set.xt, trec.id_k); *ref_t = t; mutex_lock(&t->mtx); ns = rbtree_x_cached_lookup(&svc_rqst_set.xt, t, &trec.node_k, trec.id_k); if (ns) { sr_rec = opr_containerof(ns, struct svc_rqst_rec, node_k); if (!(flags & SVC_RQST_FLAG_SREC_LOCKED)) mutex_lock(&sr_rec->mtx); ++(sr_rec->refcnt); if (flags & SVC_RQST_FLAG_SREC_UNLOCK) mutex_unlock(&sr_rec->mtx); } if (flags & SVC_RQST_FLAG_PART_UNLOCK) mutex_unlock(&t->mtx); return (sr_rec); } int svc_rqst_new_evchan(uint32_t *chan_id /* OUT */, void *u_data, uint32_t flags) { uint32_t n_id; struct svc_rqst_rec *sr_rec; struct rbtree_x_part *t; bool rslt __attribute__ ((unused)); int code = 0; cond_init_svc_rqst(); flags |= SVC_RQST_FLAG_EPOLL; /* XXX */ sr_rec = mem_zalloc(sizeof(struct svc_rqst_rec)); /* create a pair of anonymous sockets for async event channel wakeups */ code = socketpair(AF_UNIX, SOCK_STREAM, 0, sr_rec->sv); if (code) { __warnx(TIRPC_DEBUG_FLAG_SVC_RQST, "%s: failed creating event signal socketpair", __func__); mem_free(sr_rec, sizeof(struct svc_rqst_rec)); goto out; } /* set non-blocking */ SetNonBlock(sr_rec->sv[0]); SetNonBlock(sr_rec->sv[1]); #if defined(TIRPC_EPOLL) if (flags & SVC_RQST_FLAG_EPOLL) { sr_rec->flags = flags & SVC_RQST_FLAG_MASK; sr_rec->ev_type = SVC_EVENT_EPOLL; /* XXX improve this too */ sr_rec->ev_u.epoll.max_events = __svc_params->ev_u.evchan.max_events; sr_rec->ev_u.epoll.events = (struct epoll_event *) mem_alloc(sr_rec->ev_u.epoll.max_events * sizeof(struct epoll_event)); /* create epoll fd */ sr_rec->ev_u.epoll.epoll_fd = epoll_create_wr(sr_rec->ev_u.epoll.max_events, EPOLL_CLOEXEC); if (sr_rec->ev_u.epoll.epoll_fd == -1) { __warnx(TIRPC_DEBUG_FLAG_SVC_RQST, "%s: epoll_create failed (%d)", __func__, errno); mem_free(sr_rec->ev_u.epoll.events, sr_rec->ev_u.epoll.max_events * sizeof(struct epoll_event)); mem_free(sr_rec, sizeof(struct svc_rqst_rec)); code = EINVAL; goto out; } /* permit wakeup of threads blocked in epoll_wait, with a * couple of possible semantics */ sr_rec->ev_u.epoll.ctrl_ev.events = EPOLLIN | EPOLLRDHUP; sr_rec->ev_u.epoll.ctrl_ev.data.fd = sr_rec->sv[1]; code = epoll_ctl(sr_rec->ev_u.epoll.epoll_fd, EPOLL_CTL_ADD, sr_rec->sv[1], &sr_rec->ev_u.epoll.ctrl_ev); if (code == -1) __warnx(TIRPC_DEBUG_FLAG_SVC_RQST, "%s: add control socket failed (%d)", __func__, errno); } else { /* legacy fdset (currently unhooked) */ sr_rec->ev_type = SVC_EVENT_FDSET; } #else sr_rec->ev_type = SVC_EVENT_FDSET; #endif mutex_lock(&svc_rqst_set.mtx); n_id = ++(svc_rqst_set.next_id); mutex_unlock(&svc_rqst_set.mtx); sr_rec->id_k = n_id; sr_rec->states = SVC_RQST_STATE_NONE; sr_rec->u_data = u_data; sr_rec->refcnt = 1; /* svc_rqst_set ref */ sr_rec->gen = 0; mutex_init(&sr_rec->mtx, NULL); TAILQ_INIT(&sr_rec->xprt_q); t = rbtx_partition_of_scalar(&svc_rqst_set.xt, sr_rec->id_k); mutex_lock(&t->mtx); rslt = rbtree_x_cached_insert(&svc_rqst_set.xt, t, &sr_rec->node_k, sr_rec->id_k); mutex_unlock(&t->mtx); __warnx(TIRPC_DEBUG_FLAG_SVC_RQST, "%s: create evchan %d socketpair %d:%d", __func__, n_id, sr_rec->sv[0], sr_rec->sv[1]); *chan_id = n_id; out: return (code); } /* * @note Lock flags * - Locks xprt unless SVC_RQST_FLAG_LOCKED is passed * - Locks sr_rec unless RVC_RQST_FLAG_SREC_LOCKED is passed * - Returns with xprt locked unless SVC_RQST_FLAG_UNLOCK is passed * - Returns with sr_rec locked unless SVC_RQST_FLAG_SREC_UNLOCKED is passed */ static inline void evchan_unreg_impl(struct svc_rqst_rec *sr_rec, SVCXPRT *xprt, uint32_t flags) { if (!(flags & SVC_RQST_FLAG_SREC_LOCKED)) mutex_lock(&sr_rec->mtx); if (!(flags & SVC_RQST_FLAG_LOCKED)) mutex_lock(&xprt->xp_lock); TAILQ_REMOVE(&sr_rec->xprt_q, xprt, xp_evq); /* clear events */ (void)svc_rqst_unhook_events(xprt, sr_rec); /* both LOCKED */ /* unlink from xprt */ xprt->xp_ev = NULL; __warnx(TIRPC_DEBUG_FLAG_REFCNT, "%s: %p xp_refs %" PRIu32 " after remove, before channel release", __func__, xprt, xprt->xp_refs); if (flags & SVC_RQST_FLAG_UNLOCK) mutex_unlock(&xprt->xp_lock); if (flags & SVC_RQST_FLAG_SREC_UNLOCK) mutex_unlock(&sr_rec->mtx); } /* * Write 4-byte value to shared event-notification channel. The * value as presently implemented can be interpreted only by one consumer, * so is not relied on. */ static inline void ev_sig(int fd, uint32_t sig) { int code = write(fd, &sig, sizeof(uint32_t)); __warnx(TIRPC_DEBUG_FLAG_SVC_RQST, "%s: fd %d sig %d", __func__, fd, sig); if (code < 1) __warnx(TIRPC_DEBUG_FLAG_SVC_RQST, "%s: error writing to event socket (%d:%d)", __func__, code, errno); } /* * Read a single 4-byte value from the shared event-notification channel, * the socket is in non-blocking mode. The value read is returned. */ static inline uint32_t consume_ev_sig_nb(int fd) { uint32_t sig = 0; int code __attribute__ ((unused)); code = read(fd, &sig, sizeof(uint32_t)); return (sig); } /** * Release a request * @note Locking * - sr_req is locked unless SVC_RQST_FLAG_SREC_LOCKED is passed * - sr_req is unlocked unless SR_REQ_RELEASE_KEEP_LOCKED is passed */ static inline void sr_rec_release(struct svc_rqst_rec *sr_rec, uint32_t flags) { uint32_t refcnt; if (!(flags & SVC_RQST_FLAG_SREC_LOCKED)) mutex_lock(&sr_rec->mtx); refcnt = --(sr_rec->refcnt); if (!(flags & SR_REQ_RELEASE_KEEP_LOCKED)) mutex_unlock(&sr_rec->mtx); if (refcnt == 0) { if (flags & SR_REQ_RELEASE_KEEP_LOCKED) mutex_unlock(&sr_rec->mtx); /* assert sr_rec DESTROYED */ mutex_destroy(&sr_rec->mtx); mem_free(sr_rec, sizeof(struct svc_rqst_rec)); } } static int svc_rqst_delete_evchan(uint32_t chan_id) { struct svc_rqst_rec *sr_rec; struct rbtree_x_part *t; SVCXPRT *next; SVCXPRT *xprt = NULL; int code = 0; sr_rec = svc_rqst_lookup_chan(chan_id, &t, SVC_XPRT_FLAG_NONE); if (!sr_rec) { mutex_unlock(&t->mtx); code = ENOENT; goto out; } /* traverse sr_req->xprt_q inorder */ /* sr_rec LOCKED */ xprt = TAILQ_FIRST(&sr_rec->xprt_q); while (xprt) { next = TAILQ_NEXT(xprt, xp_evq); /* indirect on xp_ev */ /* stop processing events */ evchan_unreg_impl(sr_rec, xprt, (SVC_RQST_FLAG_UNLOCK | SVC_RQST_FLAG_SREC_LOCKED)); /* wake up */ ev_sig(sr_rec->sv[0], 0); switch (sr_rec->ev_type) { #if defined(TIRPC_EPOLL) case SVC_EVENT_EPOLL: code = epoll_ctl(sr_rec->ev_u.epoll.epoll_fd, EPOLL_CTL_DEL, sr_rec->sv[1], &sr_rec->ev_u.epoll.ctrl_ev); if (code == -1) __warnx(TIRPC_DEBUG_FLAG_SVC_RQST, "%s: epoll del control socket failed (%d)", __func__, errno); break; #endif default: break; } xprt = next; } /* now remove sr_rec */ rbtree_x_cached_remove(&svc_rqst_set.xt, t, &sr_rec->node_k, sr_rec->id_k); mutex_unlock(&t->mtx); switch (sr_rec->ev_type) { #if defined(TIRPC_EPOLL) case SVC_EVENT_EPOLL: close(sr_rec->ev_u.epoll.epoll_fd); mem_free(sr_rec->ev_u.epoll.events, sr_rec->ev_u.epoll.max_events * sizeof(struct epoll_event)); break; #endif default: /* XXX */ break; } sr_rec->states = SVC_RQST_STATE_DESTROYED; sr_rec->id_k = 0; /* no chan */ /* ref count here should be 2: * 1 initial create/rbt ref we just deleted * +1 lookup (top of this routine through here) * so, DROP one ref here so the final release will go to 0. */ --(sr_rec->refcnt); /* DROP one extra ref - initial create */ sr_rec_release(sr_rec, SVC_RQST_FLAG_SREC_LOCKED); out: return (code); } int svc_rqst_evchan_reg(uint32_t chan_id, SVCXPRT *xprt, uint32_t flags) { struct svc_rqst_rec *sr_rec; struct rbtree_x_part *t; int code = 0; if (chan_id == 0) { __warnx(TIRPC_DEBUG_FLAG_SVC_RQST, "%s: called with chan_id 0, fatal (bug)", __func__); goto out; } sr_rec = svc_rqst_lookup_chan(chan_id, &t, SVC_XPRT_FLAG_NONE); if (!sr_rec) { mutex_unlock(&t->mtx); code = ENOENT; goto out; } mutex_lock(&xprt->xp_lock); if (flags & SVC_RQST_FLAG_XPRT_UREG) { if (chan_id != __svc_params->ev_u.evchan.id) { svc_rqst_evchan_unreg(__svc_params->ev_u.evchan.id, xprt, (SVC_RQST_FLAG_LOCKED | SVC_RQST_FLAG_SREC_LOCKED)); svc_xprt_clear(xprt, SVC_XPRT_FLAG_LOCKED); } } TAILQ_INSERT_TAIL(&sr_rec->xprt_q, xprt, xp_evq); /* link from xprt */ xprt->xp_ev = sr_rec; /* register on event channel */ (void)svc_rqst_hook_events(xprt, sr_rec); __warnx(TIRPC_DEBUG_FLAG_REFCNT, "%s: pre channel %p xp_refs %" PRIu32, __func__, xprt, xprt->xp_refs); mutex_unlock(&xprt->xp_lock); sr_rec_release(sr_rec, SVC_RQST_FLAG_SREC_LOCKED); mutex_unlock(&t->mtx); out: return (code); } /** * Unregister an evchan * @note Locking * - Takes sr_req lock, unless SVC_RQST_FLAG_SREC_LOCKED is passed * - Takes xprt lock, unless SVC_RQST_FLAG_LOCKED is passed * - Returns with sr_req locked and xprt locked at all times */ static int svc_rqst_evchan_unreg(uint32_t chan_id, SVCXPRT *xprt, uint32_t flags) { struct svc_rqst_rec *sr_rec; struct rbtree_x_part *t; int code = EINVAL; /* Don't let them force unlocking of the part; we need that */ flags &= ~(SVC_RQST_FLAG_PART_UNLOCK | SVC_RQST_FLAG_SREC_UNLOCK); sr_rec = svc_rqst_lookup_chan(chan_id, &t, flags); if (!sr_rec) { code = ENOENT; goto unlock; } evchan_unreg_impl(sr_rec, xprt, (flags | SVC_RQST_FLAG_SREC_LOCKED)); unlock: mutex_unlock(&t->mtx); if (sr_rec) sr_rec_release(sr_rec, SVC_RQST_FLAG_SREC_LOCKED | SR_REQ_RELEASE_KEEP_LOCKED); return (code); } static int svc_rqst_unhook_events(SVCXPRT *xprt /* LOCKED */ , struct svc_rqst_rec *sr_rec /* LOCKED */) { int code; cond_init_svc_rqst(); atomic_set_uint16_t_bits(&xprt->xp_flags, SVC_XPRT_FLAG_BLOCKED); switch (sr_rec->ev_type) { #if defined(TIRPC_EPOLL) case SVC_EVENT_EPOLL: { struct epoll_event *ev = &xprt->ev_u.epoll.event; /* clear epoll vector */ code = epoll_ctl(sr_rec->ev_u.epoll.epoll_fd, EPOLL_CTL_DEL, xprt->xp_fd, ev); if (code) { __warnx(TIRPC_DEBUG_FLAG_ERROR, "%s: %p epoll del failed fd %d " "sr_rec %p epoll_fd %d " "control fd pair (%d:%d) (%d, %d)", sr_rec, sr_rec->ev_u.epoll.epoll_fd, sr_rec->sv[0], sr_rec->sv[1], code, errno); code = errno; } else { atomic_clear_uint16_t_bits(&xprt->xp_flags, SVC_XPRT_FLAG_ADDED); __warnx(TIRPC_DEBUG_FLAG_SVC_RQST, "%s: %p epoll del fd %d " "sr_rec %p epoll_fd %d " "control fd pair (%d:%d) (%d, %d)", __func__, xprt, xprt->xp_fd, sr_rec, sr_rec->ev_u.epoll.epoll_fd, sr_rec->sv[0], sr_rec->sv[1], code, errno); } break; } #endif default: /* XXX formerly select/fd_set case, now placeholder for new * event systems, reworked select, etc. */ break; } /* switch */ return (0); } int svc_rqst_rearm_events(SVCXPRT *xprt, uint32_t __attribute__ ((unused)) flags) { struct svc_rqst_rec *sr_rec; int code; cond_init_svc_rqst(); sr_rec = (struct svc_rqst_rec *)xprt->xp_ev; /* Don't rearm a destroyed (but not yet collected) xprx */ if (xprt->xp_flags & SVC_XPRT_FLAG_DESTROYED) goto out; /* MUST follow the destroyed check above */ assert(sr_rec); mutex_lock(&sr_rec->mtx); if (atomic_fetch_uint16_t(&xprt->xp_flags) & SVC_XPRT_FLAG_ADDED) { switch (sr_rec->ev_type) { #if defined(TIRPC_EPOLL) case SVC_EVENT_EPOLL: { struct epoll_event *ev = &xprt->ev_u.epoll.event; /* set up epoll user data */ /* ev->data.ptr = xprt; *//* XXX already set */ ev->events = EPOLLIN | EPOLLONESHOT; /* rearm in epoll vector */ code = epoll_ctl(sr_rec->ev_u.epoll.epoll_fd, EPOLL_CTL_MOD, xprt->xp_fd, ev); __warnx(TIRPC_DEBUG_FLAG_SVC_RQST, "%s: %p epoll arm fd %d " "sr_rec %p epoll_fd %d " "control fd pair (%d:%d) (%d, %d)", __func__, xprt, xprt->xp_fd, sr_rec, sr_rec->ev_u.epoll.epoll_fd, sr_rec->sv[0], sr_rec->sv[1], code, errno); break; } #endif default: /* XXX formerly select/fd_set case, now placeholder * for new event systems, reworked select, etc. */ break; } /* switch */ } mutex_unlock(&sr_rec->mtx); out: return (0); } static int svc_rqst_hook_events(SVCXPRT *xprt /* LOCKED */ , struct svc_rqst_rec *sr_rec /* LOCKED */) { int code; cond_init_svc_rqst(); atomic_clear_uint16_t_bits(&xprt->xp_flags, SVC_XPRT_FLAG_BLOCKED); switch (sr_rec->ev_type) { #if defined(TIRPC_EPOLL) case SVC_EVENT_EPOLL: { struct epoll_event *ev = &xprt->ev_u.epoll.event; /* set up epoll user data */ ev->data.ptr = xprt; /* wait for read events, level triggered, oneshot */ ev->events = EPOLLIN | EPOLLONESHOT; /* add to epoll vector */ code = epoll_ctl(sr_rec->ev_u.epoll.epoll_fd, EPOLL_CTL_ADD, xprt->xp_fd, ev); if (code) { __warnx(TIRPC_DEBUG_FLAG_ERROR, "%s: %p epoll add failed fd %d " "sr_rec %p epoll_fd %d " "control fd pair (%d:%d) (%d, %d)", __func__, xprt, xprt->xp_fd, sr_rec, sr_rec->ev_u.epoll.epoll_fd, sr_rec->sv[0], sr_rec->sv[1], code, errno); code = errno; } else { atomic_set_uint16_t_bits(&xprt->xp_flags, SVC_XPRT_FLAG_ADDED); __warnx(TIRPC_DEBUG_FLAG_SVC_RQST, "%s: %p epoll add fd %d " "sr_rec %p epoll_fd %d " "control fd pair (%d:%d) (%d, %d)", __func__, xprt, xprt->xp_fd, sr_rec, sr_rec->ev_u.epoll.epoll_fd, sr_rec->sv[0], sr_rec->sv[1], code, errno); } break; } #endif default: /* XXX formerly select/fd_set case, now placeholder for new * event systems, reworked select, etc. */ break; } /* switch */ ev_sig(sr_rec->sv[0], 0); /* send wakeup */ return (0); } /* register newxprt on an event channel, based on various * parameters */ int svc_rqst_xprt_register(SVCXPRT *xprt, SVCXPRT *newxprt) { struct svc_rqst_rec *sr_rec; int code = 0; cond_init_svc_rqst(); /* do nothing if event registration is globally disabled */ if (__svc_params->flags & SVC_FLAG_NOREG_XPRTS) goto out; /* use global registration if no parent xprt */ if (!xprt) { xprt_register(newxprt); goto out; } sr_rec = (struct svc_rqst_rec *)xprt->xp_ev; /* or if parent xprt has no dedicated event channel */ if (!sr_rec) { xprt_register(newxprt); goto out; } /* follow policy if applied. the client code will still normally * be called back to, e.g., adjust channel assignment */ if (sr_rec->flags & SVC_RQST_FLAG_CHAN_AFFINITY) svc_rqst_evchan_reg(sr_rec->id_k, newxprt, SVC_RQST_FLAG_NONE); else xprt_register(newxprt); out: return (code); } void xprt_unregister(SVCXPRT *xprt) { struct svc_rqst_rec *sr_rec = (struct svc_rqst_rec *)xprt->xp_ev; /* if xprt is is on a dedicated channel? */ if (sr_rec && sr_rec->id_k) { __warnx(TIRPC_DEBUG_FLAG_REFCNT, "%s:%u %p xp_refs %" PRIu32, __func__, __LINE__, xprt, xprt->xp_refs); evchan_unreg_impl(sr_rec, xprt, SVC_RQST_FLAG_NONE); } else { __warnx(TIRPC_DEBUG_FLAG_REFCNT, "%s:%u %p xp_refs %" PRIu32, __func__, __LINE__, xprt, xprt->xp_refs); (void)svc_rqst_evchan_unreg(__svc_params->ev_u.evchan.id, xprt, SVC_RQST_FLAG_PART_UNLOCK); } /* remove xprt from xprt table */ svc_xprt_clear(xprt, SVC_XPRT_FLAG_LOCKED); /* free state */ xprt->xp_ev = NULL; /* xprt must be unlocked before sr_rec */ mutex_unlock(&xprt->xp_lock); if (sr_rec) mutex_unlock(&sr_rec->mtx); } bool_t __svc_clean_idle2(int timeout, bool_t cleanblock); #ifdef TIRPC_EPOLL static inline void svc_rqst_handle_event(struct svc_rqst_rec *sr_rec, struct epoll_event *ev, uint32_t wakeups) { SVCXPRT *xprt; int code __attribute__ ((unused)); if (ev->data.fd != sr_rec->sv[1]) { xprt = (SVCXPRT *) ev->data.ptr; if (!(atomic_fetch_uint16_t(&xprt->xp_flags) & (SVC_XPRT_FLAG_BLOCKED | SVC_XPRT_FLAG_DESTROYED)) && (xprt->xp_refs > 0)) { /* check for valid xprt. No need for lock; * (idempotent) xp_flags and xp_refs are set atomic. */ __warnx(TIRPC_DEBUG_FLAG_REFCNT | TIRPC_DEBUG_FLAG_SVC_RQST, "%s: %p xp_refs %" PRIu32 " fd %d or ptr %p EPOLL event %d", __func__, xprt, xprt->xp_refs, ev->data.fd, ev->data.ptr, ev->events); /* take extra ref, callout will release */ SVC_REF(xprt, SVC_REF_FLAG_NONE); /* ! LOCKED */ code = xprt->xp_ops->xp_getreq(xprt); __warnx(TIRPC_DEBUG_FLAG_REFCNT, "%s: %p xp_refs %" PRIu32 " post xp_getreq", __func__, xprt, xprt->xp_refs); } /* XXX failsafe idle processing */ if ((wakeups % 1000) == 0) __svc_clean_idle2(__svc_params->idle_timeout, true); } else { /* signalled -- there was a wakeup on ctrl_ev (see * top-of-loop) */ __warnx(TIRPC_DEBUG_FLAG_SVC_RQST, "%s: wakeup fd %d (sr_rec %p)", __func__, sr_rec->sv[1], sr_rec); (void)consume_ev_sig_nb(sr_rec->sv[1]); __warnx(TIRPC_DEBUG_FLAG_SVC_RQST, "%s: after consume sig fd %d (sr_rec %p)", __func__, sr_rec->sv[1], sr_rec); } } static inline int svc_rqst_thrd_run_epoll(struct svc_rqst_rec *sr_rec, uint32_t __attribute__ ((unused)) flags) { struct epoll_event *ev; int ix, code = 0; int timeout_ms = 120 * 1000; /* XXX */ int n_events; static uint32_t wakeups; for (;;) { mutex_lock(&sr_rec->mtx); ++(wakeups); /* check for signals */ if (sr_rec->signals & SVC_RQST_SIGNAL_SHUTDOWN) { mutex_unlock(&sr_rec->mtx); break; } mutex_unlock(&sr_rec->mtx); __warnx(TIRPC_DEBUG_FLAG_SVC_RQST, "%s: before epoll_wait fd %d", __func__, sr_rec->ev_u.epoll.epoll_fd); switch (n_events = epoll_wait(sr_rec->ev_u.epoll.epoll_fd, sr_rec->ev_u.epoll.events, sr_rec->ev_u.epoll.max_events, timeout_ms)) { case -1: if (errno == EINTR) continue; __warnx(TIRPC_DEBUG_FLAG_SVC_RQST, "%s: epoll_wait failed %d", __func__, errno); break; case 0: /* timed out (idle) */ __svc_clean_idle2(__svc_params->idle_timeout, true); continue; default: /* new events */ for (ix = 0; ix < n_events; ++ix) { ev = &(sr_rec->ev_u.epoll.events[ix]); svc_rqst_handle_event(sr_rec, ev, wakeups); } } } return (code); } #endif int svc_rqst_thrd_run(uint32_t chan_id, __attribute__ ((unused)) uint32_t flags) { struct svc_rqst_rec *sr_rec = NULL; struct rbtree_x_part *t; int code = 0; sr_rec = svc_rqst_lookup_chan(chan_id, &t, (SVC_RQST_FLAG_PART_UNLOCK)); if (!sr_rec) { __warnx(TIRPC_DEBUG_FLAG_SVC_RQST, "svc_rqst_thrd_run: unknown chan_id %d", chan_id); code = ENOENT; goto out; } /* serialization model for srec is mutual exclusion on mutation only, * with a secondary state machine to detect inconsistencies (e.g., * trying to unregister a channel when it is active) */ sr_rec->states |= SVC_RQST_STATE_ACTIVE; mutex_unlock(&sr_rec->mtx); /* enter event loop */ switch (sr_rec->ev_type) { #if defined(TIRPC_EPOLL) case SVC_EVENT_EPOLL: code = svc_rqst_thrd_run_epoll(sr_rec, flags); break; #endif default: /* XXX formerly select/fd_set case, now placeholder for new * event systems, reworked select, etc. */ __warnx(TIRPC_DEBUG_FLAG_SVC_RQST, "svc_rqst_thrd_run: unsupported event type"); break; } /* switch */ if (sr_rec) sr_rec_release(sr_rec, SVC_RQST_FLAG_NONE); out: return (code); } int svc_rqst_thrd_signal(uint32_t chan_id, uint32_t flags) { struct svc_rqst_rec *sr_rec; struct rbtree_x_part *t; int code = 0; sr_rec = svc_rqst_lookup_chan(chan_id, &t, SVC_RQST_FLAG_PART_UNLOCK); if (!sr_rec) { code = ENOENT; goto out; } sr_rec->signals |= (flags & SVC_RQST_SIGNAL_MASK); ev_sig(sr_rec->sv[0], flags); /* send wakeup */ mutex_unlock(&sr_rec->mtx); out: if (sr_rec) sr_rec_release(sr_rec, SVC_RQST_FLAG_NONE); return (code); } /* * Activate a transport handle. */ void xprt_register(SVCXPRT *xprt) { int code __attribute__ ((unused)) = 0; /* Create a legacy/global event channel */ if (!(__svc_params->ev_u.evchan.id)) { code = svc_rqst_new_evchan(&(__svc_params->ev_u.evchan.id), NULL /* u_data */ , SVC_RQST_FLAG_CHAN_AFFINITY); } /* and bind xprt to it */ code = svc_rqst_evchan_reg(__svc_params->ev_u.evchan.id, xprt, SVC_RQST_FLAG_CHAN_AFFINITY); } /* xprt_register */ void svc_rqst_shutdown(void) { if (__svc_params->ev_u.evchan.id) { svc_rqst_delete_evchan(__svc_params->ev_u.evchan.id); __svc_params->ev_u.evchan.id = 0; } } <file_sep>/* * Copyright (c) 2012 Linux Box Corporation. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR `AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <config.h> #include <pthread.h> #include <reentrant.h> #include <sys/types.h> #include <sys/poll.h> #include <err.h> #include <errno.h> #include <unistd.h> #include <signal.h> #include <rpc/types.h> #include <rpc/rpc.h> #ifdef PORTMAP #include <rpc/pmap_clnt.h> #endif /* PORTMAP */ #include "rpc_com.h" #include <rpc/svc.h> #include <misc/rbtree_x.h> #include "clnt_internal.h" #include "rpc_dplx_internal.h" /* public */ void rpc_dplx_slxi(SVCXPRT *xprt, const char *func, int line) { struct rpc_dplx_rec *rec = (struct rpc_dplx_rec *)xprt->xp_p5; rpc_dplx_lock_t *lk = &rec->send.lock; mutex_lock(&lk->we.mtx); if (__debug_flag(TIRPC_DEBUG_FLAG_LOCK)) { lk->locktrace.func = (char *)func; lk->locktrace.line = line; } } void rpc_dplx_sux(SVCXPRT *xprt) { struct rpc_dplx_rec *rec = (struct rpc_dplx_rec *)xprt->xp_p5; mutex_unlock(&rec->send.lock.we.mtx); } void rpc_dplx_rlxi(SVCXPRT *xprt, const char *func, int line) { struct rpc_dplx_rec *rec = (struct rpc_dplx_rec *)xprt->xp_p5; rpc_dplx_lock_t *lk = &rec->recv.lock; mutex_lock(&lk->we.mtx); if (__debug_flag(TIRPC_DEBUG_FLAG_LOCK)) { lk->locktrace.func = (char *)func; lk->locktrace.line = line; } } void rpc_dplx_rux(SVCXPRT *xprt) { struct rpc_dplx_rec *rec = (struct rpc_dplx_rec *)xprt->xp_p5; mutex_unlock(&rec->recv.lock.we.mtx); } void rpc_dplx_slci(CLIENT *clnt, const char *func, int line) { struct rpc_dplx_rec *rec = (struct rpc_dplx_rec *)clnt->cl_p2; rpc_dplx_lock_t *lk = &rec->send.lock; mutex_lock(&lk->we.mtx); if (__debug_flag(TIRPC_DEBUG_FLAG_LOCK)) { lk->locktrace.func = (char *)func; lk->locktrace.line = line; } } void rpc_dplx_suc(CLIENT *clnt) { struct rpc_dplx_rec *rec = (struct rpc_dplx_rec *)clnt->cl_p2; mutex_unlock(&rec->send.lock.we.mtx); } void rpc_dplx_rlci(CLIENT *clnt, const char *func, int line) { struct rpc_dplx_rec *rec = (struct rpc_dplx_rec *)clnt->cl_p2; rpc_dplx_lock_t *lk = &rec->recv.lock; mutex_lock(&lk->we.mtx); if (__debug_flag(TIRPC_DEBUG_FLAG_LOCK)) { lk->locktrace.func = (char *)func; lk->locktrace.line = line; } } void rpc_dplx_ruc(CLIENT *clnt) { struct rpc_dplx_rec *rec = (struct rpc_dplx_rec *)clnt->cl_p2; mutex_unlock(&rec->recv.lock.we.mtx); } /* private */ #define RPC_DPLX_PARTITIONS 17 static bool initialized = false; static struct rpc_dplx_rec_set rpc_dplx_rec_set = { MUTEX_INITIALIZER, /* clnt_fd_lock */ { 0, /* npart */ RBT_X_FLAG_NONE /* flags */ , 0, /* cachesz */ NULL /* tree */ } /* xt */ }; static inline int rpc_dplx_cmpf(const struct opr_rbtree_node *lhs, const struct opr_rbtree_node *rhs) { struct rpc_dplx_rec *lk, *rk; lk = opr_containerof(lhs, struct rpc_dplx_rec, node_k); rk = opr_containerof(rhs, struct rpc_dplx_rec, node_k); if (lk->fd_k < rk->fd_k) return (-1); if (lk->fd_k == rk->fd_k) return (0); return (1); } void rpc_dplx_init() { int code = 0; /* XXX */ mutex_lock(&rpc_dplx_rec_set.clnt_fd_lock); if (initialized) goto unlock; /* one of advantages of this RBT is convenience of external * iteration, we'll go to that shortly */ code = rbtx_init(&rpc_dplx_rec_set.xt, rpc_dplx_cmpf /* NULL (inline) */ , RPC_DPLX_PARTITIONS, RBT_X_FLAG_ALLOC); if (code) __warnx(TIRPC_DEBUG_FLAG_LOCK, "rpc_dplx_init: rbtx_init failed"); initialized = true; unlock: mutex_unlock(&rpc_dplx_rec_set.clnt_fd_lock); } #define cond_init_rpc_dplx() { \ do { \ if (!initialized) \ rpc_dplx_init(); \ } while (0); \ } /* CLNT/SVCXPRT structures keep a reference to their associated rpc_dplx_rec * structures in private data. this way we can make the lock/unlock ops * inline, and the amortized cost of this change for locks is 0. */ static inline struct rpc_dplx_rec * alloc_dplx_rec(void) { struct rpc_dplx_rec *rec = mem_zalloc(sizeof(struct rpc_dplx_rec)); mutex_init(&rec->locktrace.mtx, NULL); /* send channel */ rpc_dplx_lock_init(&rec->send.lock); /* recv channel */ rpc_dplx_lock_init(&rec->recv.lock); return (rec); } static inline void free_dplx_rec(struct rpc_dplx_rec *rec) { mutex_destroy(&rec->locktrace.mtx); rpc_dplx_lock_destroy(&rec->send.lock); rpc_dplx_lock_destroy(&rec->recv.lock); mem_free(rec, sizeof(struct rpc_dplx_rec)); } struct rpc_dplx_rec * rpc_dplx_lookup_rec(int fd, uint32_t iflags) { struct rbtree_x_part *t; struct rpc_dplx_rec rk, *rec = NULL; struct opr_rbtree_node *nv; cond_init_rpc_dplx(); rk.fd_k = fd; t = rbtx_partition_of_scalar(&(rpc_dplx_rec_set.xt), fd); rwlock_rdlock(&t->lock); nv = opr_rbtree_lookup(&t->t, &rk.node_k); /* XXX rework lock+insert case, so that new entries are inserted * locked, and t->lock critical section is reduced */ if (!nv) { rwlock_unlock(&t->lock); rwlock_wrlock(&t->lock); nv = opr_rbtree_lookup(&t->t, &rk.node_k); if (!nv) { rec = alloc_dplx_rec(); rec->fd_k = fd; if (opr_rbtree_insert(&t->t, &rec->node_k)) { /* cant happen */ __warnx(TIRPC_DEBUG_FLAG_LOCK, "%s: collision inserting in locked rbtree partition", __func__); free_dplx_rec(rec); rec = NULL; goto unlock; } } else { /* raced */ rec = opr_containerof(nv, struct rpc_dplx_rec, node_k); } } else { rec = opr_containerof(nv, struct rpc_dplx_rec, node_k); } rpc_dplx_ref(rec, (iflags & RPC_DPLX_LKP_IFLAG_LOCKREC) ? RPC_DPLX_FLAG_LOCK : RPC_DPLX_FLAG_NONE); unlock: rwlock_unlock(&t->lock); return (rec); } void rpc_dplx_slfi(int fd, const char *func, int line) { struct rpc_dplx_rec *rec = rpc_dplx_lookup_rec(fd, RPC_DPLX_FLAG_NONE); rpc_dplx_lock_t *lk = &rec->send.lock; mutex_lock(&lk->we.mtx); if (__debug_flag(TIRPC_DEBUG_FLAG_LOCK)) { lk->locktrace.func = (char *)func; lk->locktrace.line = line; } } void rpc_dplx_suf(int fd) { struct rpc_dplx_rec *rec = rpc_dplx_lookup_rec(fd, RPC_DPLX_FLAG_NONE); /* assert: initialized */ mutex_unlock(&rec->send.lock.we.mtx); } void rpc_dplx_rlfi(int fd, const char *func, int line) { struct rpc_dplx_rec *rec = rpc_dplx_lookup_rec(fd, RPC_DPLX_FLAG_NONE); rpc_dplx_lock_t *lk = &rec->recv.lock; mutex_lock(&lk->we.mtx); if (__debug_flag(TIRPC_DEBUG_FLAG_LOCK)) { lk->locktrace.func = (char *)func; lk->locktrace.line = line; } } void rpc_dplx_ruf(int fd) { struct rpc_dplx_rec *rec = rpc_dplx_lookup_rec(fd, RPC_DPLX_FLAG_NONE); /* assert: initialized */ mutex_unlock(&rec->recv.lock.we.mtx); } int32_t rpc_dplx_unref(struct rpc_dplx_rec *rec, u_int flags) { struct rbtree_x_part *t; struct opr_rbtree_node *nv; int32_t refcnt; if (!(flags & RPC_DPLX_FLAG_LOCKED)) REC_LOCK(rec); refcnt = --(rec->refcnt); __warnx(TIRPC_DEBUG_FLAG_REFCNT, "%s: postunref %p rec->refcnt %u", __func__, rec, refcnt); if (rec->refcnt == 0) { t = rbtx_partition_of_scalar(&rpc_dplx_rec_set.xt, rec->fd_k); if (rec->hdl.xd) { rec->hdl.xd->refcnt--; rec->hdl.xd->rec = NULL; } REC_UNLOCK(rec); rwlock_wrlock(&t->lock); nv = opr_rbtree_lookup(&t->t, &rec->node_k); rec = NULL; if (nv) { rec = opr_containerof(nv, struct rpc_dplx_rec, node_k); REC_LOCK(rec); if (rec->refcnt == 0) { (void)opr_rbtree_remove(&t->t, &rec->node_k); REC_UNLOCK(rec); __warnx(TIRPC_DEBUG_FLAG_REFCNT, "%s: free rec %p rec->refcnt %u", __func__, rec, refcnt); free_dplx_rec(rec); rec = NULL; } else { refcnt = rec->refcnt; } } rwlock_unlock(&t->lock); } if (rec) { if ((!(flags & RPC_DPLX_FLAG_LOCKED)) || (flags & RPC_DPLX_FLAG_UNLOCK)) REC_UNLOCK(rec); } return (refcnt); } void rpc_dplx_shutdown() { struct rbtree_x_part *t = NULL; struct opr_rbtree_node *n; struct rpc_dplx_rec *rec = NULL; int p_ix; cond_init_rpc_dplx(); /* concurrent, restartable iteration over t */ p_ix = 0; while (p_ix < RPC_DPLX_PARTITIONS) { t = &rpc_dplx_rec_set.xt.tree[p_ix]; rwlock_wrlock(&t->lock); /* t WLOCKED */ n = opr_rbtree_first(&t->t); while (n != NULL) { rec = opr_containerof(n, struct rpc_dplx_rec, node_k); opr_rbtree_remove(&t->t, &rec->node_k); free_dplx_rec(rec); n = opr_rbtree_first(&t->t); } /* curr partition */ rwlock_unlock(&t->lock); /* t !LOCKED */ rwlock_destroy(&t->lock); p_ix++; } /* RPC_DPLX_PARTITIONS */ /* free tree */ mem_free(rpc_dplx_rec_set.xt.tree, RPC_DPLX_PARTITIONS * sizeof(struct rbtree_x_part)); /* set initialized = false? */ } <file_sep>/* * Copyright (c) 2013 Linux Box Corporation. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR `AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef WAIT_QUEUE_H #define WAIT_QUEUE_H #include <errno.h> #include <pthread.h> #include <stdint.h> #include <stdbool.h> #include <misc/queue.h> #include <reentrant.h> typedef struct wait_entry { mutex_t mtx; cond_t cv; } wait_entry_t; #define Wqe_LFlag_None 0x0000 #define Wqe_LFlag_WaitSync 0x0001 #define Wqe_LFlag_SyncDone 0x0002 /* thread wait queue */ typedef struct wait_q_entry { uint32_t flags; uint32_t waiters; wait_entry_t lwe; /* left */ wait_entry_t rwe; /* right */ TAILQ_HEAD(we_tailq, waiter) waitq; } wait_q_entry_t; static inline void init_wait_entry(wait_entry_t *we) { mutex_init(&we->mtx, NULL); pthread_cond_init(&we->cv, NULL); } static inline void destroy_wait_entry(wait_entry_t *we) { mutex_destroy(&we->mtx); cond_destroy(&we->cv); } static inline void init_wait_q_entry(wait_q_entry_t *wqe) { TAILQ_INIT(&wqe->waitq); init_wait_entry(&wqe->lwe); init_wait_entry(&wqe->rwe); } static inline void thread_delay_ms(unsigned long ms) { struct timespec then = { .tv_sec = ms / 1000, .tv_nsec = ms % 1000000UL }; nanosleep(&then, NULL); } #endif /* WAIT_QUEUE_H */ <file_sep>/* * Copyright (c) 2012 Linux Box Corporation. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR `AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef RPC_DPLX_H #define RPC_DPLX_H /* SVCXPRT variants */ /* slx: send lock xprt */ #define rpc_dplx_slx(xprt) \ rpc_dplx_slxi(xprt, __func__, __LINE__) /* slxi: send lock xprt impl */ void rpc_dplx_slxi(SVCXPRT *xprt, const char *file, int line); /* sux: send unlock xprt */ void rpc_dplx_sux(SVCXPRT *xprt); /* rlx: recv lock xprt */ #define rpc_dplx_rlx(xprt) \ rpc_dplx_rlxi(xprt, __func__, __LINE__) /* rlxi: recv lock xprt impl */ void rpc_dplx_rlxi(SVCXPRT *xprt, const char *file, int line); /* rux: recv unlock xprt */ void rpc_dplx_rux(SVCXPRT *xprt); /* CLIENT variants */ /* slc: send lock clnt */ #define rpc_dplx_slc(clnt) \ rpc_dplx_slci(clnt, __func__, __LINE__) /* slci: send lock clnt impl */ void rpc_dplx_slci(CLIENT *clnt, const char *file, int line); /* suc: send unlock clnt */ void rpc_dplx_suc(CLIENT *clnt); /* rlc: recv lock clnt */ #define rpc_dplx_rlc(clnt) \ rpc_dplx_rlci(clnt, __func__, __LINE__) /* rlci: recv lock clnt impl */ void rpc_dplx_rlci(CLIENT *clnt, const char *file, int line); /* ruc: recv unlock clnt */ void rpc_dplx_ruc(CLIENT *client); /* fd variants--these interfaces should be used only when NO OTHER * APPROACH COULD WORK. Please. */ /* slf: send lock fd */ #define rpc_dplx_slf(fd) \ rpc_dplx_slfi(fd, __func__, __LINE__) /* slfi: send lock fd impl */ void rpc_dplx_slfi(int fd, const char *file, int line); /* suf: send unlock fd */ void rpc_dplx_suf(int fd); /* rlf: recv lock fd */ #define rpc_dplx_rlf(fd) \ rpc_dplx_rlfi(fd, __func__, __LINE__) /* rlfi: recv lock fd impl */ void rpc_dplx_rlfi(int fd, const char *file, int line); /* ruf: recv unlock fd */ void rpc_dplx_ruf(int fd); #endif /* RPC_DPLX_H */ <file_sep>/* * vim:expandtab:shiftwidth=8:tabstop=8: */ /** * \file fsal_nfsv4_macros.h * \author $Author: deniel $ * \date 06/05/2007 * \version $Revision$ * \brief Usefull macros to manage NFSv4 call from FSAL_PROXY * * */ #ifndef _FSAL_NFSV4_MACROS_H #define _FSAL_NFSV4_MACROS_H #define MAXNAMLEN 256 typedef union { nfs_cookie4 data ; char pad[4]; } proxyfsal_cookie_t; typedef struct fsal_proxy_internal_fattr_readdir__ { fattr4_type type; fattr4_change change_time; fattr4_size size; fattr4_fsid fsid; fattr4_filehandle filehandle; fattr4_fileid fileid; fattr4_mode mode; fattr4_numlinks numlinks; fattr4_owner owner; /* Needs to points to a string */ fattr4_owner_group owner_group; /* Needs to points to a string */ fattr4_space_used space_used; fattr4_time_access time_access; fattr4_time_metadata time_metadata; fattr4_time_modify time_modify; fattr4_rawdev rawdev; char padowner[MAXNAMLEN]; char padgroup[MAXNAMLEN]; char padfh[NFS4_FHSIZE]; } fsal_proxy_internal_fattr_readdir_t; #define TIMEOUTRPC {2, 0} #define PRINT_HANDLE( tag, handle ) \ do { \ if(isFullDebug(COMPONENT_FSAL)) \ { \ char outstr[1024] ; \ snprintHandle(outstr, 1024, handle) ; \ LogFullDebug(COMPONENT_FSAL, "============> %s : handle=%s\n", tag, outstr ) ; \ } \ } while( 0 ) /* Free a compound */ #define COMPOUNDV4_ARG_FREE \ do {gsh_free(argcompound.argarray_val);} while( 0 ) /* OP specific macros */ #define COMPOUNDV4_ARG_ADD_OP_PUTROOTFH( argcompound ) \ do { \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].argop = OP_PUTROOTFH ; \ argcompound.argarray.argarray_len += 1 ; \ } while( 0 ) #define COMPOUNDV4_ARG_ADD_OP_OPEN_CONFIRM( argcompound, __openseqid, __other, __seqid ) \ do { \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].argop = OP_OPEN_CONFIRM ; \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].nfs_argop4_u.opopen_confirm.seqid = __seqid ; \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].nfs_argop4_u.opopen_confirm.open_stateid.seqid = __openseqid ; \ memcpy( argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].nfs_argop4_u.opopen_confirm.open_stateid.other, __other, 12 ) ; \ argcompound.argarray.argarray_len += 1 ; \ } while( 0 ) #define COMPOUNDV4_ARG_ADD_OP_OPEN_NOCREATE( argcompound, __seqid, inclientid, inaccess, inname, __owner_val, __owner_len ) \ do { \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].argop = OP_OPEN ; \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].nfs_argop4_u.opopen.seqid = __seqid ; \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].nfs_argop4_u.opopen.share_access = OPEN4_SHARE_ACCESS_BOTH ; \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].nfs_argop4_u.opopen.share_deny = OPEN4_SHARE_DENY_NONE ; \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].nfs_argop4_u.opopen.owner.clientid = inclientid ; \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].nfs_argop4_u.opopen.owner.owner.owner_len = __owner_len ; \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].nfs_argop4_u.opopen.owner.owner.owner_val = __owner_val ; \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].nfs_argop4_u.opopen.openhow.opentype = OPEN4_NOCREATE ; \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].nfs_argop4_u.opopen.claim.claim = CLAIM_NULL ; \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].nfs_argop4_u.opopen.claim.open_claim4_u.file = inname ; \ argcompound.argarray.argarray_len += 1 ; \ } while( 0 ) #define COMPOUNDV4_ARG_ADD_OP_CLOSE( argcompound, __stateid ) \ do { \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].argop = OP_CLOSE ; \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].nfs_argop4_u.opclose.seqid = __stateid.seqid +1 ; \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].nfs_argop4_u.opclose.open_stateid.seqid = __stateid.seqid ; \ memcpy( argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].nfs_argop4_u.opclose.open_stateid.other, __stateid.other, 12 ) ; \ argcompound.argarray.argarray_len += 1 ; \ } while( 0 ) #define COMPOUNDV4_ARG_ADD_OP_GETATTR( argcompound, bitmap ) \ do { \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].argop = OP_GETATTR ; \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].nfs_argop4_u.opgetattr.attr_request = bitmap ; \ argcompound.argarray.argarray_len += 1 ; \ } while( 0 ) #define COMPOUNDV4_ARG_ADD_OP_SETATTR( argcompound, inattr ) \ do { \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].argop = OP_SETATTR ; \ memset(&argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].nfs_argop4_u.opsetattr.stateid,0,sizeof(stateid4)); \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].nfs_argop4_u.opsetattr.obj_attributes = inattr ; \ argcompound.argarray.argarray_len += 1 ; \ } while( 0 ) #define COMPOUNDV4_ARG_ADD_OP_GETFH( argcompound ) \ do { \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].argop = OP_GETFH ; \ argcompound.argarray.argarray_len += 1 ; \ } while( 0 ) #define COMPOUNDV4_ARG_ADD_OP_PUTFH( argcompound, nfs4fh ) \ do { \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].argop = OP_PUTFH ; \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].nfs_argop4_u.opputfh.object = nfs4fh ; \ argcompound.argarray.argarray_len += 1 ; \ } while( 0 ) #define COMPOUNDV4_ARG_ADD_OP_LOOKUP( argcompound, name ) \ do { \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].argop = OP_LOOKUP ; \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].nfs_argop4_u.oplookup.objname = name ; \ argcompound.argarray.argarray_len += 1 ; \ } while ( 0 ) #define COMPOUNDV4_ARG_ADD_OP_LOOKUPP( argcompound ) \ do { \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].argop = OP_LOOKUPP ; \ argcompound.argarray.argarray_len += 1 ; \ } while ( 0 ) #define COMPOUNDV4_ARG_ADD_OP_SETCLIENTID( argcompound, inclient, incallback ) \ do { \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].argop = OP_SETCLIENTID ; \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].nfs_argop4_u.opsetclientid.client = inclient ; \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].nfs_argop4_u.opsetclientid.callback = incallback ; \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].nfs_argop4_u.opsetclientid.callback_ident = 0 ; \ argcompound.argarray.argarray_len += 1 ; \ } while ( 0 ) #define COMPOUNDV4_ARG_ADD_OP_SETCLIENTID_CONFIRM( argcompound, inclientid, inverifier ) \ do { \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].argop = OP_SETCLIENTID_CONFIRM ; \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].nfs_argop4_u.opsetclientid_confirm.clientid = inclientid ; \ strncpy( argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].nfs_argop4_u.opsetclientid_confirm.setclientid_confirm, inverifier, NFS4_VERIFIER_SIZE ) ; \ argcompound.argarray.argarray_len += 1 ; \ } while ( 0 ) #define COMPOUNDV4_ARG_ADD_OP_ACCESS( argcompound, inaccessflag ) \ do { \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].argop = OP_ACCESS ; \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].nfs_argop4_u.opaccess.access = inaccessflag ; \ argcompound.argarray.argarray_len += 1 ; \ } while ( 0 ) #define COMPOUNDV4_ARG_ADD_OP_READDIR( argcompound, incookie, innbentry, inverifier, inbitmap ) \ do { \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].argop = OP_READDIR ; \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].nfs_argop4_u.opreaddir.cookie = incookie ; \ memcpy( argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].nfs_argop4_u.opreaddir.cookieverf, inverifier, NFS4_VERIFIER_SIZE ) ; \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].nfs_argop4_u.opreaddir.dircount = innbentry*sizeof( entry4 ) ; \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].nfs_argop4_u.opreaddir.dircount = 2048 ; \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].nfs_argop4_u.opreaddir.maxcount = innbentry*sizeof( entry4 ) ; \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].nfs_argop4_u.opreaddir.maxcount = 4096 ; \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].nfs_argop4_u.opreaddir.attr_request = inbitmap ; \ argcompound.argarray.argarray_len += 1 ; \ } while ( 0 ) #define COMPOUNDV4_ARG_ADD_OP_OPEN_CREATE( argcompound, inname, inattrs, inclientid, __owner_val, __owner_len ) \ do { \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].argop = OP_OPEN ; \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].nfs_argop4_u.opopen.seqid = 0 ; \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].nfs_argop4_u.opopen.share_access = OPEN4_SHARE_ACCESS_BOTH ; \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].nfs_argop4_u.opopen.share_deny = OPEN4_SHARE_DENY_NONE ; \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].nfs_argop4_u.opopen.owner.clientid = inclientid ; \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].nfs_argop4_u.opopen.owner.owner.owner_len = __owner_len ; \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].nfs_argop4_u.opopen.owner.owner.owner_val = __owner_val ; \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].nfs_argop4_u.opopen.openhow.opentype = OPEN4_CREATE ; \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].nfs_argop4_u.opopen.openhow.openflag4_u.how.mode = GUARDED4 ; \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].nfs_argop4_u.opopen.openhow.openflag4_u.how.createhow4_u.createattrs = inattrs ; \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].nfs_argop4_u.opopen.claim.claim = CLAIM_NULL ; \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].nfs_argop4_u.opopen.claim.open_claim4_u.file = inname ; \ argcompound.argarray.argarray_len += 1 ; \ } while ( 0 ) #define COMPOUNDV4_ARG_ADD_OP_MKDIR( argcompound, inname, inattrs ) \ do { \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].argop = OP_CREATE ; \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].nfs_argop4_u.opcreate.objtype.type = NF4DIR ; \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].nfs_argop4_u.opcreate.objname = inname ; \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].nfs_argop4_u.opcreate.createattrs = inattrs ; \ argcompound.argarray.argarray_len += 1 ; \ } while ( 0 ) #define COMPOUNDV4_ARG_ADD_OP_SYMLINK( argcompound, inname, incontent, inattrs ) \ do { \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].argop = OP_CREATE ; \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].nfs_argop4_u.opcreate.objtype.type = NF4LNK ; \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].nfs_argop4_u.opcreate.objtype.createtype4_u.linkdata = incontent ; \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].nfs_argop4_u.opcreate.objname = inname ; \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].nfs_argop4_u.opcreate.createattrs = inattrs ; \ argcompound.argarray.argarray_len += 1 ; \ } while ( 0 ) #define COMPOUNDV4_ARG_ADD_OP_LINK( argcompound, inname ) \ do { \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].argop = OP_LINK ; \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].nfs_argop4_u.oplink.newname = inname ; \ argcompound.argarray.argarray_len += 1 ; \ } while ( 0 ) #define COMPOUNDV4_ARG_ADD_OP_REMOVE( argcompound, inname ) \ do { \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].argop = OP_REMOVE ; \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].nfs_argop4_u.opremove.target = inname ; \ argcompound.argarray.argarray_len += 1 ; \ } while ( 0 ) #define COMPOUNDV4_ARG_ADD_OP_RENAME( argcompound, inoldname, innewname ) \ do { \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].argop = OP_RENAME ; \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].nfs_argop4_u.oprename.oldname = inoldname ; \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].nfs_argop4_u.oprename.newname = innewname ; \ argcompound.argarray.argarray_len += 1 ; \ } while ( 0 ) #define COMPOUNDV4_ARG_ADD_OP_READLINK( argcompound ) \ do { \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].argop = OP_READLINK ; \ argcompound.argarray.argarray_len += 1 ; \ } while ( 0 ) #define COMPOUNDV4_ARG_ADD_OP_SAVEFH( argcompound ) \ do { \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].argop = OP_SAVEFH ; \ argcompound.argarray.argarray_len += 1 ; \ } while ( 0 ) #define COMPOUNDV4_ARG_ADD_OP_RESTOREFH( argcompound ) \ do { \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].argop = OP_RESTOREFH ; \ argcompound.argarray.argarray_len += 1 ; \ } while ( 0 ) #define COMPOUNDV4_ARG_ADD_OP_READ( argcompound, instateid, inoffset, incount ) \ do { \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].argop = OP_READ ; \ memcpy( &argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].nfs_argop4_u.opread.stateid, instateid, sizeof( stateid4 ) ) ; \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].nfs_argop4_u.opread.offset = inoffset ; \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].nfs_argop4_u.opread.count = incount ; \ argcompound.argarray.argarray_len += 1 ; \ } while ( 0 ) #define COMPOUNDV4_ARG_ADD_OP_WRITE( argcompound, instateid, inoffset, indatabuffval, indatabufflen ) \ do { \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].argop = OP_WRITE ; \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].nfs_argop4_u.opwrite.stable= DATA_SYNC4 ; \ memcpy( &argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].nfs_argop4_u.opwrite.stateid, instateid, sizeof( stateid4 ) ) ; \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].nfs_argop4_u.opwrite.offset = inoffset ; \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].nfs_argop4_u.opwrite.data.data_val = indatabuffval ; \ argcompound.argarray.argarray_val[argcompound.argarray.argarray_len].nfs_argop4_u.opwrite.data.data_len = indatabufflen ; \ argcompound.argarray.argarray_len += 1 ; \ } while ( 0 ) #define COMPOUNDV4_EXECUTE( pcontext, argcompound, rescompound, rc ) \ do { \ int __renew_rc = 0 ; \ rc = -1 ; \ do { \ if( __renew_rc == 0 ) \ { \ if( FSAL_proxy_change_user( pcontext ) == NULL ) break ; \ if( ( rc = clnt_call( pcontext->rpc_client, NFSPROC4_COMPOUND, \ (xdrproc_t)xdr_COMPOUND4args, (caddr_t)&argcompound, \ (xdrproc_t)xdr_COMPOUND4res, (caddr_t)&rescompound, \ timeout ) ) == RPC_SUCCESS ) \ break ; \ } \ LogEvent(COMPONENT_FSAL, "Reconnecting to the remote server.." ) ; \ pthread_mutex_lock( &pcontext->lock ) ; \ __renew_rc = fsal_internal_ClientReconnect( pcontext ) ; \ pthread_mutex_unlock( &pcontext->lock ) ; \ if (__renew_rc) { \ LogEvent(COMPONENT_FSAL, "Cannot reconnect, will sleep for %d seconds", \ pcontext->retry_sleeptime ) ; \ sleep( pcontext->retry_sleeptime ) ; \ } \ } while( 1 ) ; \ } while( 0 ) #define COMPOUNDV4_EXECUTE_SIMPLE( pcontext, argcompound, rescompound ) \ clnt_call( pcontext->rpc_client, NFSPROC4_COMPOUND, \ (xdrproc_t)xdr_COMPOUND4args, (caddr_t)&argcompound, \ (xdrproc_t)xdr_COMPOUND4res, (caddr_t)&rescompound, \ timeout ) #endif /* _FSAL_NFSV4_MACROS_H */ <file_sep>/* * Copyright (c) 2012-2014 CEA * <NAME> <<EMAIL>> * * DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE * Version 2, December 2004 * * Everyone is permitted to copy and distribute verbatim or modified * copies of this license document, and changing it is allowed as long * as the name is changed. * * DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE * TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION * * 0. You just DO WHAT THE FUCK YOU WANT TO. */ #include <rpc/rpc.h> #include <rpc/clnt.h> #include <rpc/xdr.h> #include <rpc/auth.h> #include <arpa/inet.h> #include <netdb.h> #include <unistd.h> #include <errno.h> #include <mooshika.h> #include "rpc/svc.h" #include "nfsv40.h" #include "nfs4.h" #include "fsal_nfsv4_macros.h" extern SVCXPRT *svc_msk_create(msk_trans_t*, u_int, void (*)(void*), void*); #define PROGNUM 100003 #define NFS_V4 4 #define SENDSIZE 32768 #define RECVSIZE 32768 #define CREDITS 20 inline void die(char* str, int i) { printf("%s: %s (%d)\n", str, strerror(i), i); exit(1); } int main() { int rc; SVCXPRT *rpc_svc; msk_trans_t *trans; msk_trans_attr_t attr; memset(&attr, 0, sizeof(msk_trans_attr_t)); attr.server = 10; attr.rq_depth = CREDITS; attr.sq_depth = CREDITS; attr.max_send_sge = 4; attr.port = "20049"; attr.node = "0.0.0.0"; attr.debug = 1; if (msk_init(&trans, &attr)) die("couldn't init trans", ENOMEM); msk_bind_server(trans); trans = msk_accept_one(trans); rpc_svc = svc_msk_create(trans, CREDITS, NULL, NULL); if (!rpc_svc) die("no rpc client", errno); struct rpc_msg rply; struct svc_req req; FILE *logfd = fopen("/tmp/nfsrdma_log", "w+"); memset(&req, 0, sizeof(req)); memset(&rply, 0, sizeof(rply)); rc = rpc_svc->xp_ops->xp_recv(rpc_svc, &req); printf("Got something (status %d)\n", rc); fwrite((char*)(&req.rq_msg), sizeof(req.rq_msg), sizeof(char), logfd); fwrite("\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11", 0x10, sizeof(char), logfd); fflush(logfd); rply.rm_xid = req.rq_xid; rply.rm_direction=REPLY; rply.rm_reply.rp_stat = MSG_DENIED; rply.rm_flags = RPC_MSG_FLAG_NONE; rply.rjcted_rply.rj_stat = AUTH_ERROR; rply.rjcted_rply.rj_why = AUTH_FAILED; rpc_svc->xp_ops->xp_reply(rpc_svc, &req, &rply); msk_destroy_trans(&trans); return 0; } <file_sep>/* * Copyright (c) 2009, Sun Microsystems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - Neither the name of Sun Microsystems, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* * clnt_tcp.c, Implements a TCP/IP based, client side RPC. * * Copyright (C) 1984, Sun Microsystems, Inc. * * TCP based RPC supports 'batched calls'. * A sequence of calls may be batched-up in a send buffer. The rpc call * return immediately to the client even though the call was not necessarily * sent. The batching occurs if the results' xdr routine is NULL (0) AND * the rpc timeout value is zero (see clnt.h, rpc). * * Clients should NOT casually batch calls that in fact return results; that is, * the server side should be aware that a call is batched and not produce any * return message. Batched calls that produce many result messages can * deadlock (netlock) the client and the server.... * * Now go hang yourself. [Ouch, that was intemperate.] */ #include <config.h> #include <sys/types.h> #include <sys/poll.h> #include <sys/syslog.h> #include <sys/un.h> #include <sys/uio.h> #include <sys/socket.h> #include <misc/socket.h> #include <arpa/inet.h> #include <assert.h> #include <err.h> #include <errno.h> #include <netdb.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <signal.h> #include <rpc/types.h> #include <misc/portable.h> #include <reentrant.h> #include <rpc/rpc.h> #include "rpc_com.h" #include "clnt_internal.h" #include "rpc_dplx_internal.h" #include "rpc_ctx.h" #include <rpc/svc_rqst.h> #include <rpc/xdr_inrec.h> #include <rpc/xdr_ioq.h> #include "svc_ioq.h" static enum clnt_stat clnt_vc_call(CLIENT *, AUTH *, rpcproc_t, xdrproc_t, void *, xdrproc_t, void *, struct timeval); static void clnt_vc_geterr(CLIENT *, struct rpc_err *); static bool clnt_vc_freeres(CLIENT *, xdrproc_t, void *); static void clnt_vc_abort(CLIENT *); static bool clnt_vc_control(CLIENT *, u_int, void *); static bool clnt_vc_ref(CLIENT *, u_int); static void clnt_vc_release(CLIENT *, u_int); static void clnt_vc_destroy(CLIENT *); static struct clnt_ops *clnt_vc_ops(void); static bool time_not_ok(struct timeval *); int generic_read_vc(XDR *, void *, void *, int); int generic_write_vc(XDR *, void *, void *, int); #include "clnt_internal.h" #include "svc_internal.h" /* * This machinery implements per-fd locks for MT-safety. It is not * sufficient to do per-CLIENT handle locks for MT-safety because a * user may create more than one CLIENT handle with the same fd behind * it. Therfore, we allocate an array of flags (vc_fd_locks), protected * by the clnt_fd_lock mutex, and an array (vc_cv) of condition variables * similarly protected. Vc_fd_lock[fd] == 1 => a call is active on some * CLIENT handle created for that fd. (Historical interest only.) * * The current implementation holds locks across the entire RPC and reply. * Yes, this is silly, and as soon as this code is proven to work, this * should be the first thing fixed. One step at a time. (Fixing this.) * * The ONC RPC record marking (RM) standard (RFC 5531, s. 11) does not * provide for mixed call and reply fragment reassembly, so writes to the * bytestream with MUST be record-wise atomic. It appears that an * implementation may interleave call and reply messages on distinct * conversations. This is not incompatible with holding a transport * exclusive locked across a full call and reply, bud does require new * control tranfers and delayed decoding support in the transport. For * duplex channels, full coordination is required between client and * server tranpsorts sharing an underlying bytestream (Matt). */ static const char clnt_vc_errstr[] = "%s : %s"; static const char clnt_vc_str[] = "clnt_vc_ncreate"; static const char __no_mem_str[] = "out of memory"; /* * Create a client handle for a connection. * Default options are set, which the user can change using clnt_control()'s. * The rpc/vc package does buffering similar to stdio, so the client * must pick send and receive buffer sizes, 0 => use the default. * NB: fd is copied into a private area. * NB: The rpch->cl_auth is set null authentication. Caller may wish to * set this something more useful. * * fd should be an open socket */ CLIENT * clnt_vc_ncreate(int fd, /* open file descriptor */ const struct netbuf *raddr, /* servers address */ const rpcprog_t prog, /* program number */ const rpcvers_t vers, /* version number */ u_int sendsz, /* buffer recv size */ u_int recvsz /* buffer send size */) { return (clnt_vc_ncreate2 (fd, raddr, prog, vers, sendsz, recvsz, CLNT_CREATE_FLAG_CONNECT)); } CLIENT * clnt_vc_ncreate2(int fd, /* open file descriptor */ const struct netbuf *raddr, /* servers address */ const rpcprog_t prog, /* program number */ const rpcvers_t vers, /* version number */ u_int sendsz, /* buffer send size */ u_int recvsz, /* buffer recv size */ u_int flags) { CLIENT *clnt = NULL; struct rpc_dplx_rec *rec = NULL; struct x_vc_data *xd = NULL; struct ct_data *ct = NULL; struct ct_serialized *cs = NULL; struct rpc_msg call_msg; sigset_t mask, newmask; struct __rpc_sockinfo si; struct sockaddr_storage ss; XDR ct_xdrs[1]; /* temp XDR stream */ socklen_t slen; sigfillset(&newmask); thr_sigsetmask(SIG_SETMASK, &newmask, &mask); if (flags & CLNT_CREATE_FLAG_CONNECT) { slen = sizeof(ss); if (getpeername(fd, (struct sockaddr *)&ss, &slen) < 0) { if (errno != ENOTCONN) { rpc_createerr.cf_stat = RPC_SYSTEMERROR; rpc_createerr.cf_error.re_errno = errno; goto err; } if (connect (fd, (struct sockaddr *)raddr->buf, raddr->len) < 0) { rpc_createerr.cf_stat = RPC_SYSTEMERROR; rpc_createerr.cf_error.re_errno = errno; goto err; } } } /* connect */ if (!__rpc_fd2sockinfo(fd, &si)) goto err; /* atomically find or create shared fd state */ rec = rpc_dplx_lookup_rec(fd, RPC_DPLX_LKP_IFLAG_LOCKREC); if (!rec) { __warnx(TIRPC_DEBUG_FLAG_SVC_VC, "clnt_vc_ncreate2: rpc_dplx_lookup_rec failed"); goto err; } /* attach shared state */ if (!rec->hdl.xd) { xd = alloc_x_vc_data(); if (xd == NULL) { (void)syslog(LOG_ERR, clnt_vc_errstr, clnt_vc_str, __no_mem_str); rpc_createerr.cf_stat = RPC_SYSTEMERROR; rpc_createerr.cf_error.re_errno = errno; goto err; } rec->hdl.xd = xd; xd->refcnt++; xd->rec = rec; rpc_dplx_ref(rec, RPC_DPLX_FLAG_LOCKED); /* XXX tracks outstanding calls */ opr_rbtree_init(&xd->cx.calls.t, call_xid_cmpf); xd->cx.calls.xid = 0; /* next call xid is 1 */ xd->shared.sendsz = __rpc_get_t_size(si.si_af, si.si_proto, (int)sendsz); xd->shared.recvsz = __rpc_get_t_size(si.si_af, si.si_proto, (int)recvsz); /* duplex streams */ xdr_inrec_create(&(xd->shared.xdrs_in), xd->shared.recvsz, xd, generic_read_vc); xd->shared.xdrs_in.x_op = XDR_DECODE; xdrrec_create(&(xd->shared.xdrs_out), sendsz, xd->shared.recvsz, xd, generic_read_vc, generic_write_vc); xd->shared.xdrs_out.x_op = XDR_ENCODE; } else xd = rec->hdl.xd; clnt = (CLIENT *) mem_zalloc(sizeof(CLIENT)); mutex_init(&clnt->cl_lock, NULL); clnt->cl_flags = CLNT_FLAG_NONE; /* private data struct */ xd->cx.data.ct_fd = fd; cs = mem_alloc(sizeof(struct ct_serialized)); ct = &xd->cx.data; ct->ct_closeit = false; ct->ct_wait.tv_usec = 0; ct->ct_waitset = false; ct->ct_addr.buf = mem_alloc(raddr->maxlen); memcpy(ct->ct_addr.buf, raddr->buf, raddr->len); ct->ct_addr.len = raddr->len; ct->ct_addr.maxlen = raddr->maxlen; clnt->cl_netid = NULL; clnt->cl_tp = NULL; /* * initialize call message */ call_msg.rm_xid = 1; call_msg.rm_direction = CALL; call_msg.rm_call.cb_rpcvers = RPC_MSG_VERSION; call_msg.rm_call.cb_prog = (u_int32_t) prog; call_msg.rm_call.cb_vers = (u_int32_t) vers; /* * pre-serialize the static part of the call msg and stash it away */ xdrmem_create(ct_xdrs, cs->ct_u.ct_mcallc, MCALL_MSG_SIZE, XDR_ENCODE); if (!xdr_callhdr(ct_xdrs, &call_msg)) { if (ct->ct_closeit) (void)close(fd); goto err; } cs->ct_mpos = XDR_GETPOS(ct_xdrs); XDR_DESTROY(ct_xdrs); /* * Create a client handle which uses xdrrec for serialization * and authnone for authentication. */ clnt->cl_ops = clnt_vc_ops(); clnt->cl_p1 = xd; xd->refcnt++; clnt->cl_p2 = rec; rpc_dplx_ref(rec, RPC_DPLX_FLAG_LOCKED); clnt->cl_p3 = cs; /* release rec */ REC_UNLOCK(rec); thr_sigsetmask(SIG_SETMASK, &(mask), NULL); clnt_vc_ref(clnt, CLNT_REF_FLAG_NONE); /* ref for returned clnt */ return (clnt); err: /* XXX fix */ if (cs) { mem_free(cs, sizeof(struct ct_serialized)); } if (clnt) { xd->refcnt--; rpc_dplx_unref(rec, RPC_DPLX_FLAG_LOCKED); mutex_destroy(&clnt->cl_lock); mem_free(clnt, sizeof(CLIENT)); } if (rec) { /* return reference from lookup */ rpc_dplx_unref(rec, RPC_DPLX_FLAG_LOCKED | RPC_DPLX_FLAG_UNLOCK); } if (xd) { rpc_dplx_unref(xd->rec, RPC_DPLX_FLAG_NONE); if (ct->ct_addr.len) mem_free(ct->ct_addr.buf, ct->ct_addr.len); if (xd->refcnt == 0) { XDR_DESTROY(&xd->shared.xdrs_in); XDR_DESTROY(&xd->shared.xdrs_out); free_x_vc_data(xd); } } thr_sigsetmask(SIG_SETMASK, &(mask), NULL); return (NULL); } #define vc_call_return(r) \ do { \ result = (r); \ goto out; \ } while (0) #define vc_call_return_slocked(r) \ do { \ result = (r); \ if (!bidi) \ rpc_dplx_suc(clnt); \ goto out; \ } while (0) #define vc_call_return_rlocked(r) \ do { \ result = (r); \ rpc_dplx_ruc(clnt); \ goto out; \ } while (0) static enum clnt_stat clnt_vc_call(CLIENT *clnt, AUTH *auth, rpcproc_t proc, xdrproc_t xdr_args, void *args_ptr, xdrproc_t xdr_results, void *results_ptr, struct timeval timeout) { struct x_vc_data *xd = (struct x_vc_data *)clnt->cl_p1; struct ct_data *ct = &(xd->cx.data); struct ct_serialized *cs = (struct ct_serialized *)clnt->cl_p3; struct rpc_dplx_rec *rec = xd->rec; enum clnt_stat result = RPC_SUCCESS; rpc_ctx_t *ctx = NULL; XDR *xdrs; int code, refreshes = 2; bool ctx_needack = false; bool bidi = (rec->hdl.xprt != NULL); bool shipnow; bool gss = false; /* Create a call context. A lot of TI-RPC decisions need to be * looked at, including: * * 1. the client has a serialized call. This looks harmless, so long * as the xid is adjusted. * * 2. the last xid used is now saved in handle shared private data, it * will be incremented by rpc_call_create (successive calls). There's * no more reason to use the old time-dependent xid logic. It should be * preferable to count atomically from 1. * * 3. the client has an XDR structure, which contains the initialied * xdrrec stream. Since there is only one physical byte stream, it * would potentially be worse to do anything else? The main issue which * will arise is the need to transition the stream between calls--which * may require adjustment to xdrrec code. But on review it seems to * follow that one xdrrec stream would be parameterized by different * call contexts. We'll keep the call parameters, control transfer * machinery, etc, in an rpc_ctx_t, to permit this. */ ctx = alloc_rpc_call_ctx(clnt, proc, xdr_args, args_ptr, xdr_results, results_ptr, timeout); /*add total timeout? */ if (!ct->ct_waitset) { /* If time is not within limits, we ignore it. */ if (time_not_ok(&timeout) == false) ct->ct_wait = timeout; } shipnow = (xdr_results == NULL && timeout.tv_sec == 0 && timeout.tv_usec == 0) ? false : true; call_again: if (bidi) { /* XXX Until gss_get_mic and gss_wrap can be replaced with * iov equivalents, replies with RPCSEC_GSS security must be * encoded in a contiguous buffer. * * Nb, we should probably use getpagesize() on Unix. Need * an equivalent for Windows. */ gss = (auth->ah_cred.oa_flavor == RPCSEC_GSS); xdrs = xdr_ioq_create(8192 /* default segment size */ , __svc_params->svc_ioq_maxbuf + 8192, gss ? UIO_FLAG_REALLOC | UIO_FLAG_FREE : UIO_FLAG_FREE); } else { rpc_dplx_slc(clnt); xdrs = &(xd->shared.xdrs_out); xdrs->x_lib[0] = (void *)RPC_DPLX_CLNT; xdrs->x_lib[1] = (void *)ctx; /* thread call ctx */ } ctx->error.re_status = RPC_SUCCESS; cs->ct_u.ct_mcalli = ntohl(ctx->xid); if ((!XDR_PUTBYTES(xdrs, cs->ct_u.ct_mcallc, cs->ct_mpos)) || (!XDR_PUTINT32(xdrs, (int32_t *) &proc)) || (!AUTH_MARSHALL(auth, xdrs)) || (!AUTH_WRAP(auth, xdrs, xdr_args, args_ptr))) { if (ctx->error.re_status == RPC_SUCCESS) ctx->error.re_status = RPC_CANTENCODEARGS; /* error case */ if (!bidi) { (void)xdrrec_endofrecord(xdrs, true); vc_call_return_slocked(ctx->error.re_status); } else vc_call_return(ctx->error.re_status); } if (bidi) { svc_ioq_append(rec->hdl.xprt, xd, xdrs); } else { if (!xdrrec_endofrecord(xdrs, shipnow)) vc_call_return_slocked(ctx->error.re_status = RPC_CANTSEND); if (!shipnow) vc_call_return_slocked(RPC_SUCCESS); /* * Hack to provide rpc-based message passing */ if (timeout.tv_sec == 0 && timeout.tv_usec == 0) vc_call_return_slocked(ctx->error.re_status = RPC_TIMEDOUT); rpc_dplx_suc(clnt); } /* reply */ rpc_dplx_rlc(clnt); /* if the channel is bi-directional, then the the shared conn is in a * svc event loop, and recv processing decodes reply headers */ xdrs = &(xd->shared.xdrs_in); xdrs->x_lib[0] = (void *)RPC_DPLX_CLNT; xdrs->x_lib[1] = (void *)ctx; /* transiently thread call ctx */ if (bidi) { code = rpc_ctx_wait_reply(ctx, RPC_DPLX_FLAG_LOCKED);/* RECV! */ if (code == ETIMEDOUT) { /* UL can retry, we dont. This CAN indicate xprt * destroyed (error status already set). */ ctx->error.re_status = RPC_TIMEDOUT; goto unlock; } /* switch on direction */ switch (ctx->msg->rm_direction) { case REPLY: if (ctx->msg->rm_xid == ctx->xid) { ctx_needack = true; goto replied; } break; case CALL: /* in this configuration, we do not expect calls */ break; default: break; } } else { /* * Keep receiving until we get a valid transaction id. */ while (true) { /* skiprecord */ if (!xdr_inrec_skiprecord(xdrs)) { __warnx(TIRPC_DEBUG_FLAG_CLNT_VC, "%s: error at skiprecord", __func__); vc_call_return_rlocked(ctx->error.re_status); } /* now decode and validate the response header */ if (!xdr_dplx_decode(xdrs, ctx->msg)) { __warnx(TIRPC_DEBUG_FLAG_CLNT_VC, "%s: error at xdr_dplx_decode", __func__); vc_call_return_rlocked(ctx->error.re_status); } /* switch on direction */ switch (ctx->msg->rm_direction) { case REPLY: if (ctx->msg->rm_xid == ctx->xid) goto replied; break; case CALL: /* in this configuration, we do not expect * calls */ break; default: break; } } /* while (true) */ } /* ! bi-directional */ /* * process header */ replied: /* XXX move into routine which can be called from rpc_ctx_xfer_replymsg, * for (maybe) reduced MP overhead */ _seterr_reply(ctx->msg, &(ctx->error)); if (ctx->error.re_status == RPC_SUCCESS) { if (!AUTH_VALIDATE(auth, &(ctx->msg->acpted_rply.ar_verf))) { ctx->error.re_status = RPC_AUTHERROR; ctx->error.re_why = AUTH_INVALIDRESP; } else if (xdr_results /* XXX caller setup error? */ && !AUTH_UNWRAP(auth, xdrs, xdr_results, results_ptr)) { if (ctx->error.re_status == RPC_SUCCESS) ctx->error.re_status = RPC_CANTDECODERES; } /* free verifier ... */ if (ctx->msg->acpted_rply.ar_verf.oa_base != NULL) { xdrs->x_op = XDR_FREE; (void)xdr_opaque_auth(xdrs, &(ctx->msg->acpted_rply.ar_verf)); } if (ctx_needack) rpc_ctx_ack_xfer(ctx); } /* end successful completion */ else { /* maybe our credentials need to be refreshed ... */ if (refreshes-- && AUTH_REFRESH(auth, &(ctx->msg))) { rpc_ctx_next_xid(ctx, RPC_CTX_FLAG_NONE); rpc_dplx_ruc(clnt); if (ctx_needack) rpc_ctx_ack_xfer(ctx); goto call_again; } } /* end of unsuccessful completion */ unlock: vc_call_return_rlocked(ctx->error.re_status); out: free_rpc_call_ctx(ctx, RPC_CTX_FLAG_NONE); return (result); } static void clnt_vc_geterr(CLIENT *clnt, struct rpc_err *errp) { struct x_vc_data *xd = (struct x_vc_data *)clnt->cl_p1; XDR *xdrs; /* assert: it doesn't matter which we use */ xdrs = &xd->shared.xdrs_out; if (xdrs->x_lib[0]) { rpc_ctx_t *ctx = (rpc_ctx_t *) xdrs->x_lib[1]; *errp = ctx->error; } else { /* XXX we don't want (overhead of) an unsafe last-error value */ struct rpc_err err; memset(&err, 0, sizeof(struct rpc_err)); *errp = err; } } static bool clnt_vc_freeres(CLIENT *clnt, xdrproc_t xdr_res, void *res_ptr) { sigset_t mask, newmask; bool rslt; /* XXX is this (legacy) signalling/barrier logic needed? */ /* Handle our own signal mask here, the signal section is * larger than the wait (not 100% clear why) */ sigfillset(&newmask); thr_sigsetmask(SIG_SETMASK, &newmask, &mask); /* barrier recv channel */ rpc_dplx_rwc(clnt, rpc_flag_clear); rslt = xdr_free(xdr_res, res_ptr); thr_sigsetmask(SIG_SETMASK, &(mask), NULL); /* signal recv channel */ rpc_dplx_rsc(clnt, RPC_DPLX_FLAG_NONE); return (rslt); } /*ARGSUSED*/ static void clnt_vc_abort(CLIENT *clnt) { } static bool clnt_vc_control(CLIENT *clnt, u_int request, void *info) { struct x_vc_data *xd = (struct x_vc_data *)clnt->cl_p1; struct ct_data *ct = &(xd->cx.data); struct ct_serialized *cs = (struct ct_serialized *)clnt->cl_p3; void *infop = info; bool rslt = true; /* always take recv lock first if taking together */ rpc_dplx_rlc(clnt); rpc_dplx_slc(clnt); switch (request) { case CLSET_FD_CLOSE: ct->ct_closeit = true; goto unlock; return (true); case CLSET_FD_NCLOSE: ct->ct_closeit = false; goto unlock; return (true); default: break; } /* for other requests which use info */ if (info == NULL) { rslt = false; goto unlock; } switch (request) { case CLSET_TIMEOUT: if (time_not_ok((struct timeval *)info)) { rslt = false; goto unlock; } ct->ct_wait = *(struct timeval *)infop; ct->ct_waitset = true; break; case CLGET_TIMEOUT: *(struct timeval *)infop = ct->ct_wait; break; case CLGET_SERVER_ADDR: (void)memcpy(info, ct->ct_addr.buf, (size_t) ct->ct_addr.len); break; case CLGET_FD: *(int *)info = ct->ct_fd; break; case CLGET_SVC_ADDR: /* The caller should not free this memory area */ *(struct netbuf *)info = ct->ct_addr; break; case CLSET_SVC_ADDR: /* set to new address */ rslt = false; goto unlock; case CLGET_XID: /* * use the knowledge that xid is the * first element in the call structure * This will get the xid of the PREVIOUS call */ *(u_int32_t *) info = ntohl(*(u_int32_t *) (void *)&cs->ct_u.ct_mcalli); break; case CLSET_XID: /* This will set the xid of the NEXT call */ *(u_int32_t *) (void *)&cs->ct_u.ct_mcalli = htonl(*((u_int32_t *) info) + 1); /* increment by 1 as clnt_vc_call() decrements once */ break; case CLGET_VERS: /* * This RELIES on the information that, in the call body, * the version number field is the fifth field from the * begining of the RPC header. MUST be changed if the * call_struct is changed */ { u_int32_t *tmp = (u_int32_t *) (cs->ct_u.ct_mcallc + 4 * BYTES_PER_XDR_UNIT); *(u_int32_t *) info = ntohl(*tmp); } break; case CLSET_VERS: { u_int32_t tmp = htonl(*(u_int32_t *) info); *(cs->ct_u.ct_mcallc + 4 * BYTES_PER_XDR_UNIT) = tmp; } break; case CLGET_PROG: /* * This RELIES on the information that, in the call body, * the program number field is the fourth field from the * begining of the RPC header. MUST be changed if the * call_struct is changed */ { u_int32_t *tmp = (u_int32_t *) (cs->ct_u.ct_mcallc + 3 * BYTES_PER_XDR_UNIT); *(u_int32_t *) info = ntohl(*tmp); } break; case CLSET_PROG: { u_int32_t tmp = htonl(*(u_int32_t *) info); *(cs->ct_u.ct_mcallc + 3 * BYTES_PER_XDR_UNIT) = tmp; } break; default: rslt = false; goto unlock; break; } unlock: rpc_dplx_ruc(clnt); rpc_dplx_suc(clnt); return (rslt); } static bool clnt_vc_ref(CLIENT *clnt, u_int flags) { uint32_t refcnt; if (!(flags & CLNT_REF_FLAG_LOCKED)) mutex_lock(&clnt->cl_lock); if (clnt->cl_flags & CLNT_FLAG_DESTROYED) { mutex_unlock(&clnt->cl_lock); return (false); } refcnt = ++(clnt->cl_refcnt); mutex_unlock(&clnt->cl_lock); __warnx(TIRPC_DEBUG_FLAG_REFCNT, "%s: postref %p %u", __func__, clnt, refcnt); return (true); } static void clnt_vc_release(CLIENT *clnt, u_int flags) { uint32_t cl_refcnt; if (!(flags & CLNT_RELEASE_FLAG_LOCKED)) mutex_lock(&clnt->cl_lock); cl_refcnt = --(clnt->cl_refcnt); __warnx(TIRPC_DEBUG_FLAG_REFCNT, "%s: postunref %p cl_refcnt %u", __func__, clnt, cl_refcnt); /* conditional destroy */ if ((clnt->cl_flags & CLNT_FLAG_DESTROYED) && (cl_refcnt == 0)) { struct x_vc_data *xd = (struct x_vc_data *)clnt->cl_p1; struct rpc_dplx_rec *rec = xd->rec; struct ct_serialized *cs = (struct ct_serialized *)clnt->cl_p3; mutex_unlock(&clnt->cl_lock); mutex_destroy(&clnt->cl_lock); /* client handles are now freed directly */ mem_free(cs, sizeof(struct ct_serialized)); if (clnt->cl_netid && clnt->cl_netid[0]) mem_free(clnt->cl_netid, strlen(clnt->cl_netid) + 1); if (clnt->cl_tp && clnt->cl_tp[0]) mem_free(clnt->cl_tp, strlen(clnt->cl_tp) + 1); mem_free(clnt, sizeof(CLIENT)); REC_LOCK(rec); xd->refcnt--; /* clnt's reference */ rpc_dplx_unref(rec, RPC_DPLX_FLAG_LOCKED); vc_shared_destroy(xd); /* RECLOCKED */ } else mutex_unlock(&clnt->cl_lock); } static void clnt_vc_destroy(CLIENT *clnt) { struct rpc_dplx_rec *rec; struct x_vc_data *xd; uint32_t cl_refcnt = 0; mutex_lock(&clnt->cl_lock); if (clnt->cl_flags & CLNT_FLAG_DESTROYED) { mutex_unlock(&clnt->cl_lock); return; } xd = (struct x_vc_data *)clnt->cl_p1; rec = xd->rec; clnt->cl_flags |= CLNT_FLAG_DESTROYED; cl_refcnt = --(clnt->cl_refcnt); __warnx(TIRPC_DEBUG_FLAG_REFCNT, "%s: cl_destroy %p cl_refcnt %u", __func__, clnt, cl_refcnt); /* conditional destroy */ if (cl_refcnt != 0) return; mutex_unlock(&clnt->cl_lock); mutex_destroy(&clnt->cl_lock); /* client handles are now freed directly */ mem_free(clnt->cl_p3, sizeof(struct ct_serialized)); if (clnt->cl_netid && clnt->cl_netid[0]) mem_free(clnt->cl_netid, strlen(clnt->cl_netid) + 1); if (clnt->cl_tp && clnt->cl_tp[0]) mem_free(clnt->cl_tp, strlen(clnt->cl_tp) + 1); mem_free(clnt, sizeof(CLIENT)); REC_LOCK(rec); xd->refcnt--; rpc_dplx_unref(rec, RPC_DPLX_FLAG_LOCKED); vc_shared_destroy(xd); /* RECLOCKED */ } static struct clnt_ops * clnt_vc_ops(void) { static struct clnt_ops ops; extern mutex_t ops_lock; sigset_t mask, newmask; /* VARIABLES PROTECTED BY ops_lock: ops */ sigfillset(&newmask); thr_sigsetmask(SIG_SETMASK, &newmask, &mask); mutex_lock(&ops_lock); if (ops.cl_call == NULL) { ops.cl_call = clnt_vc_call; ops.cl_abort = clnt_vc_abort; ops.cl_geterr = clnt_vc_geterr; ops.cl_freeres = clnt_vc_freeres; ops.cl_ref = clnt_vc_ref; ops.cl_release = clnt_vc_release; ops.cl_destroy = clnt_vc_destroy; ops.cl_control = clnt_vc_control; } mutex_unlock(&ops_lock); thr_sigsetmask(SIG_SETMASK, &(mask), NULL); return (&ops); } /* * Make sure that the time is not garbage. -1 value is disallowed. * Note this is different from time_not_ok in clnt_dg.c */ static bool time_not_ok(struct timeval *t) { return (t->tv_sec <= -1 || t->tv_sec > 100000000 || t->tv_usec <= -1 || t->tv_usec > 1000000); } <file_sep>/* * Copyright (c) 2009, Sun Microsystems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - Neither the name of Sun Microsystems, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <config.h> /* * svc_vc.c, Server side for Connection Oriented RPC. * * Actually implements two flavors of transporter - * a tcp rendezvouser (a listner and connection establisher) * and a record/tcp stream. */ #include <sys/cdefs.h> #include <sys/socket.h> #ifdef RPC_VSOCK #include <linux/vm_sockets.h> #endif /* VSOCK */ #include <sys/types.h> #include <sys/param.h> #include <sys/poll.h> #include <sys/un.h> #include <sys/time.h> #include <sys/uio.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <assert.h> #include <err.h> #include <errno.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <signal.h> #include <misc/timespec.h> #include <rpc/types.h> #include <misc/portable.h> #include <rpc/rpc.h> #include <rpc/svc.h> #include <rpc/svc_auth.h> #include "rpc_com.h" #include "clnt_internal.h" #include "svc_internal.h" #include "svc_xprt.h" #include "rpc_dplx_internal.h" #include "rpc_ctx.h" #include <rpc/svc_rqst.h> #include <rpc/xdr_inrec.h> #include <rpc/xdr_ioq.h> #include <getpeereid.h> #include "svc_ioq.h" int generic_read_vc(XDR *, void *, void *, int); int generic_write_vc(XDR *, void *, void *, int); static void svc_vc_rendezvous_ops(SVCXPRT *, u_int); static void svc_vc_ops(SVCXPRT *, u_int); static void svc_vc_override_ops(SVCXPRT *, SVCXPRT *); bool __svc_clean_idle2(int, bool); static SVCXPRT *makefd_xprt(int, u_int, u_int); extern pthread_mutex_t svc_ctr_lock; /* * Usage: * xprt = svc_vc_ncreate(sock, send_buf_size, recv_buf_size); * * Creates, registers, and returns a (rpc) tcp based transport. * Once *xprt is initialized, it is registered as a transport * see (svc.h, xprt_register). This routine returns * a NULL if a problem occurred. * * Since streams do buffered io similar to stdio, the caller can specify * how big the send and receive buffers are via the second and third parms; * 0 => use the system default. * * Added svc_vc_ncreate2 with flags argument, has the behavior of the * original function if flags are SVC_VC_FLAG_NONE (0). * */ SVCXPRT * svc_vc_ncreate2(int fd, u_int sendsize, u_int recvsize, u_int flags) { SVCXPRT *xprt = NULL; struct cf_rendezvous *rdvs; struct __rpc_sockinfo si; struct sockaddr_storage sslocal; struct sockaddr *salocal; struct sockaddr_in *salocal_in; struct sockaddr_in6 *salocal_in6; struct rpc_dplx_rec *rec = NULL; struct x_vc_data *xd = NULL; const char *netid; socklen_t slen; if (!__rpc_fd2sockinfo(fd, &si)) return NULL; if (!__rpc_sockinfo2netid(&si, &netid)) return NULL; #ifdef RPC_VSOCK flags |= (si.si_af == AF_VSOCK) ? SVC_VC_CREATE_VSOCK : 0; #endif /* VSOCK */ /* atomically find or create shared fd state */ rec = rpc_dplx_lookup_rec(fd, RPC_DPLX_LKP_IFLAG_LOCKREC); if (!rec) { __warnx(TIRPC_DEBUG_FLAG_SVC_VC, "svc_vc: makefd_xprt: rpc_dplx_lookup_rec failed"); return NULL; } rdvs = mem_alloc(sizeof(struct cf_rendezvous)); rdvs->sendsize = __rpc_get_t_size(si.si_af, si.si_proto, (int)sendsize); rdvs->recvsize = __rpc_get_t_size(si.si_af, si.si_proto, (int)recvsize); rdvs->maxrec = __svc_maxrec; /* attach shared state */ if (!rec->hdl.xd) { xd = alloc_x_vc_data(); if (xd == NULL) { __warnx(TIRPC_DEBUG_FLAG_SVC_VC, "svc_vc: makefd_xprt: out of memory"); goto err; } rec->hdl.xd = xd; xd->refcnt++; xd->rec = rec; rpc_dplx_ref(rec, RPC_DPLX_FLAG_LOCKED); /* XXX tracks outstanding calls */ opr_rbtree_init(&xd->cx.calls.t, call_xid_cmpf); xd->cx.calls.xid = 0; /* next call xid is 1 */ xd->shared.sendsz = __rpc_get_t_size(si.si_af, si.si_proto, (int)sendsize); xd->shared.recvsz = __rpc_get_t_size(si.si_af, si.si_proto, (int)recvsize); /* duplex streams are not used by the rendevous transport */ memset(&xd->shared.xdrs_in, 0, sizeof xd->shared.xdrs_in); memset(&xd->shared.xdrs_out, 0, sizeof xd->shared.xdrs_out); } else { xd = (struct x_vc_data *)rec->hdl.xd; /* dont return destroyed xprts */ if (!(xd->flags & X_VC_DATA_FLAG_SVC_DESTROYED) && (rec->hdl.xprt)) { xprt = rec->hdl.xprt; mem_free(rdvs, sizeof(struct cf_rendezvous)); goto done; } } xprt = mem_zalloc(sizeof(SVCXPRT)); xprt->xp_flags = SVC_XPRT_FLAG_NONE; svc_vc_rendezvous_ops(xprt, flags); xprt->xp_p1 = xd; xd->refcnt++; xprt->xp_p5 = rec; rpc_dplx_ref(rec, RPC_DPLX_FLAG_LOCKED); xprt->xp_fd = fd; xprt->xp_p2 = rdvs; mutex_init(&xprt->xp_lock, NULL); /* make reachable from rec */ rec->hdl.xprt = xprt; svc_ref(xprt, xprt->xp_flags); /* caller should know what it's doing */ if (flags & SVC_VC_CREATE_LISTEN) listen(fd, SOMAXCONN); slen = sizeof(struct sockaddr_storage); if (getsockname(fd, (struct sockaddr *)(void *)&sslocal, &slen) < 0) { __warnx(TIRPC_DEBUG_FLAG_SVC_VC, "svc_vc_create: could not retrieve local addr"); goto err; } /* XXX following breaks strict aliasing? */ salocal = (struct sockaddr *)&sslocal; switch (salocal->sa_family) { case AF_INET: salocal_in = (struct sockaddr_in *)salocal; xprt->xp_port = ntohs(salocal_in->sin_port); break; case AF_INET6: salocal_in6 = (struct sockaddr_in6 *)salocal; xprt->xp_port = ntohs(salocal_in6->sin6_port); break; } __rpc_set_address(&xprt->xp_local, &sslocal, slen); xprt->xp_netid = mem_strdup(netid); /* release rec */ REC_UNLOCK(rec); /* make reachable from xprt list */ svc_rqst_init_xprt(xprt); /* conditional xprt_register */ if ((!(__svc_params->flags & SVC_FLAG_NOREG_XPRTS)) && (!(flags & SVC_VC_CREATE_XPRT_NOREG))) xprt_register(xprt); #if defined(HAVE_BLKIN) __rpc_set_blkin_endpoint(xprt, "svc_vc"); #endif done: svc_ref(xprt, xprt->xp_flags); /* inc for the returned reference */ return (xprt); err: mem_free(rdvs, sizeof(struct cf_rendezvous)); if (xprt) { #if defined(HAVE_BLKIN) if (xprt->blkin.svc_name) mem_free(xprt->blkin.svc_name, 2*INET6_ADDRSTRLEN); #endif if (xprt->xp_p1) xd->refcnt--; if (xprt->xp_p5) rpc_dplx_ref(rec, RPC_DPLX_FLAG_LOCKED); svc_release(xprt, xprt->xp_flags); /* return ref from rec */ } /* return ref from rpc_dplx_lookup_rec() */ rpc_dplx_unref(rec, RPC_DPLX_FLAG_LOCKED | RPC_DPLX_FLAG_UNLOCK); if (xd) { rpc_dplx_unref(xd->rec, RPC_DPLX_FLAG_NONE); if (xd->refcnt == 0) free_x_vc_data(xd); } return (NULL); } SVCXPRT * svc_vc_ncreate(int fd, u_int sendsize, u_int recvsize) { return (svc_vc_ncreate2(fd, sendsize, recvsize, SVC_VC_CREATE_NONE)); } /* * Like svtcp_ncreate(), except the routine takes any *open* UNIX file * descriptor as its first input. */ SVCXPRT * svc_fd_ncreate(int fd, u_int sendsize, u_int recvsize) { struct sockaddr_storage ss; socklen_t slen; SVCXPRT *xprt; assert(fd != -1); xprt = makefd_xprt(fd, sendsize, recvsize); if ((!xprt) || /* ref'd existing xprt */ atomic_postclear_uint16_t_bits(&xprt->xp_flags, SVC_XPRT_FLAG_ALLOCATED)) goto done; /* conditional xprt_register */ if (!(__svc_params->flags & SVC_FLAG_NOREG_XPRTS)) xprt_register(xprt); slen = sizeof(struct sockaddr_storage); if (getsockname(fd, (struct sockaddr *)(void *)&ss, &slen) < 0) { __warnx(TIRPC_DEBUG_FLAG_SVC_VC, "svc_fd_create: could not retrieve local addr"); goto freedata; } __rpc_set_address(&xprt->xp_local, &ss, slen); slen = sizeof(struct sockaddr_storage); if (getpeername(fd, (struct sockaddr *)(void *)&ss, &slen) < 0) { __warnx(TIRPC_DEBUG_FLAG_SVC_VC, "svc_fd_create: could not retrieve remote addr"); goto freedata; } __rpc_set_address(&xprt->xp_remote, &ss, slen); done: return (xprt); freedata: svc_release(xprt, xprt->xp_flags); return (NULL); } /* * Like sv_fd_ncreate(), except export flags for additional control. */ SVCXPRT * svc_fd_ncreate2(int fd, u_int sendsize, u_int recvsize, u_int flags) { struct sockaddr_storage ss; struct sockaddr *sa = (struct sockaddr *)(void *)&ss; socklen_t slen; SVCXPRT *xprt; assert(fd != -1); xprt = makefd_xprt(fd, sendsize, recvsize); if ((!xprt) || /* ref'd existing xprt */ atomic_postclear_uint16_t_bits(&xprt->xp_flags, SVC_XPRT_FLAG_ALLOCATED)) return (xprt); slen = sizeof(struct sockaddr_storage); if (getsockname(fd, sa, &slen) < 0) { __warnx(TIRPC_DEBUG_FLAG_SVC_VC, "svc_fd_ncreate: could not retrieve local addr"); goto freedata; } __rpc_set_address(&xprt->xp_local, &ss, slen); slen = sizeof(struct sockaddr_storage); if (getpeername(fd, (struct sockaddr *)(void *)&ss, &slen) < 0) { __warnx(TIRPC_DEBUG_FLAG_SVC_VC, "svc_fd_ncreate: could not retrieve remote addr"); goto freedata; } __rpc_set_address(&xprt->xp_remote, &ss, slen); /* conditional xprt_register */ if ((!(__svc_params->flags & SVC_FLAG_NOREG_XPRTS)) && (!(flags & SVC_VC_CREATE_XPRT_NOREG))) xprt_register(xprt); return (xprt); freedata: svc_release(xprt, xprt->xp_flags); return (NULL); } static SVCXPRT * makefd_xprt(int fd, u_int sendsz, u_int recvsz) { SVCXPRT *xprt = NULL; struct x_vc_data *xd = NULL; struct rpc_dplx_rec *rec; struct __rpc_sockinfo si; const char *netid; assert(fd != -1); if (!svc_vc_new_conn_ok()) { __warnx(TIRPC_DEBUG_FLAG_SVC_VC, "%s: makefd_xprt: max_connections exceeded\n", __func__); goto done; } /* atomically find or create shared fd state */ rec = rpc_dplx_lookup_rec(fd, RPC_DPLX_LKP_IFLAG_LOCKREC); if (!rec) { __warnx(TIRPC_DEBUG_FLAG_SVC_VC, "svc_vc: makefd_xprt: rpc_dplx_lookup_rec failed"); return NULL; } /* attach shared state */ if (!rec->hdl.xd) { xd = alloc_x_vc_data(); if (xd == NULL) { __warnx(TIRPC_DEBUG_FLAG_SVC_VC, "svc_vc: makefd_xprt: out of memory"); goto err; } rec->hdl.xd = xd; xd->refcnt++; xd->rec = rec; rpc_dplx_ref(rec, RPC_DPLX_FLAG_LOCKED); /* XXX tracks outstanding calls */ opr_rbtree_init(&xd->cx.calls.t, call_xid_cmpf); xd->cx.calls.xid = 0; /* next call xid is 1 */ if (__rpc_fd2sockinfo(fd, &si)) { xd->shared.sendsz = __rpc_get_t_size( si.si_af, si.si_proto, (int)sendsz); xd->shared.recvsz = __rpc_get_t_size( si.si_af, si.si_proto, (int)recvsz); } /* duplex streams */ xdr_inrec_create(&(xd->shared.xdrs_in), recvsz, xd, generic_read_vc); xd->shared.xdrs_in.x_op = XDR_DECODE; xdrrec_create(&(xd->shared.xdrs_out), sendsz, recvsz, xd, generic_read_vc, generic_write_vc); xd->shared.xdrs_out.x_op = XDR_ENCODE; } else { xd = (struct x_vc_data *)rec->hdl.xd; /* dont return destroyed xprts */ if (!(xd->flags & X_VC_DATA_FLAG_SVC_DESTROYED) && (rec->hdl.xprt)) { xprt = rec->hdl.xprt; goto done; } } /* XXX bi-directional? initially I had assumed that explicit * routines to create a clnt or svc handle from an already-connected * handle of the other type, but perhaps it is more natural to * just discover it */ /* new xprt (the common case) */ xprt = mem_zalloc(sizeof(SVCXPRT)); xprt->xp_flags = SVC_XPRT_FLAG_ALLOCATED; xprt->xp_p1 = xd; xd->refcnt++; xprt->xp_p5 = rec; rpc_dplx_ref(rec, RPC_DPLX_FLAG_LOCKED); xprt->xp_fd = fd; /* XXX take xp_lock? */ mutex_init(&xprt->xp_lock, NULL); mutex_init(&xprt->xp_auth_lock, NULL); /* make reachable from rec */ rec->hdl.xprt = xprt; svc_ref(xprt, xprt->xp_flags); /* the SVCXPRT created in svc_vc_create accepts new connections * in its xp_recv op, the rendezvous_request method, but xprt is * a call channel */ u_int ops_flags = #ifdef RPC_VSOCK (si.si_af == AF_VSOCK) ? SVC_VC_CREATE_VSOCK : #endif /* VSOCK */ 0; svc_vc_ops(xprt, ops_flags); xd->sx.strm_stat = XPRT_IDLE; /* ensures valid si */ if (__rpc_sockinfo2netid(&si, &netid)) xprt->xp_netid = mem_strdup(netid); /* release */ REC_UNLOCK(rec); /* Make reachable from xprt list. Registration deferred. */ svc_rqst_init_xprt(xprt); done: svc_ref(xprt, xprt->xp_flags); return (xprt); err: if (xprt) { if (xprt->xp_p1) xd->refcnt--; if (xprt->xp_p5) rpc_dplx_ref(rec, RPC_DPLX_FLAG_LOCKED); svc_release(xprt, xprt->xp_flags); /* return ref from rec */ } /* return ref from rpc_dplx_lookup_rec() */ rpc_dplx_unref(rec, RPC_DPLX_FLAG_LOCKED | RPC_DPLX_FLAG_UNLOCK); if (xd) { rpc_dplx_unref(xd->rec, RPC_DPLX_FLAG_NONE); if (xd->refcnt == 0) { XDR_DESTROY(&xd->shared.xdrs_in); XDR_DESTROY(&xd->shared.xdrs_out); free_x_vc_data(xd); } } return (NULL); } /*ARGSUSED*/ static bool rendezvous_request(SVCXPRT *xprt, struct svc_req *req) { int fd; socklen_t len; struct cf_rendezvous *rdvs; struct x_vc_data *xd; struct sockaddr_storage addr; struct __rpc_sockinfo si; socklen_t slen; SVCXPRT *newxprt; static int n = 1; rdvs = (struct cf_rendezvous *)xprt->xp_p2; again: len = sizeof(addr); fd = accept(xprt->xp_fd, (struct sockaddr *)(void *)&addr, &len); if (fd < 0) { if (errno == EINTR) goto again; /* * Clean out the most idle file descriptor when we're * running out. */ if (errno == EMFILE || errno == ENFILE) { switch (__svc_params->ev_type) { #if defined(TIRPC_EPOLL) case SVC_EVENT_EPOLL: break; #endif default: abort(); /* XXX */ break; } /* switch */ goto again; } return (FALSE); } (void) setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n)); /* * make a new transport (re-uses xprt) */ newxprt = makefd_xprt(fd, rdvs->sendsize, rdvs->recvsize); if ((!newxprt) || /* ref'd existing xprt */ atomic_postclear_uint16_t_bits(&newxprt->xp_flags, SVC_XPRT_FLAG_ALLOCATED)) return (FALSE); /* * propagate special ops */ svc_vc_override_ops(xprt, newxprt); /* move xprt_register() out of makefd_xprt */ (void)svc_rqst_xprt_register(xprt, newxprt); __rpc_set_address(&newxprt->xp_remote, &addr, len); XPRT_TRACE(newxprt, __func__, __func__, __LINE__); /* XXX fvdl - is this useful? (Yes. Matt) */ if (__rpc_fd2sockinfo(fd, &si) && si.si_proto == IPPROTO_TCP) { len = 1; (void) setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &len, sizeof(len)); } slen = sizeof(struct sockaddr_storage); if (getsockname(fd, (struct sockaddr *)(void *)&addr, &slen) < 0) { __warnx(TIRPC_DEBUG_FLAG_SVC_VC, "%s: could not retrieve local addr", __func__); } else { __rpc_set_address(&newxprt->xp_local, &addr, slen); } #if defined(HAVE_BLKIN) __rpc_set_blkin_endpoint(newxprt, "svc_vc"); #endif xd = (struct x_vc_data *)newxprt->xp_p1; xd->shared.recvsz = rdvs->recvsize; xd->shared.sendsz = rdvs->sendsize; xd->sx.maxrec = rdvs->maxrec; #if 0 /* XXX vrec wont support atm (and it seems to need work) */ if (cd->maxrec != 0) { flags = fcntl(fd, F_GETFL, 0); if (flags == -1) return (FALSE); if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1) return (FALSE); if (xd->shared.recvsz > xd->sx.maxrec) xd->shared.recvsz = xd->sx.maxrec; xd->shared.nonblock = TRUE; __xdrrec_setnonblock(&xd->shared.xdrs_in, xd->sx.maxrec); __xdrrec_setnonblock(&xd->shared.xdrs_out, xd->sx.maxrec); } else cd->nonblock = FALSE; #else xd->shared.nonblock = FALSE; #endif (void)clock_gettime(CLOCK_MONOTONIC_FAST, &xd->sx.last_recv); /* if parent has xp_recv_user_data, use it */ if (xprt->xp_ops->xp_recv_user_data) xprt->xp_ops->xp_recv_user_data(xprt, newxprt, SVC_RQST_FLAG_NONE, NULL); return (FALSE); /* there is never an rpc msg to be processed */ } /*ARGSUSED*/ static enum xprt_stat rendezvous_stat(SVCXPRT *xprt) { return (XPRT_IDLE); } /* XXX pending further unification * * note: currently, rdvs xprt handles have a rec structure, * but no xd structure, etc. * (they do too have an xd -- to track "destroyed" flag -- fixme?) * */ static void svc_rdvs_destroy(SVCXPRT *xprt, u_int flags, const char *tag, const int line) { struct cf_rendezvous *rdvs = (struct cf_rendezvous *)xprt->xp_p2; struct x_vc_data *xd = (struct x_vc_data *)xprt->xp_p1; struct rpc_dplx_rec *rec = (struct rpc_dplx_rec *)xprt->xp_p5; /* clears xprt from the xprt table (eg, idle scans) */ xprt_unregister(xprt); __warnx(TIRPC_DEBUG_FLAG_REFCNT, "%s() %p xp_refs %" PRIu32 " should actually destroy things @ %s:%d", __func__, xprt, xprt->xp_refs, tag, line); if (xprt->xp_fd != RPC_ANYFD) (void)close(xprt->xp_fd); if (xprt->xp_ops->xp_free_user_data) { /* call free hook */ xprt->xp_ops->xp_free_user_data(xprt); } REC_LOCK(rec); mutex_destroy(&xprt->xp_lock); if (xprt->xp_tp) mem_free(xprt->xp_tp, 0); if (xprt->xp_netid) mem_free(xprt->xp_netid, 0); mem_free(rdvs, sizeof(struct cf_rendezvous)); mem_free(xprt, sizeof(SVCXPRT)); xd->refcnt--; /* xprt's reference */ rec->hdl.xprt = NULL; (void)rpc_dplx_unref(rec, RPC_DPLX_FLAG_LOCKED | RPC_DPLX_FLAG_UNLOCK); if (xd->refcnt == 0) { (void)rpc_dplx_unref(rec, RPC_DPLX_FLAG_NONE); XDR_DESTROY(&xd->shared.xdrs_in); XDR_DESTROY(&xd->shared.xdrs_out); free_x_vc_data(xd); } } static void svc_vc_destroy(SVCXPRT *xprt, u_int flags, const char *tag, const int line) { struct x_vc_data *xd = (struct x_vc_data *)xprt->xp_p1; struct rpc_dplx_rec *rec = xd->rec; /* connection tracking--decrement now, he's dead jim */ svc_vc_dec_nconns(); /* clears xprt from the xprt table (eg, idle scans) */ xprt_unregister(xprt); /* bidirectional */ REC_LOCK(rec); xd->flags |= X_VC_DATA_FLAG_SVC_DESTROYED; rec->hdl.xd = NULL; xd->refcnt--; xprt->xp_p1 = NULL; xd->refcnt--; rpc_dplx_unref(rec, RPC_DPLX_FLAG_LOCKED); __warnx(TIRPC_DEBUG_FLAG_REFCNT, "%s: postfinalize %p xp_refs %" PRIu32 " xd_refcnt %u", __func__, xprt, xprt->xp_refs, xd->refcnt); vc_shared_destroy(xd); /* RECLOCKED */ } extern mutex_t ops_lock; /*ARGSUSED*/ static bool svc_vc_control(SVCXPRT *xprt, const u_int rq, void *in) { switch (rq) { case SVCGET_XP_FLAGS: *(u_int *) in = xprt->xp_flags; break; case SVCSET_XP_FLAGS: xprt->xp_flags = *(u_int *) in; break; case SVCGET_XP_RECV: mutex_lock(&ops_lock); *(xp_recv_t *) in = xprt->xp_ops->xp_recv; mutex_unlock(&ops_lock); break; case SVCSET_XP_RECV: mutex_lock(&ops_lock); xprt->xp_ops->xp_recv = *(xp_recv_t) in; mutex_unlock(&ops_lock); break; case SVCGET_XP_GETREQ: mutex_lock(&ops_lock); *(xp_getreq_t *) in = xprt->xp_ops->xp_getreq; mutex_unlock(&ops_lock); break; case SVCSET_XP_GETREQ: mutex_lock(&ops_lock); xprt->xp_ops->xp_getreq = *(xp_getreq_t) in; mutex_unlock(&ops_lock); break; case SVCGET_XP_DISPATCH: mutex_lock(&ops_lock); *(xp_dispatch_t *) in = xprt->xp_ops->xp_dispatch; mutex_unlock(&ops_lock); break; case SVCSET_XP_DISPATCH: mutex_lock(&ops_lock); xprt->xp_ops->xp_dispatch = *(xp_dispatch_t) in; mutex_unlock(&ops_lock); break; case SVCGET_XP_RECV_USER_DATA: mutex_lock(&ops_lock); *(xp_recv_user_data_t *) in = xprt->xp_ops->xp_recv_user_data; mutex_unlock(&ops_lock); break; case SVCSET_XP_RECV_USER_DATA: mutex_lock(&ops_lock); xprt->xp_ops->xp_recv_user_data = *(xp_recv_user_data_t) in; mutex_unlock(&ops_lock); break; case SVCGET_XP_FREE_USER_DATA: mutex_lock(&ops_lock); *(xp_free_user_data_t *) in = xprt->xp_ops->xp_free_user_data; mutex_unlock(&ops_lock); break; case SVCSET_XP_FREE_USER_DATA: mutex_lock(&ops_lock); xprt->xp_ops->xp_free_user_data = *(xp_free_user_data_t) in; mutex_unlock(&ops_lock); break; default: return (FALSE); } return (TRUE); } static bool svc_vc_rendezvous_control(SVCXPRT *xprt, const u_int rq, void *in) { struct cf_rendezvous *cfp; cfp = (struct cf_rendezvous *)xprt->xp_p2; if (cfp == NULL) return (FALSE); switch (rq) { case SVCGET_CONNMAXREC: *(int *)in = cfp->maxrec; break; case SVCSET_CONNMAXREC: cfp->maxrec = *(int *)in; break; case SVCGET_XP_RECV: mutex_lock(&ops_lock); *(xp_recv_t *) in = xprt->xp_ops->xp_recv; mutex_unlock(&ops_lock); break; case SVCSET_XP_RECV: mutex_lock(&ops_lock); xprt->xp_ops->xp_recv = *(xp_recv_t) in; mutex_unlock(&ops_lock); break; case SVCGET_XP_GETREQ: mutex_lock(&ops_lock); *(xp_getreq_t *) in = xprt->xp_ops->xp_getreq; mutex_unlock(&ops_lock); break; case SVCSET_XP_GETREQ: mutex_lock(&ops_lock); xprt->xp_ops->xp_getreq = *(xp_getreq_t) in; mutex_unlock(&ops_lock); break; case SVCGET_XP_DISPATCH: mutex_lock(&ops_lock); *(xp_dispatch_t *) in = xprt->xp_ops->xp_dispatch; mutex_unlock(&ops_lock); break; case SVCSET_XP_DISPATCH: mutex_lock(&ops_lock); xprt->xp_ops->xp_dispatch = *(xp_dispatch_t) in; mutex_unlock(&ops_lock); break; case SVCGET_XP_RECV_USER_DATA: mutex_lock(&ops_lock); *(xp_recv_user_data_t *) in = xprt->xp_ops->xp_recv_user_data; mutex_unlock(&ops_lock); break; case SVCSET_XP_RECV_USER_DATA: mutex_lock(&ops_lock); xprt->xp_ops->xp_recv_user_data = *(xp_recv_user_data_t) in; mutex_unlock(&ops_lock); break; case SVCGET_XP_FREE_USER_DATA: mutex_lock(&ops_lock); *(xp_free_user_data_t *) in = xprt->xp_ops->xp_free_user_data; mutex_unlock(&ops_lock); break; case SVCSET_XP_FREE_USER_DATA: mutex_lock(&ops_lock); xprt->xp_ops->xp_free_user_data = *(xp_free_user_data_t) in; mutex_unlock(&ops_lock); break; default: return (FALSE); } return (TRUE); } static enum xprt_stat svc_vc_stat(SVCXPRT *xprt) { struct x_vc_data *xd = (struct x_vc_data *)xprt->xp_p1; if (xprt->xp_flags & SVC_XPRT_FLAG_DESTROYED) return (XPRT_DESTROYED); if (!xd) return (XPRT_IDLE); /* we hold the recv lock */ if (xd->sx.strm_stat == XPRT_DIED) return (XPRT_DIED); if (!xdr_inrec_eof(&(xd->shared.xdrs_in))) return (XPRT_MOREREQS); return (XPRT_IDLE); } static bool svc_vc_recv(SVCXPRT *xprt, struct svc_req *req) { struct x_vc_data *xd = (struct x_vc_data *)xprt->xp_p1; XDR *xdrs = &(xd->shared.xdrs_in); /* recv queue */ /* XXX assert(! cd->nonblock) */ if (xd->shared.nonblock) { if (!__xdrrec_getrec(xdrs, &xd->sx.strm_stat, TRUE)) return FALSE; } xdrs->x_op = XDR_DECODE; xdrs->x_lib[0] = (void *)RPC_DPLX_SVC; xdrs->x_lib[1] = (void *)xprt; /* transiently thread xprt */ /* Consumes any remaining -fragment- bytes, and clears last_frag */ (void)xdr_inrec_skiprecord(xdrs); req->rq_msg = alloc_rpc_msg(); req->rq_clntcred = req->rq_msg->rq_cred_body; /* Advances to next record, will read up to 1024 bytes * into the stream. */ (void)xdr_inrec_readahead(xdrs, 1024); if (xdr_dplx_decode(xdrs, req->rq_msg)) { switch (req->rq_msg->rm_direction) { case CALL: /* an ordinary call header */ req->rq_xprt = xprt; req->rq_prog = req->rq_msg->rm_call.cb_prog; req->rq_vers = req->rq_msg->rm_call.cb_vers; req->rq_proc = req->rq_msg->rm_call.cb_proc; req->rq_xid = req->rq_msg->rm_xid; return (TRUE); break; case REPLY: /* reply header (xprt OK) */ rpc_ctx_xfer_replymsg(xd, req->rq_msg); req->rq_msg = NULL; break; default: /* not good (but xprt OK) */ break; } /* XXX skiprecord? */ return (FALSE); } __warnx(TIRPC_DEBUG_FLAG_SVC_VC, "%s: xdr_dplx_msg_decode failed (will set dead)", __func__); return (FALSE); } static bool svc_vc_freeargs(SVCXPRT *xprt, struct svc_req *req, xdrproc_t xdr_args, void *args_ptr) { return xdr_free(xdr_args, args_ptr); } static bool svc_vc_getargs(SVCXPRT *xprt, struct svc_req *req, xdrproc_t xdr_args, void *args_ptr, void *u_data) { struct x_vc_data *xd = (struct x_vc_data *)xprt->xp_p1; XDR *xdrs = &xd->shared.xdrs_in; /* recv queue */ bool rslt; /* threads u_data for advanced decoders */ xdrs->x_public = u_data; rslt = SVCAUTH_UNWRAP(req->rq_auth, req, xdrs, xdr_args, args_ptr); /* XXX Upstream TI-RPC lacks this call, but -does- call svc_dg_freeargs * in svc_dg_getargs if SVCAUTH_UNWRAP fails. */ if (rslt) req->rq_cksum = xdr_inrec_cksum(xdrs); else svc_vc_freeargs(xprt, req, xdr_args, args_ptr); return (rslt); } static bool svc_vc_reply(SVCXPRT *xprt, struct svc_req *req, struct rpc_msg *msg) { struct x_vc_data *xd = (struct x_vc_data *)xprt->xp_p1; XDR *xdrs_2; xdrproc_t xdr_results; caddr_t xdr_location; bool rstat = false; bool has_args; bool gss; if (msg->rm_reply.rp_stat == MSG_ACCEPTED && msg->rm_reply.rp_acpt.ar_stat == SUCCESS) { has_args = TRUE; xdr_results = msg->acpted_rply.ar_results.proc; xdr_location = msg->acpted_rply.ar_results.where; msg->acpted_rply.ar_results.proc = (xdrproc_t) xdr_void; msg->acpted_rply.ar_results.where = NULL; } else { has_args = FALSE; xdr_results = NULL; xdr_location = NULL; } /* XXX Until gss_get_mic and gss_wrap can be replaced with * iov equivalents, replies with RPCSEC_GSS security must be * encoded in a contiguous buffer. * * Nb, we should probably use getpagesize() on Unix. Need * an equivalent for Windows. */ gss = (req->rq_cred.oa_flavor == RPCSEC_GSS); xdrs_2 = xdr_ioq_create(8192 /* default segment size */ , __svc_params->svc_ioq_maxbuf + 8192, gss ? UIO_FLAG_REALLOC | UIO_FLAG_FREE : UIO_FLAG_FREE); if (xdr_replymsg(xdrs_2, msg) && (!has_args || (req->rq_auth && SVCAUTH_WRAP(req->rq_auth, req, xdrs_2, xdr_results, xdr_location)))) { rstat = TRUE; } svc_ioq_append(xprt, xd, xdrs_2); return (rstat); } static void svc_vc_lock(SVCXPRT *xprt, uint32_t flags, const char *func, int line) { if (flags & XP_LOCK_RECV) rpc_dplx_rlxi(xprt, func, line); if (flags & XP_LOCK_SEND) rpc_dplx_slxi(xprt, func, line); } static void svc_vc_unlock(SVCXPRT *xprt, uint32_t flags, const char *func, int line) { if (flags & XP_LOCK_RECV) rpc_dplx_rux(xprt); if (flags & XP_LOCK_SEND) rpc_dplx_sux(xprt); } static void svc_vc_ops(SVCXPRT *xprt, u_int flags) { static struct xp_ops ops; /* VARIABLES PROTECTED BY ops_lock: ops, xp_type */ mutex_lock(&ops_lock); xprt->xp_type = XPRT_TCP; xprt->xp_type = #ifdef RPC_VSOCK (flags & SVC_VC_CREATE_VSOCK) ? XPRT_VSOCK : #endif /* VSOCK */ XPRT_TCP; if (ops.xp_recv == NULL) { ops.xp_recv = svc_vc_recv; ops.xp_stat = svc_vc_stat; ops.xp_getargs = svc_vc_getargs; ops.xp_reply = svc_vc_reply; ops.xp_freeargs = svc_vc_freeargs; ops.xp_destroy = svc_vc_destroy; ops.xp_control = svc_vc_control; ops.xp_lock = svc_vc_lock; ops.xp_unlock = svc_vc_unlock; ops.xp_getreq = svc_getreq_default; ops.xp_dispatch = svc_dispatch_default; ops.xp_recv_user_data = NULL; /* no default */ ops.xp_free_user_data = NULL; /* no default */ } xprt->xp_ops = &ops; mutex_unlock(&ops_lock); } static void svc_vc_override_ops(SVCXPRT *xprt, SVCXPRT *newxprt) { if (xprt->xp_ops->xp_getreq) newxprt->xp_ops->xp_getreq = xprt->xp_ops->xp_getreq; if (xprt->xp_ops->xp_dispatch) newxprt->xp_ops->xp_dispatch = xprt->xp_ops->xp_dispatch; if (xprt->xp_ops->xp_recv_user_data) { newxprt->xp_ops->xp_recv_user_data = xprt->xp_ops->xp_recv_user_data; } if (xprt->xp_ops->xp_free_user_data) { newxprt->xp_ops->xp_free_user_data = xprt->xp_ops->xp_free_user_data; } } static void svc_vc_rendezvous_ops(SVCXPRT *xprt, u_int flags) { static struct xp_ops ops; extern mutex_t ops_lock; mutex_lock(&ops_lock); xprt->xp_type = #ifdef RPC_VSOCK (flags & SVC_VC_CREATE_VSOCK) ? XPRT_VSOCK_RENDEZVOUS : #endif /* VSOCK */ XPRT_TCP_RENDEZVOUS; if (ops.xp_recv == NULL) { ops.xp_recv = rendezvous_request; ops.xp_stat = rendezvous_stat; /* XXX wow */ ops.xp_getargs = (bool(*) (SVCXPRT *, struct svc_req *, xdrproc_t, void *, void *))abort; ops.xp_reply = (bool(*) (SVCXPRT *, struct svc_req *req, struct rpc_msg *))abort; ops.xp_freeargs = (bool(*) (SVCXPRT *, struct svc_req *, xdrproc_t, void *))abort; ops.xp_destroy = svc_rdvs_destroy; ops.xp_control = svc_vc_rendezvous_control; ops.xp_lock = svc_vc_lock; ops.xp_unlock = svc_vc_unlock; ops.xp_getreq = svc_getreq_default; ops.xp_dispatch = svc_dispatch_default; ops.xp_recv_user_data = NULL; /* no default */ ops.xp_free_user_data = NULL; /* no default */ } xprt->xp_ops = &ops; mutex_unlock(&ops_lock); } /* * Get the effective UID of the sending process. Used by rpcbind, keyserv * and rpc.yppasswdd on AF_LOCAL. */ int __rpc_get_local_uid(SVCXPRT *transp, uid_t *uid) { int sock, ret; gid_t egid; uid_t euid; struct sockaddr *sa; sock = transp->xp_fd; sa = (struct sockaddr *)&transp->xp_remote.ss; if (sa->sa_family == AF_LOCAL) { ret = getpeereid(sock, &euid, &egid); if (ret == 0) *uid = euid; return (ret); } else return (-1); } /* * Destroy xprts that have not have had any activity in 'timeout' seconds. * If 'cleanblock' is true, blocking connections (the default) are also * cleaned. If timeout is 0, the least active connection is picked. * * Though this is not a publicly documented interface, some versions of * rpcbind are known to call this function. Do not alter or remove this * API without changing the library's sonum. */ bool __svc_clean_idle(fd_set *fds, int timeout, bool cleanblock) { return (__svc_clean_idle2(timeout, cleanblock)); } /* __svc_clean_idle */ /* * Like __svc_clean_idle but event-type independent. For now no cleanfds. */ struct svc_clean_idle_arg { SVCXPRT *least_active; struct timespec ts, tmax; int cleanblock, ncleaned, timeout; }; static uint32_t svc_clean_idle2_func(SVCXPRT *xprt, void *arg) { struct timespec tdiff; struct svc_clean_idle_arg *acc = (struct svc_clean_idle_arg *)arg; uint32_t rflag = SVC_XPRT_FOREACH_NONE; if (!acc->cleanblock) goto out; mutex_lock(&xprt->xp_lock); /* invalid xprt (error) */ if (xprt->xp_ops == NULL) goto unlock; if (xprt->xp_flags & SVC_XPRT_FLAG_DESTROYED) { /* XXX should not happen--but do no harm */ __warnx(TIRPC_DEBUG_FLAG_SVC_VC, "%s: destroyed xprt %p seen in clean idle\n", __func__, xprt); goto unlock; } if (xprt->xp_ops->xp_recv != svc_vc_recv) goto unlock; { /* XXX nb., safe because xprt type is verfied */ struct x_vc_data *xd = xprt->xp_p1; if (!xd->shared.nonblock) goto unlock; if (acc->timeout == 0) { tdiff = acc->ts; timespecsub(&tdiff, &xd->sx.last_recv); if (timespeccmp(&tdiff, &acc->tmax, >)) { acc->tmax = tdiff; acc->least_active = xprt; } goto unlock; } if (acc->ts.tv_sec - xd->sx.last_recv.tv_sec > acc->timeout) { rflag = SVC_XPRT_FOREACH_CLEAR; mutex_unlock(&xprt->xp_lock); SVC_DESTROY(xprt); acc->ncleaned++; goto out; } } unlock: mutex_unlock(&xprt->xp_lock); out: return (rflag); } /* XXX move to svc_run */ void authgss_ctx_gc_idle(void); bool __svc_clean_idle2(int timeout, bool cleanblock) { struct svc_clean_idle_arg acc; static mutex_t active_mtx = MUTEX_INITIALIZER; static uint32_t active; bool_t rslt = FALSE; if (mutex_trylock(&active_mtx) != 0) goto out; if (active > 0) goto unlock; ++active; /* trim gss context cache */ authgss_ctx_gc_idle(); /* trim xprts (not sorted, not aggressive [but self limiting]) */ memset(&acc, 0, sizeof(struct svc_clean_idle_arg)); (void)clock_gettime(CLOCK_MONOTONIC_FAST, &acc.ts); acc.cleanblock = cleanblock; acc.timeout = timeout; svc_xprt_foreach(svc_clean_idle2_func, (void *)&acc); if (timeout == 0 && acc.least_active != NULL) { SVC_DESTROY(acc.least_active); acc.ncleaned++; } rslt = (acc.ncleaned > 0) ? TRUE : FALSE; --active; unlock: mutex_unlock(&active_mtx); out: return (rslt); } /* __svc_clean_idle2 */ /* * Create an RPC client handle from an active service transport * handle, i.e., to issue calls on the channel. * * If flags & SVC_VC_CLNT_CREATE_DEDICATED, the supplied xprt will be * unregistered and disposed inline. */ CLIENT * clnt_vc_ncreate_svc(SVCXPRT *xprt, const rpcprog_t prog, const rpcvers_t vers, const uint32_t flags) { struct x_vc_data *xd; CLIENT *clnt; mutex_lock(&xprt->xp_lock); xd = (struct x_vc_data *)xprt->xp_p1; /* XXX return allocated client structure, or allocate one if none * is currently allocated */ clnt = clnt_vc_ncreate2(xprt->xp_fd, &xprt->xp_remote.nb, prog, vers, xd->shared.sendsz, xd->shared.recvsz, CLNT_CREATE_FLAG_SVCXPRT); mutex_unlock(&xprt->xp_lock); /* for a dedicated channel, unregister and free xprt */ if ((flags & SVC_VC_CREATE_ONEWAY) && (flags & SVC_VC_CREATE_DISPOSE)) { __warnx(TIRPC_DEBUG_FLAG_SVC_VC, "%s: disposing--calls svc_vc_destroy\n", __func__); svc_vc_destroy(xprt, 0, __func__, __LINE__); } return (clnt); } /* * Create an RPC SVCXPRT handle from an active client transport * handle, i.e., to service RPC requests. * * If flags & SVC_VC_CREATE_CL_FLAG_DEDICATED, then clnt is also * deallocated without closing cl->cl_p1->ct_fd. */ SVCXPRT * svc_vc_ncreate_clnt(CLIENT *clnt, const u_int sendsz, const u_int recvsz, const uint32_t flags) { int fd; socklen_t len; struct x_vc_data *xd = (struct x_vc_data *)clnt->cl_p1; struct ct_data *ct = &xd->cx.data; struct sockaddr_storage addr; struct __rpc_sockinfo si; SVCXPRT *xprt = NULL; fd = ct->ct_fd; rpc_dplx_rlc(clnt); rpc_dplx_slc(clnt); len = sizeof(struct sockaddr_storage); if (getpeername(fd, (struct sockaddr *)(void *)&addr, &len) < 0) { __warnx(TIRPC_DEBUG_FLAG_SVC_VC, "%s: could not retrieve remote addr", __func__); goto unlock; } /* * make a new transport */ xprt = makefd_xprt(fd, sendsz, recvsz); if ((!xprt) || /* ref'd existing xprt */ atomic_postclear_uint16_t_bits(&xprt->xp_flags, SVC_XPRT_FLAG_ALLOCATED)) goto unlock; __rpc_set_address(&xprt->xp_remote, &addr, len); if (__rpc_fd2sockinfo(fd, &si) && si.si_proto == IPPROTO_TCP) { len = 1; (void) setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &len, sizeof(len)); } xd->sx.maxrec = __svc_maxrec; /* XXX check */ #if 0 /* XXX wont currently support */ if (xd->sx.maxrec != 0) { fflags = fcntl(fd, F_GETFL, 0); if (fflags == -1) return (FALSE); if (fcntl(fd, F_SETFL, fflags | O_NONBLOCK) == -1) return (FALSE); if (xd->shared.recvsz > xd->sx.maxrec) xd->shared.recvsz = xd->sx.maxrec; cd->nonblock = TRUE; __xdrrec_setnonblock(&cd->xdrs, xd->sx.maxrec); } else xd->shared.nonblock = FALSE; #else xd->shared.nonblock = FALSE; #endif (void)clock_gettime(CLOCK_MONOTONIC_FAST, &xd->sx.last_recv); /* conditional xprt_register */ if ((!(__svc_params->flags & SVC_FLAG_NOREG_XPRTS)) && (!(flags & SVC_VC_CREATE_XPRT_NOREG))) xprt_register(xprt); /* If creating a dedicated channel collect the supplied client * without closing fd */ if ((flags & SVC_VC_CREATE_ONEWAY) && (flags & SVC_VC_CREATE_DISPOSE)) { ct->ct_closeit = FALSE; /* must not close */ rpc_dplx_ruc(clnt); rpc_dplx_suc(clnt); CLNT_DESTROY(clnt); /* clean up immediately */ goto out; } unlock: rpc_dplx_ruc(clnt); rpc_dplx_suc(clnt); out: return (xprt); } <file_sep>/* * Copyright (c) 2009, Sun Microsystems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - Neither the name of Sun Microsystems, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* #include <sys/cdefs.h> */ /* * clnt_perror.c * * Copyright (C) 1984, Sun Microsystems, Inc. * */ #include <config.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <rpc/rpc.h> #include <rpc/types.h> #include <rpc/auth.h> #include <rpc/clnt.h> static char *buf; static char *_buf(void); static char *auth_errmsg(enum auth_stat); #define CLNT_PERROR_BUFLEN 256 static char * _buf(void) { if (!buf) buf = (char *)mem_alloc(CLNT_PERROR_BUFLEN); return (buf); } /* * Print reply error info */ char * clnt_sperror(CLIENT *rpch, const char *s) { struct rpc_err e; char *err; char *str; char *strstart; size_t len, i; if (rpch == NULL || s == NULL) return (0); str = _buf(); /* side effect: sets CLNT_PERROR_BUFLEN */ if (str == 0) return (0); len = CLNT_PERROR_BUFLEN; strstart = str; CLNT_GETERR(rpch, &e); if (snprintf(str, len, "%s: ", s) > 0) { i = strlen(str); str += i; len -= i; } (void)strncpy(str, clnt_sperrno(e.re_status), len - 1); i = strlen(str); str += i; len -= i; switch (e.re_status) { case RPC_SUCCESS: case RPC_CANTENCODEARGS: case RPC_CANTDECODERES: case RPC_TIMEDOUT: case RPC_PROGUNAVAIL: case RPC_PROCUNAVAIL: case RPC_CANTDECODEARGS: case RPC_SYSTEMERROR: case RPC_UNKNOWNHOST: case RPC_UNKNOWNPROTO: case RPC_PMAPFAILURE: case RPC_PROGNOTREGISTERED: case RPC_FAILED: break; case RPC_CANTSEND: case RPC_CANTRECV: snprintf(str, len, "; errno = %s", strerror(e.re_errno)); i = strlen(str); if (i > 0) { str += i; len -= i; } break; case RPC_VERSMISMATCH: snprintf(str, len, "; low version = %u, high version = %u", e.re_vers.low, e.re_vers.high); i = strlen(str); if (i > 0) { str += i; len -= i; } break; case RPC_AUTHERROR: err = auth_errmsg(e.re_why); snprintf(str, len, "; why = "); i = strlen(str); if (i > 0) { str += i; len -= i; } if (err != NULL) { snprintf(str, len, "%s", err); } else { snprintf(str, len, "(unknown authentication error - %d)", (int)e.re_why); } i = strlen(str); if (i > 0) { str += i; len -= i; } break; case RPC_PROGVERSMISMATCH: snprintf(str, len, "; low version = %u, high version = %u", e.re_vers.low, e.re_vers.high); i = strlen(str); if (i > 0) { str += i; len -= i; } break; default: /* unknown */ snprintf(str, len, "; s1 = %u, s2 = %u", e.re_lb.s1, e.re_lb.s2); i = strlen(str); if (i > 0) { str += i; len -= i; } break; } strstart[CLNT_PERROR_BUFLEN - 1] = '\0'; return (strstart); } void clnt_perror(CLIENT *rpch, const char *s) { if (rpch == NULL || s == NULL) return; (void)fprintf(stderr, "%s\n", clnt_sperror(rpch, s)); } static const char *const rpc_errlist[] = { "RPC: Success", /* 0 - RPC_SUCCESS */ "RPC: Can't encode arguments", /* 1 - RPC_CANTENCODEARGS */ "RPC: Can't decode result", /* 2 - RPC_CANTDECODERES */ "RPC: Unable to send", /* 3 - RPC_CANTSEND */ "RPC: Unable to receive", /* 4 - RPC_CANTRECV */ "RPC: Timed out", /* 5 - RPC_TIMEDOUT */ "RPC: Incompatible versions of RPC", /* 6 - RPC_VERSMISMATCH */ "RPC: Authentication error", /* 7 - RPC_AUTHERROR */ "RPC: Program unavailable", /* 8 - RPC_PROGUNAVAIL */ "RPC: Program/version mismatch", /* 9 - RPC_PROGVERSMISMATCH */ "RPC: Procedure unavailable", /* 10 - RPC_PROCUNAVAIL */ "RPC: Server can't decode arguments", /* 11 - RPC_CANTDECODEARGS */ "RPC: Remote system error", /* 12 - RPC_SYSTEMERROR */ "RPC: Unknown host", /* 13 - RPC_UNKNOWNHOST */ "RPC: Port mapper failure", /* 14 - RPC_PMAPFAILURE */ "RPC: Program not registered", /* 15 - RPC_PROGNOTREGISTERED */ "RPC: Failed (unspecified error)", /* 16 - RPC_FAILED */ "RPC: Unknown protocol" /* 17 - RPC_UNKNOWNPROTO */ }; /* * This interface for use by clntrpc */ char * clnt_sperrno(enum clnt_stat stat) { unsigned int errnum = stat; if (errnum < (sizeof(rpc_errlist) / sizeof(rpc_errlist[0]))) /* LINTED interface problem */ return (char *)rpc_errlist[errnum]; return ("RPC: (unknown error code)"); } void clnt_perrno(enum clnt_stat num) { (void)fprintf(stderr, "%s\n", clnt_sperrno(num)); } char * clnt_spcreateerror(const char *s) { char *str, *err; size_t len, i; if (s == NULL) return (0); str = _buf(); /* side effect: sets CLNT_PERROR_BUFLEN */ if (str == 0) return (0); len = CLNT_PERROR_BUFLEN; snprintf(str, len, "%s: ", s); i = strlen(str); if (i > 0) len -= i; (void)strncat(str, clnt_sperrno(rpc_createerr.cf_stat), len - 1); switch (rpc_createerr.cf_stat) { case RPC_PMAPFAILURE: (void)strncat(str, " - ", len - 1); err = clnt_sperrno(rpc_createerr.cf_error.re_status); if (err) (void)strncat(str, err + 5, len - 5); switch (rpc_createerr.cf_error.re_status) { case RPC_CANTSEND: case RPC_CANTRECV: i = strlen(str); len -= i; snprintf(str + i, len, ": errno %d (%s)", rpc_createerr.cf_error.re_errno, strerror(rpc_createerr.cf_error.re_errno)); break; default: break; } break; case RPC_SYSTEMERROR: (void)strncat(str, " - ", len - 1); (void)strncat(str, strerror(rpc_createerr.cf_error.re_errno), len - 4); break; case RPC_CANTSEND: case RPC_CANTDECODERES: case RPC_CANTENCODEARGS: case RPC_SUCCESS: case RPC_UNKNOWNPROTO: case RPC_PROGNOTREGISTERED: case RPC_FAILED: case RPC_UNKNOWNHOST: case RPC_CANTDECODEARGS: case RPC_PROCUNAVAIL: case RPC_PROGVERSMISMATCH: case RPC_PROGUNAVAIL: case RPC_AUTHERROR: case RPC_VERSMISMATCH: case RPC_TIMEDOUT: case RPC_CANTRECV: default: break; } str[CLNT_PERROR_BUFLEN - 1] = '\0'; return (str); } void clnt_pcreateerror(const char *s) { if (s == NULL) return; (void)fprintf(stderr, "%s\n", clnt_spcreateerror(s)); } static const char *const auth_errlist[] = { "Authentication OK", /* 0 - AUTH_OK */ "Invalid client credential", /* 1 - AUTH_BADCRED */ "Server rejected credential", /* 2 - AUTH_REJECTEDCRED */ "Invalid client verifier", /* 3 - AUTH_BADVERF */ "Server rejected verifier", /* 4 - AUTH_REJECTEDVERF */ "Client credential too weak", /* 5 - AUTH_TOOWEAK */ "Invalid server verifier", /* 6 - AUTH_INVALIDRESP */ "Failed (unspecified error)" /* 7 - AUTH_FAILED */ }; static char * auth_errmsg(enum auth_stat stat) { unsigned int errnum = stat; if (errnum < (sizeof(auth_errlist) / sizeof(auth_errlist[0]))) /* LINTED interface problem */ return (char *)auth_errlist[errnum]; return (NULL); } <file_sep>/* * Copyright (c) 2012 Linux Box Corporation. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR `AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <config.h> #include <sys/types.h> #include <stdint.h> #include <assert.h> #if !defined(_WIN32) #include <err.h> #endif #include <errno.h> #include <rpc/types.h> #include <reentrant.h> #include <misc/portable.h> #include <signal.h> #include <rpc/xdr.h> #include <rpc/rpc.h> #include <rpc/svc.h> #include "rpc_com.h" #include <misc/rbtree_x.h> #include "clnt_internal.h" #include "rpc_dplx_internal.h" #include "rpc_ctx.h" #define tv_to_ms(tv) (1000 * ((tv)->tv_sec) + (tv)->tv_usec/1000) rpc_ctx_t * alloc_rpc_call_ctx(CLIENT *clnt, rpcproc_t proc, xdrproc_t xdr_args, void *args_ptr, xdrproc_t xdr_results, void *results_ptr, struct timeval timeout) { struct x_vc_data *xd = (struct x_vc_data *)clnt->cl_p1; struct rpc_dplx_rec *rec = xd->rec; rpc_ctx_t *ctx = mem_alloc(sizeof(rpc_ctx_t)); /* potects this */ mutex_init(&ctx->we.mtx, NULL); cond_init(&ctx->we.cv, 0, NULL); /* rec->calls and rbtree protected by (adaptive) mtx */ REC_LOCK(rec); /* XXX we hold the client-fd lock */ ctx->xid = ++(xd->cx.calls.xid); /* some of this looks like overkill; it's here to support future, * fully async calls */ ctx->ctx_u.clnt.clnt = clnt; ctx->ctx_u.clnt.timeout.tv_sec = 0; ctx->ctx_u.clnt.timeout.tv_nsec = 0; timespec_addms(&ctx->ctx_u.clnt.timeout, tv_to_ms(&timeout)); ctx->msg = alloc_rpc_msg(); ctx->flags = 0; /* stash it */ if (opr_rbtree_insert(&xd->cx.calls.t, &ctx->node_k)) { __warnx(TIRPC_DEBUG_FLAG_RPC_CTX, "%s: call ctx insert failed (xid %d client %p)", __func__, ctx->xid, clnt); REC_UNLOCK(rec); mutex_destroy(&ctx->we.mtx); cond_destroy(&ctx->we.cv); mem_free(ctx, sizeof(*ctx)); ctx = NULL; goto out; } REC_UNLOCK(rec); out: return (ctx); } void rpc_ctx_next_xid(rpc_ctx_t *ctx, uint32_t flags) { struct x_vc_data *xd = (struct x_vc_data *)ctx->ctx_u.clnt.clnt->cl_p1; struct rpc_dplx_rec *rec = xd->rec; assert(flags & RPC_CTX_FLAG_LOCKED); REC_LOCK(rec); opr_rbtree_remove(&xd->cx.calls.t, &ctx->node_k); ctx->xid = ++(xd->cx.calls.xid); if (opr_rbtree_insert(&xd->cx.calls.t, &ctx->node_k)) { REC_UNLOCK(rec); __warnx(TIRPC_DEBUG_FLAG_RPC_CTX, "%s: call ctx insert failed (xid %d client %p)", __func__, ctx->xid, ctx->ctx_u.clnt.clnt); goto out; } REC_UNLOCK(rec); out: return; } bool rpc_ctx_xfer_replymsg(struct x_vc_data *xd, struct rpc_msg *msg) { rpc_ctx_t ctx_k, *ctx; struct opr_rbtree_node *nv; rpc_dplx_lock_t *lk = &xd->rec->recv.lock; ctx_k.xid = msg->rm_xid; REC_LOCK(xd->rec); nv = opr_rbtree_lookup(&xd->cx.calls.t, &ctx_k.node_k); if (nv) { ctx = opr_containerof(nv, rpc_ctx_t, node_k); opr_rbtree_remove(&xd->cx.calls.t, &ctx->node_k); free_rpc_msg(ctx->msg); /* free call header */ ctx->msg = msg; /* and stash reply header */ ctx->flags |= RPC_CTX_FLAG_SYNCDONE; REC_UNLOCK(xd->rec); cond_signal(&lk->we.cv); /* XXX we hold lk->we.mtx */ /* now, we must ourselves wait for the other side to run */ while (!(ctx->flags & RPC_CTX_FLAG_ACKSYNC)) cond_wait(&lk->we.cv, &lk->we.mtx); /* ctx-specific signal--indicates we will make no further * references to ctx whatsoever */ mutex_lock(&ctx->we.mtx); ctx->flags &= ~RPC_CTX_FLAG_WAITSYNC; cond_signal(&ctx->we.cv); mutex_unlock(&ctx->we.mtx); return (true); } REC_UNLOCK(xd->rec); return (false); } int rpc_ctx_wait_reply(rpc_ctx_t *ctx, uint32_t flags) { struct x_vc_data *xd = (struct x_vc_data *)ctx->ctx_u.clnt.clnt->cl_p1; struct rpc_dplx_rec *rec = xd->rec; rpc_dplx_lock_t *lk = &rec->recv.lock; struct timespec ts; int code = 0; /* we hold recv channel lock */ ctx->flags |= RPC_CTX_FLAG_WAITSYNC; while (!(ctx->flags & RPC_CTX_FLAG_SYNCDONE)) { (void)clock_gettime(CLOCK_REALTIME_FAST, &ts); timespecadd(&ts, &ctx->ctx_u.clnt.timeout); code = cond_timedwait(&lk->we.cv, &lk->we.mtx, &ts); /* if we timed out, check for xprt destroyed (no more * receives) */ if (code == ETIMEDOUT) { SVCXPRT *xprt = rec->hdl.xprt; uint32_t xp_flags; /* dequeue the call */ REC_LOCK(rec); opr_rbtree_remove(&xd->cx.calls.t, &ctx->node_k); REC_UNLOCK(rec); mutex_lock(&xprt->xp_lock); xp_flags = xprt->xp_flags; mutex_unlock(&xprt->xp_lock); if (xp_flags & SVC_XPRT_FLAG_DESTROYED) { /* XXX should also set error.re_why, but the * facility is not well developed. */ ctx->error.re_status = RPC_TIMEDOUT; } ctx->flags &= ~RPC_CTX_FLAG_WAITSYNC; goto out; } } ctx->flags &= ~RPC_CTX_FLAG_SYNCDONE; /* switch on direction */ switch (ctx->msg->rm_direction) { case REPLY: if (ctx->msg->rm_xid == ctx->xid) return (RPC_SUCCESS); break; case CALL: /* XXX cond transfer control to svc */ /* */ break; default: break; } out: return (code); } void rpc_ctx_ack_xfer(rpc_ctx_t *ctx) { struct x_vc_data *xd = (struct x_vc_data *)ctx->ctx_u.clnt.clnt->cl_p1; rpc_dplx_lock_t *lk = &xd->rec->recv.lock; ctx->flags |= RPC_CTX_FLAG_ACKSYNC; cond_signal(&lk->we.cv); /* XXX we hold lk->we.mtx */ } void free_rpc_call_ctx(rpc_ctx_t *ctx, uint32_t flags) { struct x_vc_data *xd = (struct x_vc_data *)ctx->ctx_u.clnt.clnt->cl_p1; struct rpc_dplx_rec *rec = xd->rec; struct timespec ts; /* wait for commit of any xfer (ctx specific) */ mutex_lock(&ctx->we.mtx); if (ctx->flags & RPC_CTX_FLAG_WAITSYNC) { /* WAITSYNC is already cleared if the call timed out, but it is * incorrect to wait forever */ (void)clock_gettime(CLOCK_REALTIME_FAST, &ts); timespecadd(&ts, &ctx->ctx_u.clnt.timeout); (void)cond_timedwait(&ctx->we.cv, &ctx->we.mtx, &ts); } REC_LOCK(rec); opr_rbtree_remove(&xd->cx.calls.t, &ctx->node_k); /* interlock */ mutex_unlock(&ctx->we.mtx); REC_UNLOCK(rec); if (ctx->msg) free_rpc_msg(ctx->msg); mutex_destroy(&ctx->we.mtx); cond_destroy(&ctx->we.cv); mem_free(ctx, sizeof(*ctx)); } <file_sep>/* * Copyright (c) 2009, Sun Microsystems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - Neither the name of Sun Microsystems, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* * Copyright (c) 1986-1991 by Sun Microsystems Inc. */ /* * Implements a connectionless client side RPC. */ #include <config.h> #include <sys/types.h> #include <sys/socket.h> #include <stdint.h> #include <sys/poll.h> #include <sys/time.h> #include <sys/ioctl.h> #include <rpc/clnt.h> #include <arpa/inet.h> #include <rpc/types.h> #include <misc/portable.h> #include <reentrant.h> #include <rpc/rpc.h> #include <rpc/xdr.h> #include <errno.h> #include <stdlib.h> #include <string.h> #include <signal.h> #include <unistd.h> #include <err.h> #ifdef IP_RECVERR #include <asm/types.h> #include <linux/errqueue.h> #include <sys/uio.h> #endif #include <rpc/types.h> #include <misc/portable.h> #include <reentrant.h> #include <rpc/rpc.h> #include "rpc_com.h" #include "clnt_internal.h" #include "rpc_dplx_internal.h" #include "rpc_ctx.h" #include <rpc/svc_rqst.h> #define MAX_DEFAULT_FDS 20000 static struct clnt_ops *clnt_dg_ops(void); static bool time_not_ok(struct timeval *); static enum clnt_stat clnt_dg_call(CLIENT *, AUTH *, rpcproc_t, xdrproc_t, void *, xdrproc_t, void *, struct timeval); static void clnt_dg_geterr(CLIENT *, struct rpc_err *); static bool clnt_dg_freeres(CLIENT *, xdrproc_t, void *); static bool clnt_dg_ref(CLIENT *, u_int); static void clnt_dg_release(CLIENT *, u_int flags); static void clnt_dg_abort(CLIENT *); static bool clnt_dg_control(CLIENT *, u_int, void *); static void clnt_dg_destroy(CLIENT *); static const char mem_err_clnt_dg[] = "clnt_dg_create: out of memory"; /* * Connection less client creation returns with client handle parameters. * Default options are set, which the user can change using clnt_control(). * fd should be open and bound. * * sendsz and recvsz are the maximum allowable packet sizes that can be * sent and received. Normally they are the same, but they can be * changed to improve the program efficiency and buffer allocation. * If they are 0, use the transport default. * * If svcaddr is NULL, returns NULL. */ CLIENT * clnt_dg_ncreate(int fd, /* open file descriptor */ const struct netbuf *svcaddr, /* servers address */ rpcprog_t program, /* program number */ rpcvers_t version, /* version number */ u_int sendsz, /* buffer recv size */ u_int recvsz /* buffer send size */) { CLIENT *clnt = NULL; /* client handle */ struct cx_data *cx = NULL; /* private data */ struct cu_data *cu = NULL; struct timespec now; struct rpc_msg call_msg; struct __rpc_sockinfo si; int one = 1; if (svcaddr == NULL) { rpc_createerr.cf_stat = RPC_UNKNOWNADDR; return (NULL); } if (!__rpc_fd2sockinfo(fd, &si)) { rpc_createerr.cf_stat = RPC_TLIERROR; rpc_createerr.cf_error.re_errno = 0; return (NULL); } /* * Find the receive and the send size */ sendsz = __rpc_get_t_size(si.si_af, si.si_proto, (int)sendsz); recvsz = __rpc_get_t_size(si.si_af, si.si_proto, (int)recvsz); if ((sendsz == 0) || (recvsz == 0)) { rpc_createerr.cf_stat = RPC_TLIERROR; /* XXX */ rpc_createerr.cf_error.re_errno = 0; return (NULL); } clnt = mem_alloc(sizeof(CLIENT)); mutex_init(&clnt->cl_lock, NULL); clnt->cl_flags = CLNT_FLAG_NONE; /* * Should be multiple of 4 for XDR. */ sendsz = ((sendsz + 3) / 4) * 4; recvsz = ((recvsz + 3) / 4) * 4; cx = alloc_cx_data(CX_DG_DATA, sendsz, recvsz); if (cx == NULL) goto err1; cu = CU_DATA(cx); (void)memcpy(&cu->cu_raddr, svcaddr->buf, (size_t) svcaddr->len); cu->cu_rlen = svcaddr->len; /* Other values can also be set through clnt_control() */ cu->cu_wait.tv_sec = 15; /* heuristically chosen */ cu->cu_wait.tv_usec = 0; cu->cu_total.tv_sec = -1; cu->cu_total.tv_usec = -1; cu->cu_sendsz = sendsz; cu->cu_recvsz = recvsz; cu->cu_async = false; cu->cu_connect = false; cu->cu_connected = false; (void)clock_gettime(CLOCK_MONOTONIC_FAST, &now); call_msg.rm_xid = __RPC_GETXID(&now); /* XXX? */ call_msg.rm_call.cb_prog = program; call_msg.rm_call.cb_vers = version; xdrmem_create(&(cu->cu_outxdrs), cu->cu_outbuf, sendsz, XDR_ENCODE); if (!xdr_callhdr(&(cu->cu_outxdrs), &call_msg)) { rpc_createerr.cf_stat = RPC_CANTENCODEARGS; /* XXX */ rpc_createerr.cf_error.re_errno = 0; goto err2; } cu->cu_xdrpos = XDR_GETPOS(&(cu->cu_outxdrs)); /* XXX fvdl - do we still want this? */ #if 0 (void)bindresvport_sa(fd, (struct sockaddr *)svcaddr->buf); #endif #ifdef IP_RECVERR { int on = 1; (void) setsockopt(fd, SOL_IP, IP_RECVERR, &on, sizeof(on)); } #endif ioctl(fd, FIONBIO, (char *)(void *)&one); /* * By default, closeit is always false. It is users responsibility * to do a close on it, else the user may use clnt_control * to let clnt_destroy do it for him/her. */ cu->cu_closeit = false; cu->cu_fd = fd; clnt->cl_ops = clnt_dg_ops(); clnt->cl_p1 = cx; clnt->cl_p2 = rpc_dplx_lookup_rec(fd, RPC_DPLX_LKP_FLAG_NONE); /*ref+1*/ clnt->cl_tp = NULL; clnt->cl_netid = NULL; return (clnt); err1: __warnx(TIRPC_DEBUG_FLAG_CLNT_DG, mem_err_clnt_dg); rpc_createerr.cf_stat = RPC_SYSTEMERROR; rpc_createerr.cf_error.re_errno = errno; err2: mem_free(clnt, sizeof(CLIENT)); if (cx) free_cx_data(cx); return (NULL); } static enum clnt_stat clnt_dg_call(CLIENT *clnt, /* client handle */ AUTH *auth, /* auth handle */ rpcproc_t proc, /* procedure number */ xdrproc_t xargs, /* xdr routine for args */ void *argsp, /* pointer to args */ xdrproc_t xresults, /* xdr routine for results */ void *resultsp, /* pointer to results */ struct timeval utimeout /* seconds to wait before giving up */) { struct cu_data *cu = CU_DATA((struct cx_data *)clnt->cl_p1); XDR *xdrs; size_t outlen = 0; struct rpc_msg reply_msg; XDR reply_xdrs; bool ok; int nrefreshes = 2; /* number of times to refresh cred */ struct timeval timeout; struct pollfd fd; int total_time, nextsend_time, tv = 0; struct sockaddr *sa; socklen_t __attribute__ ((unused)) inlen, salen; ssize_t recvlen = 0; u_int32_t xid, inval, outval; bool slocked = false; bool rlocked = false; bool once = true; outlen = 0; rpc_dplx_slc(clnt); slocked = true; if (cu->cu_total.tv_usec == -1) timeout = utimeout; /* use supplied timeout */ else timeout = cu->cu_total; /* use default timeout */ total_time = timeout.tv_sec * 1000 + timeout.tv_usec / 1000; nextsend_time = cu->cu_wait.tv_sec * 1000 + cu->cu_wait.tv_usec / 1000; if (cu->cu_connect && !cu->cu_connected) { if (connect (cu->cu_fd, (struct sockaddr *)&cu->cu_raddr, cu->cu_rlen) < 0) { cu->cu_error.re_errno = errno; cu->cu_error.re_status = RPC_CANTSEND; goto out; } cu->cu_connected = 1; } if (cu->cu_connected) { sa = NULL; salen = 0; } else { sa = (struct sockaddr *)&cu->cu_raddr; salen = cu->cu_rlen; } /* Clean up in case the last call ended in a longjmp(3) call. */ call_again: if (!slocked) { rpc_dplx_slc(clnt); slocked = true; } xdrs = &(cu->cu_outxdrs); if (cu->cu_async == true && xargs == NULL) goto get_reply; xdrs->x_op = XDR_ENCODE; XDR_SETPOS(xdrs, cu->cu_xdrpos); /* * the transaction is the first thing in the out buffer * XXX Yes, and it's in network byte order, so we should to * be careful when we increment it, shouldn't we. */ xid = ntohl(*(u_int32_t *) (void *)(cu->cu_outbuf)); xid++; *(u_int32_t *) (void *)(cu->cu_outbuf) = htonl(xid); if ((!XDR_PUTINT32(xdrs, (int32_t *) &proc)) || (!AUTH_MARSHALL(auth, xdrs)) || (!AUTH_WRAP(auth, xdrs, xargs, argsp))) { cu->cu_error.re_status = RPC_CANTENCODEARGS; goto out; } outlen = (size_t) XDR_GETPOS(xdrs); send_again: nextsend_time = cu->cu_wait.tv_sec * 1000 + cu->cu_wait.tv_usec / 1000; if (sendto(cu->cu_fd, cu->cu_outbuf, outlen, 0, sa, salen) != outlen) { cu->cu_error.re_errno = errno; cu->cu_error.re_status = RPC_CANTSEND; goto out; } get_reply: /* * sub-optimal code appears here because we have * some clock time to spare while the packets are in flight. * (We assume that this is actually only executed once.) */ rpc_dplx_suc(clnt); slocked = false; rpc_dplx_rlc(clnt); rlocked = true; reply_msg.acpted_rply.ar_verf = _null_auth; reply_msg.acpted_rply.ar_results.where = NULL; reply_msg.acpted_rply.ar_results.proc = (xdrproc_t) xdr_void; fd.fd = cu->cu_fd; fd.events = POLLIN; fd.revents = 0; while ((total_time > 0) || once) { tv = total_time < nextsend_time ? total_time : nextsend_time; once = false; switch (poll(&fd, 1, tv)) { case 0: total_time -= tv; rpc_dplx_ruc(clnt); rlocked = false; if (total_time <= 0) { cu->cu_error.re_status = RPC_TIMEDOUT; goto out; } goto send_again; case -1: if (errno == EINTR) continue; cu->cu_error.re_status = RPC_CANTRECV; cu->cu_error.re_errno = errno; goto out; } break; } #ifdef IP_RECVERR if (fd.revents & POLLERR) { struct msghdr msg; struct cmsghdr *cmsg; struct sock_extended_err *e; struct sockaddr_in err_addr; struct sockaddr_in *sin = (struct sockaddr_in *)&cu->cu_raddr; struct iovec iov; char *cbuf = (char *)alloca(outlen + 256); int ret; iov.iov_base = cbuf + 256; iov.iov_len = outlen; msg.msg_name = (void *)&err_addr; msg.msg_namelen = sizeof(err_addr); msg.msg_iov = &iov; msg.msg_iovlen = 1; msg.msg_flags = 0; msg.msg_control = cbuf; msg.msg_controllen = 256; ret = recvmsg(cu->cu_fd, &msg, MSG_ERRQUEUE); if (ret >= 0 && memcmp(cbuf + 256, cu->cu_outbuf, ret) == 0 && (msg.msg_flags & MSG_ERRQUEUE) && ((msg.msg_namelen == 0 && ret >= 12) || (msg.msg_namelen == sizeof(err_addr) && err_addr.sin_family == AF_INET && memcmp(&err_addr.sin_addr, &sin->sin_addr, sizeof(err_addr.sin_addr)) == 0 && err_addr.sin_port == sin->sin_port))) for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg)) if ((cmsg->cmsg_level == SOL_IP) && (cmsg->cmsg_type == IP_RECVERR)) { e = (struct sock_extended_err *) CMSG_DATA(cmsg); cu->cu_error.re_errno = e->ee_errno; cu->cu_error.re_status = RPC_CANTRECV; } } #endif /* We have some data now */ do { recvlen = recvfrom(cu->cu_fd, cu->cu_inbuf, cu->cu_recvsz, 0, NULL, NULL); } while (recvlen < 0 && errno == EINTR); if (recvlen < 0 && errno != EWOULDBLOCK) { cu->cu_error.re_errno = errno; cu->cu_error.re_status = RPC_CANTRECV; goto out; } if (recvlen < sizeof(u_int32_t)) { total_time -= tv; rpc_dplx_ruc(clnt); rlocked = false; goto send_again; } if (cu->cu_async == true) inlen = (socklen_t) recvlen; else { memcpy(&inval, cu->cu_inbuf, sizeof(u_int32_t)); memcpy(&outval, cu->cu_outbuf, sizeof(u_int32_t)); if (inval != outval) { total_time -= tv; rpc_dplx_ruc(clnt); rlocked = false; goto send_again; } inlen = (socklen_t) recvlen; } /* * now decode and validate the response */ xdrmem_create(&reply_xdrs, cu->cu_inbuf, (u_int) recvlen, XDR_DECODE); ok = xdr_replymsg(&reply_xdrs, &reply_msg); /* XDR_DESTROY(&reply_xdrs); save a few cycles on noop destroy */ if (ok) { if ((reply_msg.rm_reply.rp_stat == MSG_ACCEPTED) && (reply_msg.acpted_rply.ar_stat == SUCCESS)) cu->cu_error.re_status = RPC_SUCCESS; else _seterr_reply(&reply_msg, &(cu->cu_error)); if (cu->cu_error.re_status == RPC_SUCCESS) { if (!AUTH_VALIDATE (auth, &reply_msg.acpted_rply.ar_verf)) { cu->cu_error.re_status = RPC_AUTHERROR; cu->cu_error.re_why = AUTH_INVALIDRESP; } else if (!AUTH_UNWRAP (auth, &reply_xdrs, xresults, resultsp)) { if (cu->cu_error.re_status == RPC_SUCCESS) cu->cu_error.re_status = RPC_CANTDECODERES; } if (reply_msg.acpted_rply.ar_verf.oa_base != NULL) { xdrs->x_op = XDR_FREE; (void)xdr_opaque_auth(xdrs, &(reply_msg.acpted_rply. ar_verf)); } } /* end successful completion */ /* * If unsuccesful AND error is an authentication error * then refresh credentials and try again, else break */ else if (cu->cu_error.re_status == RPC_AUTHERROR) /* maybe our credentials need to be refreshed ... */ if (nrefreshes > 0 && AUTH_REFRESH(auth, &reply_msg)) { nrefreshes--; rpc_dplx_ruc(clnt); rlocked = false; goto call_again; } /* end of unsuccessful completion */ } /* end of valid reply message */ else cu->cu_error.re_status = RPC_CANTDECODERES; out: if (slocked) rpc_dplx_suc(clnt); if (rlocked) rpc_dplx_ruc(clnt); return (cu->cu_error.re_status); } static void clnt_dg_geterr(CLIENT *clnt, struct rpc_err *errp) { struct cu_data *cu = CU_DATA((struct cx_data *)clnt->cl_p1); *errp = cu->cu_error; } static bool clnt_dg_freeres(CLIENT *clnt, xdrproc_t xdr_res, void *res_ptr) { struct cu_data *cu = CU_DATA((struct cx_data *)clnt->cl_p1); XDR *xdrs; sigset_t mask, newmask; bool dummy = 0; /* XXX guard against illegal invocation from libc (will fix) */ if (!xdr_res) goto out; xdrs = &(cu->cu_outxdrs); /* XXX outxdrs? */ /* Handle our own signal mask here, the signal section is * larger than the wait (not 100% clear why) */ sigfillset(&newmask); thr_sigsetmask(SIG_SETMASK, &newmask, &mask); /* barrier recv channel */ rpc_dplx_rwc(clnt, rpc_flag_clear); xdrs->x_op = XDR_FREE; if (xdr_res) dummy = (*xdr_res) (xdrs, res_ptr); thr_sigsetmask(SIG_SETMASK, &mask, NULL); /* signal recv channel */ rpc_dplx_rsc(clnt, RPC_DPLX_FLAG_NONE); out: return (dummy); } static bool clnt_dg_ref(CLIENT *clnt, u_int flags) { return (true); } static void clnt_dg_release(CLIENT *clnt, u_int flags) { } /*ARGSUSED*/ static void clnt_dg_abort(CLIENT *h) { } static bool clnt_dg_control(CLIENT *clnt, u_int request, void *info) { struct cu_data *cu = CU_DATA((struct cx_data *)clnt->cl_p1); struct netbuf *addr; bool rslt = true; /* always take recv lock first, if taking both locks together */ rpc_dplx_rlc(clnt); rpc_dplx_slc(clnt); switch (request) { case CLSET_FD_CLOSE: cu->cu_closeit = true; rslt = true; goto unlock; case CLSET_FD_NCLOSE: cu->cu_closeit = false; rslt = true; goto unlock; } /* for other requests which use info */ if (info == NULL) { rslt = false; goto unlock; } switch (request) { case CLSET_TIMEOUT: if (time_not_ok((struct timeval *)info)) { rslt = false; goto unlock; } cu->cu_total = *(struct timeval *)info; break; case CLGET_TIMEOUT: *(struct timeval *)info = cu->cu_total; break; case CLGET_SERVER_ADDR: /* Give him the fd address */ /* Now obsolete. Only for backward compatibility */ (void)memcpy(info, &cu->cu_raddr, (size_t) cu->cu_rlen); break; case CLSET_RETRY_TIMEOUT: if (time_not_ok((struct timeval *)info)) { rslt = false; goto unlock; } cu->cu_wait = *(struct timeval *)info; break; case CLGET_RETRY_TIMEOUT: *(struct timeval *)info = cu->cu_wait; break; case CLGET_FD: *(int *)info = cu->cu_fd; break; case CLGET_SVC_ADDR: addr = (struct netbuf *)info; addr->buf = &cu->cu_raddr; addr->len = cu->cu_rlen; addr->maxlen = sizeof(cu->cu_raddr); break; case CLSET_SVC_ADDR: /* set to new address */ addr = (struct netbuf *)info; if (addr->len < sizeof(cu->cu_raddr)) { rslt = false; goto unlock; } (void)memcpy(&cu->cu_raddr, addr->buf, addr->len); cu->cu_rlen = addr->len; break; case CLGET_XID: /* * use the knowledge that xid is the * first element in the call structure *. * This will get the xid of the PREVIOUS call */ *(u_int32_t *) info = ntohl(*(u_int32_t *) (void *)cu->cu_outbuf); break; case CLSET_XID: /* This will set the xid of the NEXT call */ *(u_int32_t *) (void *)cu->cu_outbuf = htonl(*(u_int32_t *) info - 1); /* decrement by 1 as clnt_dg_call() increments once */ break; case CLGET_VERS: /* * This RELIES on the information that, in the call body, * the version number field is the fifth field from the * begining of the RPC header. MUST be changed if the * call_struct is changed */ *(u_int32_t *) info = ntohl(*(u_int32_t *) (void *) (cu->cu_outbuf + 4 * BYTES_PER_XDR_UNIT)); break; case CLSET_VERS: *(u_int32_t *) (void *)(cu->cu_outbuf + 4 * BYTES_PER_XDR_UNIT) = htonl(*(u_int32_t *) info); break; case CLGET_PROG: /* * This RELIES on the information that, in the call body, * the program number field is the fourth field from the * begining of the RPC header. MUST be changed if the * call_struct is changed */ *(u_int32_t *) info = ntohl(*(u_int32_t *) (void *) (cu->cu_outbuf + 3 * BYTES_PER_XDR_UNIT)); break; case CLSET_PROG: *(u_int32_t *) (void *)(cu->cu_outbuf + 3 * BYTES_PER_XDR_UNIT) = htonl(*(u_int32_t *) info); break; case CLSET_ASYNC: cu->cu_async = *(int *)info; break; case CLSET_CONNECT: cu->cu_connect = *(int *)info; break; default: break; } unlock: rpc_dplx_ruc(clnt); rpc_dplx_suc(clnt); return (rslt); } static void clnt_dg_destroy(CLIENT *clnt) { struct cx_data *cx = (struct cx_data *)clnt->cl_p1; struct rpc_dplx_rec *rec = (struct rpc_dplx_rec *)clnt->cl_p2; int cu_fd = CU_DATA(cx)->cu_fd; sigset_t mask, newmask; /* Handle our own signal mask here, the signal section is * larger than the wait (not 100% clear why) */ sigfillset(&newmask); thr_sigsetmask(SIG_SETMASK, &newmask, &mask); /* barrier both channels */ rpc_dplx_swc(clnt, rpc_flag_clear); rpc_dplx_rwc(clnt, rpc_flag_clear); if (CU_DATA(cx)->cu_closeit) (void)close(cu_fd); XDR_DESTROY(&(CU_DATA(cx)->cu_outxdrs)); /* signal both channels */ rpc_dplx_ssc(clnt, RPC_DPLX_FLAG_NONE); rpc_dplx_rsc(clnt, RPC_DPLX_FLAG_NONE); /* release */ rpc_dplx_unref(rec, RPC_DPLX_FLAG_NONE); free_cx_data(cx); if (clnt->cl_netid && clnt->cl_netid[0]) mem_free(clnt->cl_netid, strlen(clnt->cl_netid) + 1); if (clnt->cl_tp && clnt->cl_tp[0]) mem_free(clnt->cl_tp, strlen(clnt->cl_tp) + 1); mem_free(clnt, sizeof(CLIENT)); thr_sigsetmask(SIG_SETMASK, &mask, NULL); } static struct clnt_ops * clnt_dg_ops(void) { static struct clnt_ops ops; extern mutex_t ops_lock; /* XXXX does it need to be extern? */ sigset_t mask; sigset_t newmask; /* VARIABLES PROTECTED BY ops_lock: ops */ sigfillset(&newmask); thr_sigsetmask(SIG_SETMASK, &newmask, &mask); mutex_lock(&ops_lock); if (ops.cl_call == NULL) { ops.cl_call = clnt_dg_call; ops.cl_abort = clnt_dg_abort; ops.cl_geterr = clnt_dg_geterr; ops.cl_freeres = clnt_dg_freeres; ops.cl_ref = clnt_dg_ref; ops.cl_release = clnt_dg_release; ops.cl_destroy = clnt_dg_destroy; ops.cl_control = clnt_dg_control; } mutex_unlock(&ops_lock); thr_sigsetmask(SIG_SETMASK, &mask, NULL); return (&ops); } /* * Make sure that the time is not garbage. -1 value is allowed. */ static bool time_not_ok(struct timeval *t) { return (t->tv_sec < -1 || t->tv_sec > 100000000 || t->tv_usec < -1 || t->tv_usec > 1000000); } <file_sep>/* $NetBSD: svc_dg.h,v 1.1 2000/06/02 23:11:16 fvdl Exp $ */ /* $FreeBSD: src/include/rpc/svc_dg.h,v 1.1 2001/03/19 12:49:47 * alfred Exp $ */ /* * Copyright (c) 2009, Sun Microsystems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - Neither the name of Sun Microsystems, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* * XXX - this file exists only so that the rpcbind code can pull it in. * This should go away. It should only be include by svc_dg.c and * rpcb_svc_com.c in the rpcbind code. */ #ifndef _TIRPC_SVC_DG_H_ #define _TIRPC_SVC_DG_H_ #include <sys/socket.h> #include <netinet/in.h> /* * The following union is defined just to use SVC_CMSG_LEN macro for an * array length. _GNU_SOURCE must be defined to get in6_pktinfo * declaration! */ union in_pktinfo_u { struct in_pktinfo x; struct in6_pktinfo y; }; #define SVC_CMSG_LEN CMSG_SPACE(sizeof(union in_pktinfo_u)) /* * kept in xprt->xp_p2 */ struct svc_dg_data { /* XXX: optbuf should be the first field, used by ti_opts.c code */ size_t su_iosz; /* size of send.recv buffer */ u_int32_t su_xid; /* transaction id */ XDR su_xdrs; /* XDR handle */ char su_verfbody[MAX_AUTH_BYTES]; /* verifier body */ void *su_cache; /* cached data, NULL if none */ struct msghdr su_msghdr; /* msghdr received from clnt */ unsigned char su_cmsg[SVC_CMSG_LEN]; /* cmsghdr received from clnt */ }; #define __rpcb_get_dg_xidp(x) (&((struct svc_dg_data *)(x)->xp_p2)->su_xid) #endif <file_sep>/* $NetBSD: pmap_clnt.h,v 1.9 2000/06/02 22:57:55 fvdl Exp $ */ /* * Copyright (c) 2009, Sun Microsystems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - Neither the name of Sun Microsystems, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * from: @(#)pmap_clnt.h 1.11 88/02/08 SMI * from: @(#)pmap_clnt.h 2.1 88/07/29 4.0 RPCSRC * $FreeBSD: src/include/rpc/pmap_clnt.h,v 1.14 2002/04/28 15:18:45 des Exp $ */ /* * pmap_clnt.h * Supplies C routines to get to portmap services. * * Copyright (C) 1984, Sun Microsystems, Inc. */ /* * Usage: * success = pmap_set(program, version, protocol, port); * success = pmap_unset(program, version); * port = pmap_getport(address, program, version, protocol); * head = pmap_getmaps(address); * clnt_stat = pmap_rmtcall(address, program, version, procedure, * xdrargs, argsp, xdrres, resp, tout, port_ptr) * (works for udp only.) * clnt_stat = clnt_broadcast(program, version, procedure, * xdrargs, argsp, xdrres, resp, eachresult) * (like pmap_rmtcall, except the call is broadcasted to all * locally connected nets. For each valid response received, * the procedure eachresult is called. Its form is: * done = eachresult(resp, raddr) * bool done; * caddr_t resp; * struct sockaddr_in raddr; * where resp points to the results of the call and raddr is the * address if the responder to the broadcast. */ #ifndef _RPC_PMAP_CLNT_H_ #define _RPC_PMAP_CLNT_H_ #include <sys/cdefs.h> __BEGIN_DECLS extern bool pmap_set(u_long, u_long, int, int); extern bool pmap_unset(u_long, u_long); extern struct pmaplist *pmap_getmaps(struct sockaddr_in *); extern enum clnt_stat pmap_rmtcall(struct sockaddr_in *, u_long, u_long, u_long, xdrproc_t, caddr_t, xdrproc_t, caddr_t, struct timeval, u_long *); extern enum clnt_stat clnt_broadcast(u_long, u_long, u_long, xdrproc_t, void *, xdrproc_t, void *, resultproc_t); extern u_short pmap_getport(struct sockaddr_in *, u_long, u_long, u_int); __END_DECLS #endif /* !_RPC_PMAP_CLNT_H_ */ <file_sep>/* * Copyright (c) 2009, Sun Microsystems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - Neither the name of Sun Microsystems, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* * pmap_rmt.c * Client interface to pmap rpc service. * remote call and broadcast service * * Copyright (C) 1984, Sun Microsystems, Inc. */ #include <config.h> #include <sys/types.h> #include <sys/ioctl.h> #include <sys/poll.h> #include <sys/socket.h> #include <net/if.h> #include <netinet/in.h> #include <arpa/inet.h> #include <assert.h> #include <err.h> #include <errno.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <rpc/rpc.h> #include <rpc/pmap_prot.h> #include <rpc/pmap_clnt.h> #include <rpc/pmap_rmt.h> /* For the clnttcp_create function * #include <clnt_soc.h> */ static const struct timeval timeout = { 3, 0 }; /* * pmapper remote-call-service interface. * This routine is used to call the pmapper remote call service * which will look up a service program in the port maps, and then * remotely call that routine with the given parameters. This allows * programs to do a lookup and call in one step. */ enum clnt_stat pmap_rmtcall(struct sockaddr_in *addr, u_long prog, u_long vers, u_long proc, xdrproc_t xdrargs, caddr_t argsp, xdrproc_t xdrres, caddr_t resp, struct timeval tout, u_long *port_ptr) { int sock = -1; CLIENT *client; AUTH *auth; struct rmtcallargs a; struct rmtcallres r; enum clnt_stat stat; assert(addr != NULL); assert(port_ptr != NULL); addr->sin_port = htons(PMAPPORT); client = clntudp_ncreate(addr, PMAPPROG, PMAPVERS, timeout, &sock); if (client != NULL) { auth = authnone_create(); a.prog = prog; a.vers = vers; a.proc = proc; a.args_ptr = argsp; a.xdr_args = xdrargs; r.port_ptr = port_ptr; r.results_ptr = resp; r.xdr_results = xdrres; stat = CLNT_CALL(client, auth, (rpcproc_t) PMAPPROC_CALLIT, (xdrproc_t) xdr_rmtcall_args, &a, (xdrproc_t) xdr_rmtcallres, &r, tout); CLNT_DESTROY(client); } else { stat = RPC_FAILED; } addr->sin_port = 0; return (stat); } /* * XDR remote call arguments * written for XDR_ENCODE direction only */ bool xdr_rmtcall_args(XDR *xdrs, struct rmtcallargs *cap) { u_int lenposition, argposition, position; assert(xdrs != NULL); assert(cap != NULL); if (xdr_u_long(xdrs, &(cap->prog)) && xdr_u_long(xdrs, &(cap->vers)) && xdr_u_long(xdrs, &(cap->proc))) { lenposition = XDR_GETPOS(xdrs); if (!xdr_u_long(xdrs, &(cap->arglen))) return (false); argposition = XDR_GETPOS(xdrs); if (!(*(cap->xdr_args)) (xdrs, cap->args_ptr)) return (false); position = XDR_GETPOS(xdrs); cap->arglen = (u_long) position - (u_long) argposition; XDR_SETPOS(xdrs, lenposition); if (!xdr_u_long(xdrs, &(cap->arglen))) return (false); XDR_SETPOS(xdrs, position); return (true); } return (false); } /* * XDR remote call results * written for XDR_DECODE direction only */ bool xdr_rmtcallres(XDR *xdrs, struct rmtcallres *crp) { caddr_t port_ptr; assert(xdrs != NULL); assert(crp != NULL); port_ptr = (caddr_t) (void *)crp->port_ptr; if (xdr_reference (xdrs, &port_ptr, sizeof(u_long), (xdrproc_t) xdr_u_long) && xdr_u_long(xdrs, &crp->resultslen)) { crp->port_ptr = (u_long *) (void *)port_ptr; return ((*(crp->xdr_results)) (xdrs, crp->results_ptr)); } return (false); } <file_sep>/* * Copyright (c) 2013 Linux Box Corporation. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR `AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <sys/cdefs.h> #include <sys/socket.h> #include <sys/types.h> #include <sys/param.h> #include <sys/poll.h> #include <sys/un.h> #include <sys/time.h> #include <sys/uio.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <assert.h> #include <err.h> #include <errno.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <signal.h> #include <misc/timespec.h> #include <rpc/types.h> #include <misc/portable.h> #include <rpc/rpc.h> #include <rpc/svc.h> #include <rpc/svc_auth.h> #include <intrinsic.h> #include "rpc_com.h" #include "clnt_internal.h" #include "svc_internal.h" #include "svc_xprt.h" #include "rpc_dplx_internal.h" #include "rpc_ctx.h" #include <rpc/svc_rqst.h> #include <rpc/xdr_inrec.h> #include <rpc/xdr_ioq.h> #include <getpeereid.h> #include <misc/opr.h> #include "svc_ioq.h" static inline void cfconn_set_dead(SVCXPRT *xprt, struct x_vc_data *xd) { mutex_lock(&xprt->xp_lock); xd->sx.strm_stat = XPRT_DIED; mutex_unlock(&xprt->xp_lock); } #define LAST_FRAG ((u_int32_t)(1 << 31)) #define MAXALLOCA (256) static inline void ioq_flushv(SVCXPRT *xprt, struct x_vc_data *xd, struct xdr_ioq *xioq) { struct iovec *iov, *tiov, *wiov; struct poolq_entry *have; struct xdr_ioq_uv *data; ssize_t result; u_int32_t frag_header; u_int32_t fbytes; u_int32_t remaining = 0; u_int32_t vsize = (xioq->ioq_uv.uvqh.qcount + 1) * sizeof(struct iovec); int iw = 0; int ix = 1; if (unlikely(vsize > MAXALLOCA)) { iov = mem_alloc(vsize); } else { iov = alloca(vsize); } wiov = iov; /* position at initial fragment header */ /* update the most recent data length, just in case */ xdr_tail_update(xioq->xdrs); /* build list after initial fragment header (ix = 1 above) */ TAILQ_FOREACH(have, &(xioq->ioq_uv.uvqh.qh), q) { data = IOQ_(have); tiov = iov + ix; tiov->iov_base = data->v.vio_head; tiov->iov_len = ioquv_length(data); remaining += tiov->iov_len; ix++; } while (remaining > 0) { if (iw == 0) { /* new fragment header, determine last iov */ fbytes = 0; for (tiov = &wiov[++iw]; (tiov < &iov[ix]) && (iw < __svc_maxiov); ++tiov, ++iw) { fbytes += tiov->iov_len; /* check for fragment value overflow */ /* never happens, see ganesha FSAL_MAXIOSIZE */ if (unlikely(fbytes >= LAST_FRAG)) { fbytes -= tiov->iov_len; break; } } /* for */ /* fragment length doesn't include fragment header */ if (&wiov[iw] < &iov[ix]) { frag_header = htonl((u_int32_t) (fbytes)); } else { frag_header = htonl((u_int32_t) (fbytes | LAST_FRAG)); } wiov->iov_base = &(frag_header); wiov->iov_len = sizeof(u_int32_t); /* writev return includes fragment header */ remaining += sizeof(u_int32_t); fbytes += sizeof(u_int32_t); } /* blocking write */ result = writev(xprt->xp_fd, wiov, iw); remaining -= result; if (result == fbytes) { wiov += iw - 1; iw = 0; continue; } if (unlikely(result < 0)) { __warnx(TIRPC_DEBUG_FLAG_ERROR, "%s() writev failed (%d)\n", __func__, errno); cfconn_set_dead(xprt, xd); break; } fbytes -= result; /* rare? writev underrun? (assume never overrun) */ for (tiov = wiov; iw > 0; ++tiov, --iw) { if (tiov->iov_len > result) { tiov->iov_len -= result; tiov->iov_base += result; wiov = tiov; break; } else { result -= tiov->iov_len; } } /* for */ } /* while */ if (unlikely(vsize > MAXALLOCA)) { mem_free(iov, vsize); } } static void svc_ioq_callback(struct work_pool_entry *wpe) { struct x_vc_data *xd = (struct x_vc_data *)wpe; SVCXPRT *xprt = (SVCXPRT *)wpe->arg; struct poolq_entry *have; struct xdr_ioq *xioq; /* qmutex more fine grained than xp_lock */ for (;;) { mutex_lock(&xd->shared.ioq.qmutex); have = TAILQ_FIRST(&xd->shared.ioq.qh); if (unlikely(!have)) { xd->shared.active = false; mutex_unlock(&xd->shared.ioq.qmutex); SVC_RELEASE(xprt, SVC_RELEASE_FLAG_NONE); return; } TAILQ_REMOVE(&xd->shared.ioq.qh, have, q); (xd->shared.ioq.qcount)--; /* do i/o unlocked */ mutex_unlock(&xd->shared.ioq.qmutex); xioq = _IOQ(have); if (svc_work_pool.params.thrd_max && !(xprt->xp_flags & SVC_XPRT_FLAG_DESTROYED)) { /* all systems are go! */ ioq_flushv(xprt, xd, xioq); } XDR_DESTROY(xioq->xdrs); } return; } void svc_ioq_append(SVCXPRT *xprt, struct x_vc_data *xd, XDR *xdrs) { if (unlikely(!svc_work_pool.params.thrd_max || (xprt->xp_flags & SVC_XPRT_FLAG_DESTROYED))) { /* discard */ XDR_DESTROY(xdrs); return; } /* qmutex more fine grained than xp_lock */ mutex_lock(&xd->shared.ioq.qmutex); (xd->shared.ioq.qcount)++; TAILQ_INSERT_TAIL(&xd->shared.ioq.qh, &(XIOQ(xdrs)->ioq_s), q); if (!xd->shared.active) { xd->shared.active = true; xd->wpe.fun = svc_ioq_callback; xd->wpe.arg = xprt; mutex_unlock(&xd->shared.ioq.qmutex); SVC_REF(xprt, SVC_REF_FLAG_NONE); work_pool_submit(&svc_work_pool, &xd->wpe); } else { /* queuing multiple output requests for worker efficiency */ mutex_unlock(&xd->shared.ioq.qmutex); } } <file_sep>prefix=@prefix@ exec_prefix=@exec_prefix@ libdir=@libdir@ includedir=@includedir@ Name: libntirpc Description: New Transport Independent RPC Library Requires: Version: @NTIRPC_VERSION@ Libs: -L@libdir@ -lintirpc Cflags: -I@includedir@/ntirpc <file_sep>/* * Copyright (c) 2009, Sun Microsystems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - Neither the name of Sun Microsystems, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* * Copyright (c) 1988 by Sun Microsystems, Inc. */ /* * auth_des.c, client-side implementation of DES authentication */ #ifndef __APPLE__ #include <config.h> #include <pthread.h> #include <reentrant.h> #include <err.h> #include <errno.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <sys/cdefs.h> #include <rpc/des_crypt.h> #include <rpc/types.h> #include <rpc/auth.h> #include <rpc/auth_des.h> #include <rpc/clnt.h> #include <rpc/xdr.h> #include <sys/socket.h> #undef NIS #include <rpcsvc/nis.h> #if defined(LIBC_SCCS) && !defined(lint) #endif #include <sys/cdefs.h> #define USEC_PER_SEC 1000000 #define RTIME_TIMEOUT 5 /* seconds to wait for sync */ #define AUTH_PRIVATE(auth) ((struct ad_private *) (auth)->ah_private) #define ATTEMPT(xdr_op) if (!(xdr_op)) return (false) bool xdr_authdes_cred(XDR *, struct authdes_cred *); bool xdr_authdes_verf(XDR *, struct authdes_verf *); bool __rpc_get_time_offset(struct timeval *, nis_server *, char *, char **, char **); /* * DES authenticator operations vector */ static void authdes_nextverf(AUTH *); static bool authdes_marshal(AUTH *, XDR *); static bool authdes_validate(AUTH *, struct opaque_auth *); static bool authdes_refresh(AUTH *, void *); static void authdes_destroy(AUTH *); static struct auth_ops *authdes_ops(void); /* * This struct is pointed to by the ah_private field of an "AUTH *" */ struct ad_private { char *ad_fullname; /* client's full name */ u_int ad_fullnamelen; /* length of name, rounded up */ char *ad_servername; /* server's full name */ u_int ad_servernamelen; /* length of name, rounded up */ u_int ad_window; /* client specified window */ bool ad_dosync; /* synchronize? */ struct netbuf ad_syncaddr; /* remote host to synch with */ char *ad_timehost; /* remote host to synch with */ struct timeval ad_timediff; /* server's time - client's time */ u_int ad_nickname; /* server's nickname for client */ struct authdes_cred ad_cred; /* storage for credential */ struct authdes_verf ad_verf; /* storage for verifier */ struct timeval ad_timestamp; /* timestamp sent */ des_block ad_xkey; /* encrypted conversation key */ u_char ad_pkey[1024]; /* Server's actual public key */ char *ad_netid; /* Timehost netid */ char *ad_uaddr; /* Timehost uaddr */ nis_server *ad_nis_srvr; /* NIS+ server struct */ }; AUTH * authdes_pk_nseccreate(const char *, netobj *, u_int, const char *, const des_block *, nis_server *); /* * documented version of authdes_nseccreate */ /* servername: network name of server win: time to live timehost: optional hostname to sync with ckey: optional conversation key to use */ AUTH * authdes_nseccreate(const char *servername, const u_int win, const char *timehost, const des_block *ckey) { u_char pkey_data[1024]; netobj pkey; AUTH *dummy; if (!getpublickey(servername, (char *)pkey_data)) { __warnx(TIRPC_DEBUG_FLAG_AUTH, "authdes_nseccreate: no public key found for %s", servername); return (NULL); } pkey.n_bytes = (char *)pkey_data; pkey.n_len = (u_int) strlen((char *)pkey_data) + 1; dummy = authdes_pk_nseccreate(servername, &pkey, win, timehost, ckey, NULL); return (dummy); } /* * Slightly modified version of authdessec_create which takes the public key * of the server principal as an argument. This spares us a call to * getpublickey() which in the nameserver context can cause a deadlock. */ AUTH * authdes_pk_nseccreate(const char *servername, netobj *pkey, u_int window, const char *timehost, const des_block *ckey, nis_server *srvr) { AUTH *auth; struct ad_private *ad; char namebuf[MAXNETNAMELEN + 1]; /* * Allocate everything now */ auth = mem_alloc(sizeof(AUTH)); ad = mem_alloc(sizeof(struct ad_private)); ad->ad_fullname = ad->ad_servername = NULL; /* Sanity reasons */ ad->ad_timehost = NULL; ad->ad_netid = NULL; ad->ad_uaddr = NULL; ad->ad_nis_srvr = NULL; ad->ad_timediff.tv_sec = 0; ad->ad_timediff.tv_usec = 0; memcpy(ad->ad_pkey, pkey->n_bytes, pkey->n_len); if (!getnetname(namebuf)) goto failed; ad->ad_fullnamelen = RNDUP((u_int) strlen(namebuf)); ad->ad_fullname = (char *)mem_alloc(ad->ad_fullnamelen + 1); ad->ad_servernamelen = strlen(servername); ad->ad_servername = (char *)mem_alloc(ad->ad_servernamelen + 1); if (timehost != NULL) { ad->ad_timehost = mem_strdup(timehost); ad->ad_dosync = true; } else if (srvr != NULL) { ad->ad_nis_srvr = srvr; /* transient */ ad->ad_dosync = true; } else { ad->ad_dosync = false; } memcpy(ad->ad_fullname, namebuf, ad->ad_fullnamelen + 1); memcpy(ad->ad_servername, servername, ad->ad_servernamelen + 1); ad->ad_window = window; if (ckey == NULL) { if (key_gendes(&auth->ah_key) < 0) { __warnx(TIRPC_DEBUG_FLAG_AUTH, "authdes_nseccreate: keyserv(1m) is unable to generate " "session key"); goto failed; } } else { auth->ah_key = *ckey; } /* * Set up auth handle */ auth->ah_cred.oa_flavor = AUTH_DES; auth->ah_verf.oa_flavor = AUTH_DES; auth->ah_ops = authdes_ops(); auth->ah_private = (caddr_t) ad; if (!authdes_refresh(auth, NULL)) goto failed; ad->ad_nis_srvr = NULL; /* not needed any longer */ auth_get(auth); /* Reference for caller */ return (auth); failed: if (auth) mem_free(auth, sizeof(AUTH)); if (ad) { if (ad->ad_fullname) mem_free(ad->ad_fullname, ad->ad_fullnamelen + 1); if (ad->ad_servername) mem_free(ad->ad_servername, ad->ad_servernamelen + 1); if (ad->ad_timehost) mem_free(ad->ad_timehost, strlen(ad->ad_timehost) + 1); if (ad->ad_netid) mem_free(ad->ad_netid, strlen(ad->ad_netid) + 1); if (ad->ad_uaddr) mem_free(ad->ad_uaddr, strlen(ad->ad_uaddr) + 1); mem_free(ad, sizeof(struct ad_private)); } return (NULL); } /* * Implement the five authentication operations */ /* * 1. Next Verifier */ static void authdes_nextverf(AUTH *auth) { /* what the heck am I supposed to do??? */ } /* * 2. Marshal */ static bool authdes_marshal(AUTH *auth, XDR *xdrs) { /* LINTED pointer alignment */ struct ad_private *ad = AUTH_PRIVATE(auth); struct authdes_cred *cred = &ad->ad_cred; struct authdes_verf *verf = &ad->ad_verf; des_block cryptbuf[2]; des_block ivec; int status; int len; rpc_inline_t *ixdr; /* * Figure out the "time", accounting for any time difference * with the server if necessary. */ (void)gettimeofday(&ad->ad_timestamp, (struct timezone *)NULL); ad->ad_timestamp.tv_sec += ad->ad_timediff.tv_sec; ad->ad_timestamp.tv_usec += ad->ad_timediff.tv_usec; while (ad->ad_timestamp.tv_usec >= USEC_PER_SEC) { ad->ad_timestamp.tv_usec -= USEC_PER_SEC; ad->ad_timestamp.tv_sec++; } /* * XDR the timestamp and possibly some other things, then * encrypt them. */ ixdr = (rpc_inline_t *) cryptbuf; IXDR_PUT_INT32(ixdr, ad->ad_timestamp.tv_sec); IXDR_PUT_INT32(ixdr, ad->ad_timestamp.tv_usec); if (ad->ad_cred.adc_namekind == ADN_FULLNAME) { IXDR_PUT_U_INT32(ixdr, ad->ad_window); IXDR_PUT_U_INT32(ixdr, ad->ad_window - 1); ivec.key.high = ivec.key.low = 0; status = cbc_crypt((char *)&auth->ah_key, (char *)cryptbuf, (u_int) 2 * sizeof(des_block), DES_ENCRYPT | DES_HW, (char *)&ivec); } else { status = ecb_crypt((char *)&auth->ah_key, (char *)cryptbuf, (u_int) sizeof(des_block), DES_ENCRYPT | DES_HW); } if (DES_FAILED(status)) { __warnx(TIRPC_DEBUG_FLAG_AUTH, "authdes_marshal: DES encryption failure"); return (false); } ad->ad_verf.adv_xtimestamp = cryptbuf[0]; if (ad->ad_cred.adc_namekind == ADN_FULLNAME) { ad->ad_cred.adc_fullname.window = cryptbuf[1].key.high; ad->ad_verf.adv_winverf = cryptbuf[1].key.low; } else { ad->ad_cred.adc_nickname = ad->ad_nickname; ad->ad_verf.adv_winverf = 0; } /* * Serialize the credential and verifier into opaque * authentication data. */ if (ad->ad_cred.adc_namekind == ADN_FULLNAME) { len = ((1 + 1 + 2 + 1) * BYTES_PER_XDR_UNIT + ad->ad_fullnamelen); } else { len = (1 + 1) * BYTES_PER_XDR_UNIT; } ixdr = xdr_inline(xdrs, 2 * BYTES_PER_XDR_UNIT); if (ixdr) { IXDR_PUT_INT32(ixdr, AUTH_DES); IXDR_PUT_INT32(ixdr, len); } else { ATTEMPT(xdr_putint32(xdrs, (int *)&auth->ah_cred.oa_flavor)); ATTEMPT(xdr_putint32(xdrs, &len)); } ATTEMPT(xdr_authdes_cred(xdrs, cred)); len = (2 + 1) * BYTES_PER_XDR_UNIT; ixdr = xdr_inline(xdrs, 2 * BYTES_PER_XDR_UNIT); if (ixdr) { IXDR_PUT_INT32(ixdr, AUTH_DES); IXDR_PUT_INT32(ixdr, len); } else { ATTEMPT(xdr_putint32(xdrs, (int *)&auth->ah_verf.oa_flavor)); ATTEMPT(xdr_putint32(xdrs, &len)); } ATTEMPT(xdr_authdes_verf(xdrs, verf)); return (true); } /* * 3. Validate */ static bool authdes_validate(AUTH *auth, struct opaque_auth *rverf) { /* LINTED pointer alignment */ struct ad_private *ad = AUTH_PRIVATE(auth); struct authdes_verf verf; int status; uint32_t *ixdr; des_block buf; if (rverf->oa_length != (2 + 1) * BYTES_PER_XDR_UNIT) return (false); /* LINTED pointer alignment */ ixdr = (uint32_t *) rverf->oa_base; buf.key.high = (uint32_t) *ixdr++; buf.key.low = (uint32_t) *ixdr++; verf.adv_int_u = (uint32_t) *ixdr++; /* * Decrypt the timestamp */ status = ecb_crypt((char *)&auth->ah_key, (char *)&buf, (u_int) sizeof(des_block), DES_DECRYPT | DES_HW); if (DES_FAILED(status)) { __warnx(TIRPC_DEBUG_FLAG_AUTH, "authdes_validate: DES decryption failure"); return (false); } /* * xdr the decrypted timestamp */ /* LINTED pointer alignment */ ixdr = (uint32_t *) buf.c; verf.adv_timestamp.tv_sec = IXDR_GET_INT32(ixdr) + 1; verf.adv_timestamp.tv_usec = IXDR_GET_INT32(ixdr); /* * validate */ if (bcmp ((char *)&ad->ad_timestamp, (char *)&verf.adv_timestamp, sizeof(struct timeval)) != 0) { __warnx(TIRPC_DEBUG_FLAG_AUTH, "authdes_validate: verifier mismatch"); return (false); } /* * We have a nickname now, let's use it */ ad->ad_nickname = verf.adv_nickname; ad->ad_cred.adc_namekind = ADN_NICKNAME; return (true); } /* * 4. Refresh */ /*ARGSUSED*/ static bool authdes_refresh(AUTH *auth, void *dummy) { /* LINTED pointer alignment */ struct ad_private *ad = AUTH_PRIVATE(auth); struct authdes_cred *cred = &ad->ad_cred; int ok; netobj pkey; if (ad->ad_dosync) { ok = __rpc_get_time_offset(&ad->ad_timediff, ad->ad_nis_srvr, ad->ad_timehost, &(ad->ad_uaddr), &(ad->ad_netid)); if (!ok) { /* * Hope the clocks are synced! */ ad->ad_dosync = 0; __warnx(TIRPC_DEBUG_FLAG_AUTH, "authdes_refresh: unable to synchronize clock"); } } ad->ad_xkey = auth->ah_key; pkey.n_bytes = (char *)(ad->ad_pkey); pkey.n_len = (u_int) strlen((char *)ad->ad_pkey) + 1; if (key_encryptsession_pk(ad->ad_servername, &pkey, &ad->ad_xkey) < 0) { __warnx(TIRPC_DEBUG_FLAG_AUTH, "authdes_refresh: keyserv(1m) is unable to encrypt " "session key"); return (false); } cred->adc_fullname.key = ad->ad_xkey; cred->adc_namekind = ADN_FULLNAME; cred->adc_fullname.name = ad->ad_fullname; return (true); } /* * 5. Destroy */ static void authdes_destroy(AUTH *auth) { /* LINTED pointer alignment */ struct ad_private *ad = AUTH_PRIVATE(auth); mem_free(ad->ad_fullname, ad->ad_fullnamelen + 1); mem_free(ad->ad_servername, ad->ad_servernamelen + 1); if (ad->ad_timehost) mem_free(ad->ad_timehost, strlen(ad->ad_timehost) + 1); if (ad->ad_netid) mem_free(ad->ad_netid, strlen(ad->ad_netid) + 1); if (ad->ad_uaddr) mem_free(ad->ad_uaddr, strlen(ad->ad_uaddr) + 1); mem_free(ad, sizeof(struct ad_private)); mem_free(auth, sizeof(AUTH)); } static bool authdes_wrap(AUTH *auth, XDR *xdrs, xdrproc_t xfunc, caddr_t xwhere) { return ((*xfunc) (xdrs, xwhere)); } static struct auth_ops * authdes_ops(void) { static struct auth_ops ops; extern mutex_t authdes_ops_lock; /* VARIABLES PROTECTED BY ops_lock: ops */ mutex_lock(&authdes_ops_lock); if (ops.ah_nextverf == NULL) { ops.ah_nextverf = authdes_nextverf; ops.ah_marshal = authdes_marshal; ops.ah_validate = authdes_validate; ops.ah_refresh = authdes_refresh; ops.ah_destroy = authdes_destroy; ops.ah_wrap = authdes_wrap; ops.ah_unwrap = authdes_wrap; } mutex_unlock(&authdes_ops_lock); return (&ops); } #endif <file_sep>/* $NetBSD: svc_soc.h,v 1.1 2000/06/02 22:57:57 fvdl Exp $ */ /* $FreeBSD: src/include/rpc/svc_soc.h,v 1.2 2002/03/23 17:24:55 imp Exp $ */ /* * Copyright (c) 2009, Sun Microsystems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - Neither the name of Sun Microsystems, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* * Copyright (c) 1986 - 1991 by Sun Microsystems, Inc. */ /* * svc.h, Server-side remote procedure call interface. */ #ifndef _RPC_SVC_SOC_H #define _RPC_SVC_SOC_H #include <sys/cdefs.h> /* #pragma ident "@(#)svc_soc.h 1.11 94/04/25 SMI" */ /* svc_soc.h 1.8 89/05/01 SMI */ /* * All the following declarations are only for backward compatibility * with TS-RPC */ /* * Approved way of getting addresses */ #define svc_getcaller_netbuf(x) (&(x)->xp_remote.nb) #define svc_getlocal_netbuf(x) (&(x)->xp_local.nb) /* * Service registration * * svc_register(xprt, prog, vers, dispatch, protocol) * SVCXPRT *xprt; * u_long prog; * u_long vers; * void (*dispatch)(); * int protocol; like TCP or UDP, zero means do not register */ __BEGIN_DECLS extern bool svc_register(SVCXPRT *, u_long, u_long, void (*)(struct svc_req *, SVCXPRT *), int); __END_DECLS /* * Service un-registration * * svc_unregister(prog, vers) * u_long prog; * u_long vers; */ __BEGIN_DECLS extern void svc_unregister(u_long, u_long); __END_DECLS /* * Memory based rpc for testing and timing. */ __BEGIN_DECLS extern SVCXPRT *svcraw_ncreate(void); __END_DECLS /* * Udp based rpc. */ __BEGIN_DECLS extern SVCXPRT *svcudp_ncreate(int); extern SVCXPRT *svcudp_nbufcreate(int, u_int, u_int); extern int svcudp_enablecache(SVCXPRT *, u_long); extern SVCXPRT *svcudp6_ncreate(int); extern SVCXPRT *svcudp6_nbufcreate(int, u_int, u_int); __END_DECLS /* * Tcp based rpc. */ __BEGIN_DECLS extern SVCXPRT *svctcp_ncreate(int, u_int, u_int); extern SVCXPRT *svctcp6_ncreate(int, u_int, u_int); __END_DECLS /* * Fd based rpc. */ __BEGIN_DECLS extern SVCXPRT *svcfd_ncreate(int, u_int, u_int); __END_DECLS #endif /* !_RPC_SVC_SOC_H */ <file_sep>/* * Please do not edit this file. * It was generated using rpcgen. */ #include "nfs4.h" bool_t xdr_nfs_ftype4 (XDR *xdrs, nfs_ftype4 *objp) { register int32_t *buf; if (!xdr_enum (xdrs, (enum_t *) objp)) return FALSE; return TRUE; } bool_t xdr_nfsstat4 (XDR *xdrs, nfsstat4 *objp) { register int32_t *buf; if (!xdr_enum (xdrs, (enum_t *) objp)) return FALSE; return TRUE; } bool_t xdr_bitmap4 (XDR *xdrs, bitmap4 *objp) { register int32_t *buf; if (!xdr_array (xdrs, (char **)&objp->bitmap4_val, (u_int *) &objp->bitmap4_len, ~0, sizeof (uint32_t), (xdrproc_t) xdr_uint32_t)) return FALSE; return TRUE; } bool_t xdr_offset4 (XDR *xdrs, offset4 *objp) { register int32_t *buf; if (!xdr_uint64_t (xdrs, objp)) return FALSE; return TRUE; } bool_t xdr_count4 (XDR *xdrs, count4 *objp) { register int32_t *buf; if (!xdr_uint32_t (xdrs, objp)) return FALSE; return TRUE; } bool_t xdr_length4 (XDR *xdrs, length4 *objp) { register int32_t *buf; if (!xdr_uint64_t (xdrs, objp)) return FALSE; return TRUE; } bool_t xdr_clientid4 (XDR *xdrs, clientid4 *objp) { register int32_t *buf; if (!xdr_uint64_t (xdrs, objp)) return FALSE; return TRUE; } bool_t xdr_seqid4 (XDR *xdrs, seqid4 *objp) { register int32_t *buf; if (!xdr_uint32_t (xdrs, objp)) return FALSE; return TRUE; } bool_t xdr_utf8string (XDR *xdrs, utf8string *objp) { register int32_t *buf; if (!xdr_bytes (xdrs, (char **)&objp->utf8string_val, (u_int *) &objp->utf8string_len, ~0)) return FALSE; return TRUE; } bool_t xdr_utf8str_cis (XDR *xdrs, utf8str_cis *objp) { register int32_t *buf; if (!xdr_utf8string (xdrs, objp)) return FALSE; return TRUE; } bool_t xdr_utf8str_cs (XDR *xdrs, utf8str_cs *objp) { register int32_t *buf; if (!xdr_utf8string (xdrs, objp)) return FALSE; return TRUE; } bool_t xdr_utf8str_mixed (XDR *xdrs, utf8str_mixed *objp) { register int32_t *buf; if (!xdr_utf8string (xdrs, objp)) return FALSE; return TRUE; } bool_t xdr_component4 (XDR *xdrs, component4 *objp) { register int32_t *buf; if (!xdr_utf8str_cs (xdrs, objp)) return FALSE; return TRUE; } bool_t xdr_pathname4 (XDR *xdrs, pathname4 *objp) { register int32_t *buf; if (!xdr_array (xdrs, (char **)&objp->pathname4_val, (u_int *) &objp->pathname4_len, ~0, sizeof (component4), (xdrproc_t) xdr_component4)) return FALSE; return TRUE; } bool_t xdr_nfs_lockid4 (XDR *xdrs, nfs_lockid4 *objp) { register int32_t *buf; if (!xdr_uint64_t (xdrs, objp)) return FALSE; return TRUE; } bool_t xdr_nfs_cookie4 (XDR *xdrs, nfs_cookie4 *objp) { register int32_t *buf; if (!xdr_uint64_t (xdrs, objp)) return FALSE; return TRUE; } bool_t xdr_linktext4 (XDR *xdrs, linktext4 *objp) { register int32_t *buf; if (!xdr_utf8str_cs (xdrs, objp)) return FALSE; return TRUE; } bool_t xdr_sec_oid4 (XDR *xdrs, sec_oid4 *objp) { register int32_t *buf; if (!xdr_bytes (xdrs, (char **)&objp->sec_oid4_val, (u_int *) &objp->sec_oid4_len, ~0)) return FALSE; return TRUE; } bool_t xdr_qop4 (XDR *xdrs, qop4 *objp) { register int32_t *buf; if (!xdr_uint32_t (xdrs, objp)) return FALSE; return TRUE; } bool_t xdr_mode4 (XDR *xdrs, mode4 *objp) { register int32_t *buf; if (!xdr_uint32_t (xdrs, objp)) return FALSE; return TRUE; } bool_t xdr_changeid4 (XDR *xdrs, changeid4 *objp) { register int32_t *buf; if (!xdr_uint64_t (xdrs, objp)) return FALSE; return TRUE; } bool_t xdr_verifier4 (XDR *xdrs, verifier4 objp) { register int32_t *buf; if (!xdr_opaque (xdrs, objp, NFS4_VERIFIER_SIZE)) return FALSE; return TRUE; } bool_t xdr_nfstime4 (XDR *xdrs, nfstime4 *objp) { register int32_t *buf; if (!xdr_int64_t (xdrs, &objp->seconds)) return FALSE; if (!xdr_uint32_t (xdrs, &objp->nseconds)) return FALSE; return TRUE; } bool_t xdr_time_how4 (XDR *xdrs, time_how4 *objp) { register int32_t *buf; if (!xdr_enum (xdrs, (enum_t *) objp)) return FALSE; return TRUE; } bool_t xdr_settime4 (XDR *xdrs, settime4 *objp) { register int32_t *buf; if (!xdr_time_how4 (xdrs, &objp->set_it)) return FALSE; switch (objp->set_it) { case SET_TO_CLIENT_TIME4: if (!xdr_nfstime4 (xdrs, &objp->settime4_u.time)) return FALSE; break; default: break; } return TRUE; } bool_t xdr_nfs_fh4 (XDR *xdrs, nfs_fh4 *objp) { register int32_t *buf; if (!xdr_bytes (xdrs, (char **)&objp->nfs_fh4_val, (u_int *) &objp->nfs_fh4_len, NFS4_FHSIZE)) return FALSE; return TRUE; } bool_t xdr_fsid4 (XDR *xdrs, fsid4 *objp) { register int32_t *buf; if (!xdr_uint64_t (xdrs, &objp->major)) return FALSE; if (!xdr_uint64_t (xdrs, &objp->minor)) return FALSE; return TRUE; } bool_t xdr_fs_location4 (XDR *xdrs, fs_location4 *objp) { register int32_t *buf; if (!xdr_array (xdrs, (char **)&objp->server.server_val, (u_int *) &objp->server.server_len, ~0, sizeof (utf8str_cis), (xdrproc_t) xdr_utf8str_cis)) return FALSE; if (!xdr_pathname4 (xdrs, &objp->rootpath)) return FALSE; return TRUE; } bool_t xdr_fs_locations4 (XDR *xdrs, fs_locations4 *objp) { register int32_t *buf; if (!xdr_pathname4 (xdrs, &objp->fs_root)) return FALSE; if (!xdr_array (xdrs, (char **)&objp->locations.locations_val, (u_int *) &objp->locations.locations_len, ~0, sizeof (fs_location4), (xdrproc_t) xdr_fs_location4)) return FALSE; return TRUE; } bool_t xdr_acetype4 (XDR *xdrs, acetype4 *objp) { register int32_t *buf; if (!xdr_uint32_t (xdrs, objp)) return FALSE; return TRUE; } bool_t xdr_aceflag4 (XDR *xdrs, aceflag4 *objp) { register int32_t *buf; if (!xdr_uint32_t (xdrs, objp)) return FALSE; return TRUE; } bool_t xdr_acemask4 (XDR *xdrs, acemask4 *objp) { register int32_t *buf; if (!xdr_uint32_t (xdrs, objp)) return FALSE; return TRUE; } bool_t xdr_nfsace4 (XDR *xdrs, nfsace4 *objp) { register int32_t *buf; if (!xdr_acetype4 (xdrs, &objp->type)) return FALSE; if (!xdr_aceflag4 (xdrs, &objp->flag)) return FALSE; if (!xdr_acemask4 (xdrs, &objp->access_mask)) return FALSE; if (!xdr_utf8str_mixed (xdrs, &objp->who)) return FALSE; return TRUE; } bool_t xdr_specdata4 (XDR *xdrs, specdata4 *objp) { register int32_t *buf; if (!xdr_uint32_t (xdrs, &objp->specdata1)) return FALSE; if (!xdr_uint32_t (xdrs, &objp->specdata2)) return FALSE; return TRUE; } bool_t xdr_fattr4_supported_attrs (XDR *xdrs, fattr4_supported_attrs *objp) { register int32_t *buf; if (!xdr_bitmap4 (xdrs, objp)) return FALSE; return TRUE; } bool_t xdr_fattr4_type (XDR *xdrs, fattr4_type *objp) { register int32_t *buf; if (!xdr_nfs_ftype4 (xdrs, objp)) return FALSE; return TRUE; } bool_t xdr_fattr4_fh_expire_type (XDR *xdrs, fattr4_fh_expire_type *objp) { register int32_t *buf; if (!xdr_uint32_t (xdrs, objp)) return FALSE; return TRUE; } bool_t xdr_fattr4_change (XDR *xdrs, fattr4_change *objp) { register int32_t *buf; if (!xdr_changeid4 (xdrs, objp)) return FALSE; return TRUE; } bool_t xdr_fattr4_size (XDR *xdrs, fattr4_size *objp) { register int32_t *buf; if (!xdr_uint64_t (xdrs, objp)) return FALSE; return TRUE; } bool_t xdr_fattr4_link_support (XDR *xdrs, fattr4_link_support *objp) { register int32_t *buf; if (!xdr_bool (xdrs, objp)) return FALSE; return TRUE; } bool_t xdr_fattr4_symlink_support (XDR *xdrs, fattr4_symlink_support *objp) { register int32_t *buf; if (!xdr_bool (xdrs, objp)) return FALSE; return TRUE; } bool_t xdr_fattr4_named_attr (XDR *xdrs, fattr4_named_attr *objp) { register int32_t *buf; if (!xdr_bool (xdrs, objp)) return FALSE; return TRUE; } bool_t xdr_fattr4_fsid (XDR *xdrs, fattr4_fsid *objp) { register int32_t *buf; if (!xdr_fsid4 (xdrs, objp)) return FALSE; return TRUE; } bool_t xdr_fattr4_unique_handles (XDR *xdrs, fattr4_unique_handles *objp) { register int32_t *buf; if (!xdr_bool (xdrs, objp)) return FALSE; return TRUE; } bool_t xdr_fattr4_lease_time (XDR *xdrs, fattr4_lease_time *objp) { register int32_t *buf; if (!xdr_uint32_t (xdrs, objp)) return FALSE; return TRUE; } bool_t xdr_fattr4_rdattr_error (XDR *xdrs, fattr4_rdattr_error *objp) { register int32_t *buf; if (!xdr_nfsstat4 (xdrs, objp)) return FALSE; return TRUE; } bool_t xdr_fattr4_acl (XDR *xdrs, fattr4_acl *objp) { register int32_t *buf; if (!xdr_array (xdrs, (char **)&objp->fattr4_acl_val, (u_int *) &objp->fattr4_acl_len, ~0, sizeof (nfsace4), (xdrproc_t) xdr_nfsace4)) return FALSE; return TRUE; } bool_t xdr_fattr4_aclsupport (XDR *xdrs, fattr4_aclsupport *objp) { register int32_t *buf; if (!xdr_uint32_t (xdrs, objp)) return FALSE; return TRUE; } bool_t xdr_fattr4_archive (XDR *xdrs, fattr4_archive *objp) { register int32_t *buf; if (!xdr_bool (xdrs, objp)) return FALSE; return TRUE; } bool_t xdr_fattr4_cansettime (XDR *xdrs, fattr4_cansettime *objp) { register int32_t *buf; if (!xdr_bool (xdrs, objp)) return FALSE; return TRUE; } bool_t xdr_fattr4_case_insensitive (XDR *xdrs, fattr4_case_insensitive *objp) { register int32_t *buf; if (!xdr_bool (xdrs, objp)) return FALSE; return TRUE; } bool_t xdr_fattr4_case_preserving (XDR *xdrs, fattr4_case_preserving *objp) { register int32_t *buf; if (!xdr_bool (xdrs, objp)) return FALSE; return TRUE; } bool_t xdr_fattr4_chown_restricted (XDR *xdrs, fattr4_chown_restricted *objp) { register int32_t *buf; if (!xdr_bool (xdrs, objp)) return FALSE; return TRUE; } bool_t xdr_fattr4_fileid (XDR *xdrs, fattr4_fileid *objp) { register int32_t *buf; if (!xdr_uint64_t (xdrs, objp)) return FALSE; return TRUE; } bool_t xdr_fattr4_files_avail (XDR *xdrs, fattr4_files_avail *objp) { register int32_t *buf; if (!xdr_uint64_t (xdrs, objp)) return FALSE; return TRUE; } bool_t xdr_fattr4_filehandle (XDR *xdrs, fattr4_filehandle *objp) { register int32_t *buf; if (!xdr_nfs_fh4 (xdrs, objp)) return FALSE; return TRUE; } bool_t xdr_fattr4_files_free (XDR *xdrs, fattr4_files_free *objp) { register int32_t *buf; if (!xdr_uint64_t (xdrs, objp)) return FALSE; return TRUE; } bool_t xdr_fattr4_files_total (XDR *xdrs, fattr4_files_total *objp) { register int32_t *buf; if (!xdr_uint64_t (xdrs, objp)) return FALSE; return TRUE; } bool_t xdr_fattr4_fs_locations (XDR *xdrs, fattr4_fs_locations *objp) { register int32_t *buf; if (!xdr_fs_locations4 (xdrs, objp)) return FALSE; return TRUE; } bool_t xdr_fattr4_hidden (XDR *xdrs, fattr4_hidden *objp) { register int32_t *buf; if (!xdr_bool (xdrs, objp)) return FALSE; return TRUE; } bool_t xdr_fattr4_homogeneous (XDR *xdrs, fattr4_homogeneous *objp) { register int32_t *buf; if (!xdr_bool (xdrs, objp)) return FALSE; return TRUE; } bool_t xdr_fattr4_maxfilesize (XDR *xdrs, fattr4_maxfilesize *objp) { register int32_t *buf; if (!xdr_uint64_t (xdrs, objp)) return FALSE; return TRUE; } bool_t xdr_fattr4_maxlink (XDR *xdrs, fattr4_maxlink *objp) { register int32_t *buf; if (!xdr_uint32_t (xdrs, objp)) return FALSE; return TRUE; } bool_t xdr_fattr4_maxname (XDR *xdrs, fattr4_maxname *objp) { register int32_t *buf; if (!xdr_uint32_t (xdrs, objp)) return FALSE; return TRUE; } bool_t xdr_fattr4_maxread (XDR *xdrs, fattr4_maxread *objp) { register int32_t *buf; if (!xdr_uint64_t (xdrs, objp)) return FALSE; return TRUE; } bool_t xdr_fattr4_maxwrite (XDR *xdrs, fattr4_maxwrite *objp) { register int32_t *buf; if (!xdr_uint64_t (xdrs, objp)) return FALSE; return TRUE; } bool_t xdr_fattr4_mimetype (XDR *xdrs, fattr4_mimetype *objp) { register int32_t *buf; if (!xdr_utf8str_cs (xdrs, objp)) return FALSE; return TRUE; } bool_t xdr_fattr4_mode (XDR *xdrs, fattr4_mode *objp) { register int32_t *buf; if (!xdr_mode4 (xdrs, objp)) return FALSE; return TRUE; } bool_t xdr_fattr4_mounted_on_fileid (XDR *xdrs, fattr4_mounted_on_fileid *objp) { register int32_t *buf; if (!xdr_uint64_t (xdrs, objp)) return FALSE; return TRUE; } bool_t xdr_fattr4_no_trunc (XDR *xdrs, fattr4_no_trunc *objp) { register int32_t *buf; if (!xdr_bool (xdrs, objp)) return FALSE; return TRUE; } bool_t xdr_fattr4_numlinks (XDR *xdrs, fattr4_numlinks *objp) { register int32_t *buf; if (!xdr_uint32_t (xdrs, objp)) return FALSE; return TRUE; } bool_t xdr_fattr4_owner (XDR *xdrs, fattr4_owner *objp) { register int32_t *buf; if (!xdr_utf8str_mixed (xdrs, objp)) return FALSE; return TRUE; } bool_t xdr_fattr4_owner_group (XDR *xdrs, fattr4_owner_group *objp) { register int32_t *buf; if (!xdr_utf8str_mixed (xdrs, objp)) return FALSE; return TRUE; } bool_t xdr_fattr4_quota_avail_hard (XDR *xdrs, fattr4_quota_avail_hard *objp) { register int32_t *buf; if (!xdr_uint64_t (xdrs, objp)) return FALSE; return TRUE; } bool_t xdr_fattr4_quota_avail_soft (XDR *xdrs, fattr4_quota_avail_soft *objp) { register int32_t *buf; if (!xdr_uint64_t (xdrs, objp)) return FALSE; return TRUE; } bool_t xdr_fattr4_quota_used (XDR *xdrs, fattr4_quota_used *objp) { register int32_t *buf; if (!xdr_uint64_t (xdrs, objp)) return FALSE; return TRUE; } bool_t xdr_fattr4_rawdev (XDR *xdrs, fattr4_rawdev *objp) { register int32_t *buf; if (!xdr_specdata4 (xdrs, objp)) return FALSE; return TRUE; } bool_t xdr_fattr4_space_avail (XDR *xdrs, fattr4_space_avail *objp) { register int32_t *buf; if (!xdr_uint64_t (xdrs, objp)) return FALSE; return TRUE; } bool_t xdr_fattr4_space_free (XDR *xdrs, fattr4_space_free *objp) { register int32_t *buf; if (!xdr_uint64_t (xdrs, objp)) return FALSE; return TRUE; } bool_t xdr_fattr4_space_total (XDR *xdrs, fattr4_space_total *objp) { register int32_t *buf; if (!xdr_uint64_t (xdrs, objp)) return FALSE; return TRUE; } bool_t xdr_fattr4_space_used (XDR *xdrs, fattr4_space_used *objp) { register int32_t *buf; if (!xdr_uint64_t (xdrs, objp)) return FALSE; return TRUE; } bool_t xdr_fattr4_system (XDR *xdrs, fattr4_system *objp) { register int32_t *buf; if (!xdr_bool (xdrs, objp)) return FALSE; return TRUE; } bool_t xdr_fattr4_time_access (XDR *xdrs, fattr4_time_access *objp) { register int32_t *buf; if (!xdr_nfstime4 (xdrs, objp)) return FALSE; return TRUE; } bool_t xdr_fattr4_time_access_set (XDR *xdrs, fattr4_time_access_set *objp) { register int32_t *buf; if (!xdr_settime4 (xdrs, objp)) return FALSE; return TRUE; } bool_t xdr_fattr4_time_backup (XDR *xdrs, fattr4_time_backup *objp) { register int32_t *buf; if (!xdr_nfstime4 (xdrs, objp)) return FALSE; return TRUE; } bool_t xdr_fattr4_time_create (XDR *xdrs, fattr4_time_create *objp) { register int32_t *buf; if (!xdr_nfstime4 (xdrs, objp)) return FALSE; return TRUE; } bool_t xdr_fattr4_time_delta (XDR *xdrs, fattr4_time_delta *objp) { register int32_t *buf; if (!xdr_nfstime4 (xdrs, objp)) return FALSE; return TRUE; } bool_t xdr_fattr4_time_metadata (XDR *xdrs, fattr4_time_metadata *objp) { register int32_t *buf; if (!xdr_nfstime4 (xdrs, objp)) return FALSE; return TRUE; } bool_t xdr_fattr4_time_modify (XDR *xdrs, fattr4_time_modify *objp) { register int32_t *buf; if (!xdr_nfstime4 (xdrs, objp)) return FALSE; return TRUE; } bool_t xdr_fattr4_time_modify_set (XDR *xdrs, fattr4_time_modify_set *objp) { register int32_t *buf; if (!xdr_settime4 (xdrs, objp)) return FALSE; return TRUE; } bool_t xdr_attrlist4 (XDR *xdrs, attrlist4 *objp) { register int32_t *buf; if (!xdr_bytes (xdrs, (char **)&objp->attrlist4_val, (u_int *) &objp->attrlist4_len, ~0)) return FALSE; return TRUE; } bool_t xdr_fattr4 (XDR *xdrs, fattr4 *objp) { register int32_t *buf; if (!xdr_bitmap4 (xdrs, &objp->attrmask)) return FALSE; if (!xdr_attrlist4 (xdrs, &objp->attr_vals)) return FALSE; return TRUE; } bool_t xdr_change_info4 (XDR *xdrs, change_info4 *objp) { register int32_t *buf; if (!xdr_bool (xdrs, &objp->atomic)) return FALSE; if (!xdr_changeid4 (xdrs, &objp->before)) return FALSE; if (!xdr_changeid4 (xdrs, &objp->after)) return FALSE; return TRUE; } bool_t xdr_clientaddr4 (XDR *xdrs, clientaddr4 *objp) { register int32_t *buf; if (!xdr_string (xdrs, &objp->r_netid, ~0)) return FALSE; if (!xdr_string (xdrs, &objp->r_addr, ~0)) return FALSE; return TRUE; } bool_t xdr_cb_client4 (XDR *xdrs, cb_client4 *objp) { register int32_t *buf; if (!xdr_uint32_t (xdrs, &objp->cb_program)) return FALSE; if (!xdr_clientaddr4 (xdrs, &objp->cb_location)) return FALSE; return TRUE; } bool_t xdr_stateid4 (XDR *xdrs, stateid4 *objp) { register int32_t *buf; int i; if (!xdr_uint32_t (xdrs, &objp->seqid)) return FALSE; if (!xdr_opaque (xdrs, objp->other, 12)) return FALSE; return TRUE; } bool_t xdr_nfs_client_id4 (XDR *xdrs, nfs_client_id4 *objp) { register int32_t *buf; if (!xdr_verifier4 (xdrs, objp->verifier)) return FALSE; if (!xdr_bytes (xdrs, (char **)&objp->id.id_val, (u_int *) &objp->id.id_len, NFS4_OPAQUE_LIMIT)) return FALSE; return TRUE; } bool_t xdr_open_owner4 (XDR *xdrs, open_owner4 *objp) { register int32_t *buf; if (!xdr_clientid4 (xdrs, &objp->clientid)) return FALSE; if (!xdr_bytes (xdrs, (char **)&objp->owner.owner_val, (u_int *) &objp->owner.owner_len, NFS4_OPAQUE_LIMIT)) return FALSE; return TRUE; } bool_t xdr_lock_owner4 (XDR *xdrs, lock_owner4 *objp) { register int32_t *buf; if (!xdr_clientid4 (xdrs, &objp->clientid)) return FALSE; if (!xdr_bytes (xdrs, (char **)&objp->owner.owner_val, (u_int *) &objp->owner.owner_len, NFS4_OPAQUE_LIMIT)) return FALSE; return TRUE; } bool_t xdr_nfs_lock_type4 (XDR *xdrs, nfs_lock_type4 *objp) { register int32_t *buf; if (!xdr_enum (xdrs, (enum_t *) objp)) return FALSE; return TRUE; } bool_t xdr_ACCESS4args (XDR *xdrs, ACCESS4args *objp) { register int32_t *buf; if (!xdr_uint32_t (xdrs, &objp->access)) return FALSE; return TRUE; } bool_t xdr_ACCESS4resok (XDR *xdrs, ACCESS4resok *objp) { register int32_t *buf; if (!xdr_uint32_t (xdrs, &objp->supported)) return FALSE; if (!xdr_uint32_t (xdrs, &objp->access)) return FALSE; return TRUE; } bool_t xdr_ACCESS4res (XDR *xdrs, ACCESS4res *objp) { register int32_t *buf; if (!xdr_nfsstat4 (xdrs, &objp->status)) return FALSE; switch (objp->status) { case NFS4_OK: if (!xdr_ACCESS4resok (xdrs, &objp->ACCESS4res_u.resok4)) return FALSE; break; default: break; } return TRUE; } bool_t xdr_CLOSE4args (XDR *xdrs, CLOSE4args *objp) { register int32_t *buf; if (!xdr_seqid4 (xdrs, &objp->seqid)) return FALSE; if (!xdr_stateid4 (xdrs, &objp->open_stateid)) return FALSE; return TRUE; } bool_t xdr_CLOSE4res (XDR *xdrs, CLOSE4res *objp) { register int32_t *buf; if (!xdr_nfsstat4 (xdrs, &objp->status)) return FALSE; switch (objp->status) { case NFS4_OK: if (!xdr_stateid4 (xdrs, &objp->CLOSE4res_u.open_stateid)) return FALSE; break; default: break; } return TRUE; } bool_t xdr_COMMIT4args (XDR *xdrs, COMMIT4args *objp) { register int32_t *buf; if (!xdr_offset4 (xdrs, &objp->offset)) return FALSE; if (!xdr_count4 (xdrs, &objp->count)) return FALSE; return TRUE; } bool_t xdr_COMMIT4resok (XDR *xdrs, COMMIT4resok *objp) { register int32_t *buf; if (!xdr_verifier4 (xdrs, objp->writeverf)) return FALSE; return TRUE; } bool_t xdr_COMMIT4res (XDR *xdrs, COMMIT4res *objp) { register int32_t *buf; if (!xdr_nfsstat4 (xdrs, &objp->status)) return FALSE; switch (objp->status) { case NFS4_OK: if (!xdr_COMMIT4resok (xdrs, &objp->COMMIT4res_u.resok4)) return FALSE; break; default: break; } return TRUE; } bool_t xdr_createtype4 (XDR *xdrs, createtype4 *objp) { register int32_t *buf; if (!xdr_nfs_ftype4 (xdrs, &objp->type)) return FALSE; switch (objp->type) { case NF4LNK: if (!xdr_linktext4 (xdrs, &objp->createtype4_u.linkdata)) return FALSE; break; case NF4BLK: case NF4CHR: if (!xdr_specdata4 (xdrs, &objp->createtype4_u.devdata)) return FALSE; break; case NF4SOCK: case NF4FIFO: case NF4DIR: break; default: break; } return TRUE; } bool_t xdr_CREATE4args (XDR *xdrs, CREATE4args *objp) { register int32_t *buf; if (!xdr_createtype4 (xdrs, &objp->objtype)) return FALSE; if (!xdr_component4 (xdrs, &objp->objname)) return FALSE; if (!xdr_fattr4 (xdrs, &objp->createattrs)) return FALSE; return TRUE; } bool_t xdr_CREATE4resok (XDR *xdrs, CREATE4resok *objp) { register int32_t *buf; if (!xdr_change_info4 (xdrs, &objp->cinfo)) return FALSE; if (!xdr_bitmap4 (xdrs, &objp->attrset)) return FALSE; return TRUE; } bool_t xdr_CREATE4res (XDR *xdrs, CREATE4res *objp) { register int32_t *buf; if (!xdr_nfsstat4 (xdrs, &objp->status)) return FALSE; switch (objp->status) { case NFS4_OK: if (!xdr_CREATE4resok (xdrs, &objp->CREATE4res_u.resok4)) return FALSE; break; default: break; } return TRUE; } bool_t xdr_DELEGPURGE4args (XDR *xdrs, DELEGPURGE4args *objp) { register int32_t *buf; if (!xdr_clientid4 (xdrs, &objp->clientid)) return FALSE; return TRUE; } bool_t xdr_DELEGPURGE4res (XDR *xdrs, DELEGPURGE4res *objp) { register int32_t *buf; if (!xdr_nfsstat4 (xdrs, &objp->status)) return FALSE; return TRUE; } bool_t xdr_DELEGRETURN4args (XDR *xdrs, DELEGRETURN4args *objp) { register int32_t *buf; if (!xdr_stateid4 (xdrs, &objp->deleg_stateid)) return FALSE; return TRUE; } bool_t xdr_DELEGRETURN4res (XDR *xdrs, DELEGRETURN4res *objp) { register int32_t *buf; if (!xdr_nfsstat4 (xdrs, &objp->status)) return FALSE; return TRUE; } bool_t xdr_GETATTR4args (XDR *xdrs, GETATTR4args *objp) { register int32_t *buf; if (!xdr_bitmap4 (xdrs, &objp->attr_request)) return FALSE; return TRUE; } bool_t xdr_GETATTR4resok (XDR *xdrs, GETATTR4resok *objp) { register int32_t *buf; if (!xdr_fattr4 (xdrs, &objp->obj_attributes)) return FALSE; return TRUE; } bool_t xdr_GETATTR4res (XDR *xdrs, GETATTR4res *objp) { register int32_t *buf; if (!xdr_nfsstat4 (xdrs, &objp->status)) return FALSE; switch (objp->status) { case NFS4_OK: if (!xdr_GETATTR4resok (xdrs, &objp->GETATTR4res_u.resok4)) return FALSE; break; default: break; } return TRUE; } bool_t xdr_GETFH4resok (XDR *xdrs, GETFH4resok *objp) { register int32_t *buf; if (!xdr_nfs_fh4 (xdrs, &objp->object)) return FALSE; return TRUE; } bool_t xdr_GETFH4res (XDR *xdrs, GETFH4res *objp) { register int32_t *buf; if (!xdr_nfsstat4 (xdrs, &objp->status)) return FALSE; switch (objp->status) { case NFS4_OK: if (!xdr_GETFH4resok (xdrs, &objp->GETFH4res_u.resok4)) return FALSE; break; default: break; } return TRUE; } bool_t xdr_LINK4args (XDR *xdrs, LINK4args *objp) { register int32_t *buf; if (!xdr_component4 (xdrs, &objp->newname)) return FALSE; return TRUE; } bool_t xdr_LINK4resok (XDR *xdrs, LINK4resok *objp) { register int32_t *buf; if (!xdr_change_info4 (xdrs, &objp->cinfo)) return FALSE; return TRUE; } bool_t xdr_LINK4res (XDR *xdrs, LINK4res *objp) { register int32_t *buf; if (!xdr_nfsstat4 (xdrs, &objp->status)) return FALSE; switch (objp->status) { case NFS4_OK: if (!xdr_LINK4resok (xdrs, &objp->LINK4res_u.resok4)) return FALSE; break; default: break; } return TRUE; } bool_t xdr_open_to_lock_owner4 (XDR *xdrs, open_to_lock_owner4 *objp) { register int32_t *buf; if (!xdr_seqid4 (xdrs, &objp->open_seqid)) return FALSE; if (!xdr_stateid4 (xdrs, &objp->open_stateid)) return FALSE; if (!xdr_seqid4 (xdrs, &objp->lock_seqid)) return FALSE; if (!xdr_lock_owner4 (xdrs, &objp->lock_owner)) return FALSE; return TRUE; } bool_t xdr_exist_lock_owner4 (XDR *xdrs, exist_lock_owner4 *objp) { register int32_t *buf; if (!xdr_stateid4 (xdrs, &objp->lock_stateid)) return FALSE; if (!xdr_seqid4 (xdrs, &objp->lock_seqid)) return FALSE; return TRUE; } bool_t xdr_locker4 (XDR *xdrs, locker4 *objp) { register int32_t *buf; if (!xdr_bool (xdrs, &objp->new_lock_owner)) return FALSE; switch (objp->new_lock_owner) { case TRUE: if (!xdr_open_to_lock_owner4 (xdrs, &objp->locker4_u.open_owner)) return FALSE; break; case FALSE: if (!xdr_exist_lock_owner4 (xdrs, &objp->locker4_u.lock_owner)) return FALSE; break; default: return FALSE; } return TRUE; } bool_t xdr_LOCK4args (XDR *xdrs, LOCK4args *objp) { register int32_t *buf; if (!xdr_nfs_lock_type4 (xdrs, &objp->locktype)) return FALSE; if (!xdr_bool (xdrs, &objp->reclaim)) return FALSE; if (!xdr_offset4 (xdrs, &objp->offset)) return FALSE; if (!xdr_length4 (xdrs, &objp->length)) return FALSE; if (!xdr_locker4 (xdrs, &objp->locker)) return FALSE; return TRUE; } bool_t xdr_LOCK4denied (XDR *xdrs, LOCK4denied *objp) { register int32_t *buf; if (!xdr_offset4 (xdrs, &objp->offset)) return FALSE; if (!xdr_length4 (xdrs, &objp->length)) return FALSE; if (!xdr_nfs_lock_type4 (xdrs, &objp->locktype)) return FALSE; if (!xdr_lock_owner4 (xdrs, &objp->owner)) return FALSE; return TRUE; } bool_t xdr_LOCK4resok (XDR *xdrs, LOCK4resok *objp) { register int32_t *buf; if (!xdr_stateid4 (xdrs, &objp->lock_stateid)) return FALSE; return TRUE; } bool_t xdr_LOCK4res (XDR *xdrs, LOCK4res *objp) { register int32_t *buf; if (!xdr_nfsstat4 (xdrs, &objp->status)) return FALSE; switch (objp->status) { case NFS4_OK: if (!xdr_LOCK4resok (xdrs, &objp->LOCK4res_u.resok4)) return FALSE; break; case NFS4ERR_DENIED: if (!xdr_LOCK4denied (xdrs, &objp->LOCK4res_u.denied)) return FALSE; break; default: break; } return TRUE; } bool_t xdr_LOCKT4args (XDR *xdrs, LOCKT4args *objp) { register int32_t *buf; if (!xdr_nfs_lock_type4 (xdrs, &objp->locktype)) return FALSE; if (!xdr_offset4 (xdrs, &objp->offset)) return FALSE; if (!xdr_length4 (xdrs, &objp->length)) return FALSE; if (!xdr_lock_owner4 (xdrs, &objp->owner)) return FALSE; return TRUE; } bool_t xdr_LOCKT4res (XDR *xdrs, LOCKT4res *objp) { register int32_t *buf; if (!xdr_nfsstat4 (xdrs, &objp->status)) return FALSE; switch (objp->status) { case NFS4ERR_DENIED: if (!xdr_LOCK4denied (xdrs, &objp->LOCKT4res_u.denied)) return FALSE; break; case NFS4_OK: break; default: break; } return TRUE; } bool_t xdr_LOCKU4args (XDR *xdrs, LOCKU4args *objp) { register int32_t *buf; if (!xdr_nfs_lock_type4 (xdrs, &objp->locktype)) return FALSE; if (!xdr_seqid4 (xdrs, &objp->seqid)) return FALSE; if (!xdr_stateid4 (xdrs, &objp->lock_stateid)) return FALSE; if (!xdr_offset4 (xdrs, &objp->offset)) return FALSE; if (!xdr_length4 (xdrs, &objp->length)) return FALSE; return TRUE; } bool_t xdr_LOCKU4res (XDR *xdrs, LOCKU4res *objp) { register int32_t *buf; if (!xdr_nfsstat4 (xdrs, &objp->status)) return FALSE; switch (objp->status) { case NFS4_OK: if (!xdr_stateid4 (xdrs, &objp->LOCKU4res_u.lock_stateid)) return FALSE; break; default: break; } return TRUE; } bool_t xdr_LOOKUP4args (XDR *xdrs, LOOKUP4args *objp) { register int32_t *buf; if (!xdr_component4 (xdrs, &objp->objname)) return FALSE; return TRUE; } bool_t xdr_LOOKUP4res (XDR *xdrs, LOOKUP4res *objp) { register int32_t *buf; if (!xdr_nfsstat4 (xdrs, &objp->status)) return FALSE; return TRUE; } bool_t xdr_LOOKUPP4res (XDR *xdrs, LOOKUPP4res *objp) { register int32_t *buf; if (!xdr_nfsstat4 (xdrs, &objp->status)) return FALSE; return TRUE; } bool_t xdr_NVERIFY4args (XDR *xdrs, NVERIFY4args *objp) { register int32_t *buf; if (!xdr_fattr4 (xdrs, &objp->obj_attributes)) return FALSE; return TRUE; } bool_t xdr_NVERIFY4res (XDR *xdrs, NVERIFY4res *objp) { register int32_t *buf; if (!xdr_nfsstat4 (xdrs, &objp->status)) return FALSE; return TRUE; } bool_t xdr_createmode4 (XDR *xdrs, createmode4 *objp) { register int32_t *buf; if (!xdr_enum (xdrs, (enum_t *) objp)) return FALSE; return TRUE; } bool_t xdr_createhow4 (XDR *xdrs, createhow4 *objp) { register int32_t *buf; if (!xdr_createmode4 (xdrs, &objp->mode)) return FALSE; switch (objp->mode) { case UNCHECKED4: case GUARDED4: if (!xdr_fattr4 (xdrs, &objp->createhow4_u.createattrs)) return FALSE; break; case EXCLUSIVE4: if (!xdr_verifier4 (xdrs, objp->createhow4_u.createverf)) return FALSE; break; default: return FALSE; } return TRUE; } bool_t xdr_opentype4 (XDR *xdrs, opentype4 *objp) { register int32_t *buf; if (!xdr_enum (xdrs, (enum_t *) objp)) return FALSE; return TRUE; } bool_t xdr_openflag4 (XDR *xdrs, openflag4 *objp) { register int32_t *buf; if (!xdr_opentype4 (xdrs, &objp->opentype)) return FALSE; switch (objp->opentype) { case OPEN4_CREATE: if (!xdr_createhow4 (xdrs, &objp->openflag4_u.how)) return FALSE; break; default: break; } return TRUE; } bool_t xdr_limit_by4 (XDR *xdrs, limit_by4 *objp) { register int32_t *buf; if (!xdr_enum (xdrs, (enum_t *) objp)) return FALSE; return TRUE; } bool_t xdr_nfs_modified_limit4 (XDR *xdrs, nfs_modified_limit4 *objp) { register int32_t *buf; if (!xdr_uint32_t (xdrs, &objp->num_blocks)) return FALSE; if (!xdr_uint32_t (xdrs, &objp->bytes_per_block)) return FALSE; return TRUE; } bool_t xdr_nfs_space_limit4 (XDR *xdrs, nfs_space_limit4 *objp) { register int32_t *buf; if (!xdr_limit_by4 (xdrs, &objp->limitby)) return FALSE; switch (objp->limitby) { case NFS_LIMIT_SIZE: if (!xdr_uint64_t (xdrs, &objp->nfs_space_limit4_u.filesize)) return FALSE; break; case NFS_LIMIT_BLOCKS: if (!xdr_nfs_modified_limit4 (xdrs, &objp->nfs_space_limit4_u.mod_blocks)) return FALSE; break; default: return FALSE; } return TRUE; } bool_t xdr_open_delegation_type4 (XDR *xdrs, open_delegation_type4 *objp) { register int32_t *buf; if (!xdr_enum (xdrs, (enum_t *) objp)) return FALSE; return TRUE; } bool_t xdr_open_claim_type4 (XDR *xdrs, open_claim_type4 *objp) { register int32_t *buf; if (!xdr_enum (xdrs, (enum_t *) objp)) return FALSE; return TRUE; } bool_t xdr_open_claim_delegate_cur4 (XDR *xdrs, open_claim_delegate_cur4 *objp) { register int32_t *buf; if (!xdr_stateid4 (xdrs, &objp->delegate_stateid)) return FALSE; if (!xdr_component4 (xdrs, &objp->file)) return FALSE; return TRUE; } bool_t xdr_open_claim4 (XDR *xdrs, open_claim4 *objp) { register int32_t *buf; if (!xdr_open_claim_type4 (xdrs, &objp->claim)) return FALSE; switch (objp->claim) { case CLAIM_NULL: if (!xdr_component4 (xdrs, &objp->open_claim4_u.file)) return FALSE; break; case CLAIM_PREVIOUS: if (!xdr_open_delegation_type4 (xdrs, &objp->open_claim4_u.delegate_type)) return FALSE; break; case CLAIM_DELEGATE_CUR: if (!xdr_open_claim_delegate_cur4 (xdrs, &objp->open_claim4_u.delegate_cur_info)) return FALSE; break; case CLAIM_DELEGATE_PREV: if (!xdr_component4 (xdrs, &objp->open_claim4_u.file_delegate_prev)) return FALSE; break; default: return FALSE; } return TRUE; } bool_t xdr_OPEN4args (XDR *xdrs, OPEN4args *objp) { register int32_t *buf; if (!xdr_seqid4 (xdrs, &objp->seqid)) return FALSE; if (!xdr_uint32_t (xdrs, &objp->share_access)) return FALSE; if (!xdr_uint32_t (xdrs, &objp->share_deny)) return FALSE; if (!xdr_open_owner4 (xdrs, &objp->owner)) return FALSE; if (!xdr_openflag4 (xdrs, &objp->openhow)) return FALSE; if (!xdr_open_claim4 (xdrs, &objp->claim)) return FALSE; return TRUE; } bool_t xdr_open_read_delegation4 (XDR *xdrs, open_read_delegation4 *objp) { register int32_t *buf; if (!xdr_stateid4 (xdrs, &objp->stateid)) return FALSE; if (!xdr_bool (xdrs, &objp->recall)) return FALSE; if (!xdr_nfsace4 (xdrs, &objp->permissions)) return FALSE; return TRUE; } bool_t xdr_open_write_delegation4 (XDR *xdrs, open_write_delegation4 *objp) { register int32_t *buf; if (!xdr_stateid4 (xdrs, &objp->stateid)) return FALSE; if (!xdr_bool (xdrs, &objp->recall)) return FALSE; if (!xdr_nfs_space_limit4 (xdrs, &objp->space_limit)) return FALSE; if (!xdr_nfsace4 (xdrs, &objp->permissions)) return FALSE; return TRUE; } bool_t xdr_open_delegation4 (XDR *xdrs, open_delegation4 *objp) { register int32_t *buf; if (!xdr_open_delegation_type4 (xdrs, &objp->delegation_type)) return FALSE; switch (objp->delegation_type) { case OPEN_DELEGATE_NONE: break; case OPEN_DELEGATE_READ: if (!xdr_open_read_delegation4 (xdrs, &objp->open_delegation4_u.read)) return FALSE; break; case OPEN_DELEGATE_WRITE: if (!xdr_open_write_delegation4 (xdrs, &objp->open_delegation4_u.write)) return FALSE; break; default: return FALSE; } return TRUE; } bool_t xdr_OPEN4resok (XDR *xdrs, OPEN4resok *objp) { register int32_t *buf; if (!xdr_stateid4 (xdrs, &objp->stateid)) return FALSE; if (!xdr_change_info4 (xdrs, &objp->cinfo)) return FALSE; if (!xdr_uint32_t (xdrs, &objp->rflags)) return FALSE; if (!xdr_bitmap4 (xdrs, &objp->attrset)) return FALSE; if (!xdr_open_delegation4 (xdrs, &objp->delegation)) return FALSE; return TRUE; } bool_t xdr_OPEN4res (XDR *xdrs, OPEN4res *objp) { register int32_t *buf; if (!xdr_nfsstat4 (xdrs, &objp->status)) return FALSE; switch (objp->status) { case NFS4_OK: if (!xdr_OPEN4resok (xdrs, &objp->OPEN4res_u.resok4)) return FALSE; break; default: break; } return TRUE; } bool_t xdr_OPENATTR4args (XDR *xdrs, OPENATTR4args *objp) { register int32_t *buf; if (!xdr_bool (xdrs, &objp->createdir)) return FALSE; return TRUE; } bool_t xdr_OPENATTR4res (XDR *xdrs, OPENATTR4res *objp) { register int32_t *buf; if (!xdr_nfsstat4 (xdrs, &objp->status)) return FALSE; return TRUE; } bool_t xdr_OPEN_CONFIRM4args (XDR *xdrs, OPEN_CONFIRM4args *objp) { register int32_t *buf; if (!xdr_stateid4 (xdrs, &objp->open_stateid)) return FALSE; if (!xdr_seqid4 (xdrs, &objp->seqid)) return FALSE; return TRUE; } bool_t xdr_OPEN_CONFIRM4resok (XDR *xdrs, OPEN_CONFIRM4resok *objp) { register int32_t *buf; if (!xdr_stateid4 (xdrs, &objp->open_stateid)) return FALSE; return TRUE; } bool_t xdr_OPEN_CONFIRM4res (XDR *xdrs, OPEN_CONFIRM4res *objp) { register int32_t *buf; if (!xdr_nfsstat4 (xdrs, &objp->status)) return FALSE; switch (objp->status) { case NFS4_OK: if (!xdr_OPEN_CONFIRM4resok (xdrs, &objp->OPEN_CONFIRM4res_u.resok4)) return FALSE; break; default: break; } return TRUE; } bool_t xdr_OPEN_DOWNGRADE4args (XDR *xdrs, OPEN_DOWNGRADE4args *objp) { register int32_t *buf; if (!xdr_stateid4 (xdrs, &objp->open_stateid)) return FALSE; if (!xdr_seqid4 (xdrs, &objp->seqid)) return FALSE; if (!xdr_uint32_t (xdrs, &objp->share_access)) return FALSE; if (!xdr_uint32_t (xdrs, &objp->share_deny)) return FALSE; return TRUE; } bool_t xdr_OPEN_DOWNGRADE4resok (XDR *xdrs, OPEN_DOWNGRADE4resok *objp) { register int32_t *buf; if (!xdr_stateid4 (xdrs, &objp->open_stateid)) return FALSE; return TRUE; } bool_t xdr_OPEN_DOWNGRADE4res (XDR *xdrs, OPEN_DOWNGRADE4res *objp) { register int32_t *buf; if (!xdr_nfsstat4 (xdrs, &objp->status)) return FALSE; switch (objp->status) { case NFS4_OK: if (!xdr_OPEN_DOWNGRADE4resok (xdrs, &objp->OPEN_DOWNGRADE4res_u.resok4)) return FALSE; break; default: break; } return TRUE; } bool_t xdr_PUTFH4args (XDR *xdrs, PUTFH4args *objp) { register int32_t *buf; if (!xdr_nfs_fh4 (xdrs, &objp->object)) return FALSE; return TRUE; } bool_t xdr_PUTFH4res (XDR *xdrs, PUTFH4res *objp) { register int32_t *buf; if (!xdr_nfsstat4 (xdrs, &objp->status)) return FALSE; return TRUE; } bool_t xdr_PUTPUBFH4res (XDR *xdrs, PUTPUBFH4res *objp) { register int32_t *buf; if (!xdr_nfsstat4 (xdrs, &objp->status)) return FALSE; return TRUE; } bool_t xdr_PUTROOTFH4res (XDR *xdrs, PUTROOTFH4res *objp) { register int32_t *buf; if (!xdr_nfsstat4 (xdrs, &objp->status)) return FALSE; return TRUE; } bool_t xdr_READ4args (XDR *xdrs, READ4args *objp) { register int32_t *buf; if (!xdr_stateid4 (xdrs, &objp->stateid)) return FALSE; if (!xdr_offset4 (xdrs, &objp->offset)) return FALSE; if (!xdr_count4 (xdrs, &objp->count)) return FALSE; return TRUE; } bool_t xdr_READ4resok (XDR *xdrs, READ4resok *objp) { register int32_t *buf; if (!xdr_bool (xdrs, &objp->eof)) return FALSE; if (!xdr_bytes (xdrs, (char **)&objp->data.data_val, (u_int *) &objp->data.data_len, ~0)) return FALSE; return TRUE; } bool_t xdr_READ4res (XDR *xdrs, READ4res *objp) { register int32_t *buf; if (!xdr_nfsstat4 (xdrs, &objp->status)) return FALSE; switch (objp->status) { case NFS4_OK: if (!xdr_READ4resok (xdrs, &objp->READ4res_u.resok4)) return FALSE; break; default: break; } return TRUE; } bool_t xdr_READDIR4args (XDR *xdrs, READDIR4args *objp) { register int32_t *buf; if (!xdr_nfs_cookie4 (xdrs, &objp->cookie)) return FALSE; if (!xdr_verifier4 (xdrs, objp->cookieverf)) return FALSE; if (!xdr_count4 (xdrs, &objp->dircount)) return FALSE; if (!xdr_count4 (xdrs, &objp->maxcount)) return FALSE; if (!xdr_bitmap4 (xdrs, &objp->attr_request)) return FALSE; return TRUE; } bool_t xdr_entry4 (XDR *xdrs, entry4 *objp) { register int32_t *buf; if (!xdr_nfs_cookie4 (xdrs, &objp->cookie)) return FALSE; if (!xdr_component4 (xdrs, &objp->name)) return FALSE; if (!xdr_fattr4 (xdrs, &objp->attrs)) return FALSE; if (!xdr_pointer (xdrs, (char **)&objp->nextentry, sizeof (entry4), (xdrproc_t) xdr_entry4)) return FALSE; return TRUE; } bool_t xdr_dirlist4 (XDR *xdrs, dirlist4 *objp) { register int32_t *buf; if (!xdr_pointer (xdrs, (char **)&objp->entries, sizeof (entry4), (xdrproc_t) xdr_entry4)) return FALSE; if (!xdr_bool (xdrs, &objp->eof)) return FALSE; return TRUE; } bool_t xdr_READDIR4resok (XDR *xdrs, READDIR4resok *objp) { register int32_t *buf; if (!xdr_verifier4 (xdrs, objp->cookieverf)) return FALSE; if (!xdr_dirlist4 (xdrs, &objp->reply)) return FALSE; return TRUE; } bool_t xdr_READDIR4res (XDR *xdrs, READDIR4res *objp) { register int32_t *buf; if (!xdr_nfsstat4 (xdrs, &objp->status)) return FALSE; switch (objp->status) { case NFS4_OK: if (!xdr_READDIR4resok (xdrs, &objp->READDIR4res_u.resok4)) return FALSE; break; default: break; } return TRUE; } bool_t xdr_READLINK4resok (XDR *xdrs, READLINK4resok *objp) { register int32_t *buf; if (!xdr_linktext4 (xdrs, &objp->link)) return FALSE; return TRUE; } bool_t xdr_READLINK4res (XDR *xdrs, READLINK4res *objp) { register int32_t *buf; if (!xdr_nfsstat4 (xdrs, &objp->status)) return FALSE; switch (objp->status) { case NFS4_OK: if (!xdr_READLINK4resok (xdrs, &objp->READLINK4res_u.resok4)) return FALSE; break; default: break; } return TRUE; } bool_t xdr_REMOVE4args (XDR *xdrs, REMOVE4args *objp) { register int32_t *buf; if (!xdr_component4 (xdrs, &objp->target)) return FALSE; return TRUE; } bool_t xdr_REMOVE4resok (XDR *xdrs, REMOVE4resok *objp) { register int32_t *buf; if (!xdr_change_info4 (xdrs, &objp->cinfo)) return FALSE; return TRUE; } bool_t xdr_REMOVE4res (XDR *xdrs, REMOVE4res *objp) { register int32_t *buf; if (!xdr_nfsstat4 (xdrs, &objp->status)) return FALSE; switch (objp->status) { case NFS4_OK: if (!xdr_REMOVE4resok (xdrs, &objp->REMOVE4res_u.resok4)) return FALSE; break; default: break; } return TRUE; } bool_t xdr_RENAME4args (XDR *xdrs, RENAME4args *objp) { register int32_t *buf; if (!xdr_component4 (xdrs, &objp->oldname)) return FALSE; if (!xdr_component4 (xdrs, &objp->newname)) return FALSE; return TRUE; } bool_t xdr_RENAME4resok (XDR *xdrs, RENAME4resok *objp) { register int32_t *buf; if (!xdr_change_info4 (xdrs, &objp->source_cinfo)) return FALSE; if (!xdr_change_info4 (xdrs, &objp->target_cinfo)) return FALSE; return TRUE; } bool_t xdr_RENAME4res (XDR *xdrs, RENAME4res *objp) { register int32_t *buf; if (!xdr_nfsstat4 (xdrs, &objp->status)) return FALSE; switch (objp->status) { case NFS4_OK: if (!xdr_RENAME4resok (xdrs, &objp->RENAME4res_u.resok4)) return FALSE; break; default: break; } return TRUE; } bool_t xdr_RENEW4args (XDR *xdrs, RENEW4args *objp) { register int32_t *buf; if (!xdr_clientid4 (xdrs, &objp->clientid)) return FALSE; return TRUE; } bool_t xdr_RENEW4res (XDR *xdrs, RENEW4res *objp) { register int32_t *buf; if (!xdr_nfsstat4 (xdrs, &objp->status)) return FALSE; return TRUE; } bool_t xdr_RESTOREFH4res (XDR *xdrs, RESTOREFH4res *objp) { register int32_t *buf; if (!xdr_nfsstat4 (xdrs, &objp->status)) return FALSE; return TRUE; } bool_t xdr_SAVEFH4res (XDR *xdrs, SAVEFH4res *objp) { register int32_t *buf; if (!xdr_nfsstat4 (xdrs, &objp->status)) return FALSE; return TRUE; } bool_t xdr_SECINFO4args (XDR *xdrs, SECINFO4args *objp) { register int32_t *buf; if (!xdr_component4 (xdrs, &objp->name)) return FALSE; return TRUE; } bool_t xdr_rpc_gss_svc_t (XDR *xdrs, rpc_gss_svc_t *objp) { register int32_t *buf; if (!xdr_enum (xdrs, (enum_t *) objp)) return FALSE; return TRUE; } bool_t xdr_rpcsec_gss_info (XDR *xdrs, rpcsec_gss_info *objp) { register int32_t *buf; if (!xdr_sec_oid4 (xdrs, &objp->oid)) return FALSE; if (!xdr_qop4 (xdrs, &objp->qop)) return FALSE; if (!xdr_rpc_gss_svc_t (xdrs, &objp->service)) return FALSE; return TRUE; } bool_t xdr_secinfo4 (XDR *xdrs, secinfo4 *objp) { register int32_t *buf; if (!xdr_uint32_t (xdrs, &objp->flavor)) return FALSE; return TRUE; } bool_t xdr_SECINFO4resok (XDR *xdrs, SECINFO4resok *objp) { register int32_t *buf; if (!xdr_array (xdrs, (char **)&objp->SECINFO4resok_val, (u_int *) &objp->SECINFO4resok_len, ~0, sizeof (secinfo4), (xdrproc_t) xdr_secinfo4)) return FALSE; return TRUE; } bool_t xdr_SECINFO4res (XDR *xdrs, SECINFO4res *objp) { register int32_t *buf; if (!xdr_nfsstat4 (xdrs, &objp->status)) return FALSE; switch (objp->status) { case NFS4_OK: if (!xdr_SECINFO4resok (xdrs, &objp->SECINFO4res_u.resok4)) return FALSE; break; default: break; } return TRUE; } bool_t xdr_SETATTR4args (XDR *xdrs, SETATTR4args *objp) { register int32_t *buf; if (!xdr_stateid4 (xdrs, &objp->stateid)) return FALSE; if (!xdr_fattr4 (xdrs, &objp->obj_attributes)) return FALSE; return TRUE; } bool_t xdr_SETATTR4res (XDR *xdrs, SETATTR4res *objp) { register int32_t *buf; if (!xdr_nfsstat4 (xdrs, &objp->status)) return FALSE; if (!xdr_bitmap4 (xdrs, &objp->attrsset)) return FALSE; return TRUE; } bool_t xdr_SETCLIENTID4args (XDR *xdrs, SETCLIENTID4args *objp) { register int32_t *buf; if (!xdr_nfs_client_id4 (xdrs, &objp->client)) return FALSE; if (!xdr_cb_client4 (xdrs, &objp->callback)) return FALSE; if (!xdr_uint32_t (xdrs, &objp->callback_ident)) return FALSE; return TRUE; } bool_t xdr_SETCLIENTID4resok (XDR *xdrs, SETCLIENTID4resok *objp) { register int32_t *buf; if (!xdr_clientid4 (xdrs, &objp->clientid)) return FALSE; if (!xdr_verifier4 (xdrs, objp->setclientid_confirm)) return FALSE; return TRUE; } bool_t xdr_SETCLIENTID4res (XDR *xdrs, SETCLIENTID4res *objp) { register int32_t *buf; if (!xdr_nfsstat4 (xdrs, &objp->status)) return FALSE; switch (objp->status) { case NFS4_OK: if (!xdr_SETCLIENTID4resok (xdrs, &objp->SETCLIENTID4res_u.resok4)) return FALSE; break; case NFS4ERR_CLID_INUSE: if (!xdr_clientaddr4 (xdrs, &objp->SETCLIENTID4res_u.client_using)) return FALSE; break; default: break; } return TRUE; } bool_t xdr_SETCLIENTID_CONFIRM4args (XDR *xdrs, SETCLIENTID_CONFIRM4args *objp) { register int32_t *buf; if (!xdr_clientid4 (xdrs, &objp->clientid)) return FALSE; if (!xdr_verifier4 (xdrs, objp->setclientid_confirm)) return FALSE; return TRUE; } bool_t xdr_SETCLIENTID_CONFIRM4res (XDR *xdrs, SETCLIENTID_CONFIRM4res *objp) { register int32_t *buf; if (!xdr_nfsstat4 (xdrs, &objp->status)) return FALSE; return TRUE; } bool_t xdr_VERIFY4args (XDR *xdrs, VERIFY4args *objp) { register int32_t *buf; if (!xdr_fattr4 (xdrs, &objp->obj_attributes)) return FALSE; return TRUE; } bool_t xdr_VERIFY4res (XDR *xdrs, VERIFY4res *objp) { register int32_t *buf; if (!xdr_nfsstat4 (xdrs, &objp->status)) return FALSE; return TRUE; } bool_t xdr_stable_how4 (XDR *xdrs, stable_how4 *objp) { register int32_t *buf; if (!xdr_enum (xdrs, (enum_t *) objp)) return FALSE; return TRUE; } bool_t xdr_WRITE4args (XDR *xdrs, WRITE4args *objp) { register int32_t *buf; if (!xdr_stateid4 (xdrs, &objp->stateid)) return FALSE; if (!xdr_offset4 (xdrs, &objp->offset)) return FALSE; if (!xdr_stable_how4 (xdrs, &objp->stable)) return FALSE; if (!xdr_bytes (xdrs, (char **)&objp->data.data_val, (u_int *) &objp->data.data_len, ~0)) return FALSE; return TRUE; } bool_t xdr_WRITE4resok (XDR *xdrs, WRITE4resok *objp) { register int32_t *buf; if (!xdr_count4 (xdrs, &objp->count)) return FALSE; if (!xdr_stable_how4 (xdrs, &objp->committed)) return FALSE; if (!xdr_verifier4 (xdrs, objp->writeverf)) return FALSE; return TRUE; } bool_t xdr_WRITE4res (XDR *xdrs, WRITE4res *objp) { register int32_t *buf; if (!xdr_nfsstat4 (xdrs, &objp->status)) return FALSE; switch (objp->status) { case NFS4_OK: if (!xdr_WRITE4resok (xdrs, &objp->WRITE4res_u.resok4)) return FALSE; break; default: break; } return TRUE; } bool_t xdr_RELEASE_LOCKOWNER4args (XDR *xdrs, RELEASE_LOCKOWNER4args *objp) { register int32_t *buf; if (!xdr_lock_owner4 (xdrs, &objp->lock_owner)) return FALSE; return TRUE; } bool_t xdr_RELEASE_LOCKOWNER4res (XDR *xdrs, RELEASE_LOCKOWNER4res *objp) { register int32_t *buf; if (!xdr_nfsstat4 (xdrs, &objp->status)) return FALSE; return TRUE; } bool_t xdr_ILLEGAL4res (XDR *xdrs, ILLEGAL4res *objp) { register int32_t *buf; if (!xdr_nfsstat4 (xdrs, &objp->status)) return FALSE; return TRUE; } bool_t xdr_nfs_opnum4 (XDR *xdrs, nfs_opnum4 *objp) { register int32_t *buf; if (!xdr_enum (xdrs, (enum_t *) objp)) return FALSE; return TRUE; } bool_t xdr_nfs_argop4 (XDR *xdrs, nfs_argop4 *objp) { register int32_t *buf; if (!xdr_nfs_opnum4 (xdrs, &objp->argop)) return FALSE; switch (objp->argop) { case OP_ACCESS: if (!xdr_ACCESS4args (xdrs, &objp->nfs_argop4_u.opaccess)) return FALSE; break; case OP_CLOSE: if (!xdr_CLOSE4args (xdrs, &objp->nfs_argop4_u.opclose)) return FALSE; break; case OP_COMMIT: if (!xdr_COMMIT4args (xdrs, &objp->nfs_argop4_u.opcommit)) return FALSE; break; case OP_CREATE: if (!xdr_CREATE4args (xdrs, &objp->nfs_argop4_u.opcreate)) return FALSE; break; case OP_DELEGPURGE: if (!xdr_DELEGPURGE4args (xdrs, &objp->nfs_argop4_u.opdelegpurge)) return FALSE; break; case OP_DELEGRETURN: if (!xdr_DELEGRETURN4args (xdrs, &objp->nfs_argop4_u.opdelegreturn)) return FALSE; break; case OP_GETATTR: if (!xdr_GETATTR4args (xdrs, &objp->nfs_argop4_u.opgetattr)) return FALSE; break; case OP_GETFH: break; case OP_LINK: if (!xdr_LINK4args (xdrs, &objp->nfs_argop4_u.oplink)) return FALSE; break; case OP_LOCK: if (!xdr_LOCK4args (xdrs, &objp->nfs_argop4_u.oplock)) return FALSE; break; case OP_LOCKT: if (!xdr_LOCKT4args (xdrs, &objp->nfs_argop4_u.oplockt)) return FALSE; break; case OP_LOCKU: if (!xdr_LOCKU4args (xdrs, &objp->nfs_argop4_u.oplocku)) return FALSE; break; case OP_LOOKUP: if (!xdr_LOOKUP4args (xdrs, &objp->nfs_argop4_u.oplookup)) return FALSE; break; case OP_LOOKUPP: break; case OP_NVERIFY: if (!xdr_NVERIFY4args (xdrs, &objp->nfs_argop4_u.opnverify)) return FALSE; break; case OP_OPEN: if (!xdr_OPEN4args (xdrs, &objp->nfs_argop4_u.opopen)) return FALSE; break; case OP_OPENATTR: if (!xdr_OPENATTR4args (xdrs, &objp->nfs_argop4_u.opopenattr)) return FALSE; break; case OP_OPEN_CONFIRM: if (!xdr_OPEN_CONFIRM4args (xdrs, &objp->nfs_argop4_u.opopen_confirm)) return FALSE; break; case OP_OPEN_DOWNGRADE: if (!xdr_OPEN_DOWNGRADE4args (xdrs, &objp->nfs_argop4_u.opopen_downgrade)) return FALSE; break; case OP_PUTFH: if (!xdr_PUTFH4args (xdrs, &objp->nfs_argop4_u.opputfh)) return FALSE; break; case OP_PUTPUBFH: break; case OP_PUTROOTFH: break; case OP_READ: if (!xdr_READ4args (xdrs, &objp->nfs_argop4_u.opread)) return FALSE; break; case OP_READDIR: if (!xdr_READDIR4args (xdrs, &objp->nfs_argop4_u.opreaddir)) return FALSE; break; case OP_READLINK: break; case OP_REMOVE: if (!xdr_REMOVE4args (xdrs, &objp->nfs_argop4_u.opremove)) return FALSE; break; case OP_RENAME: if (!xdr_RENAME4args (xdrs, &objp->nfs_argop4_u.oprename)) return FALSE; break; case OP_RENEW: if (!xdr_RENEW4args (xdrs, &objp->nfs_argop4_u.oprenew)) return FALSE; break; case OP_RESTOREFH: break; case OP_SAVEFH: break; case OP_SECINFO: if (!xdr_SECINFO4args (xdrs, &objp->nfs_argop4_u.opsecinfo)) return FALSE; break; case OP_SETATTR: if (!xdr_SETATTR4args (xdrs, &objp->nfs_argop4_u.opsetattr)) return FALSE; break; case OP_SETCLIENTID: if (!xdr_SETCLIENTID4args (xdrs, &objp->nfs_argop4_u.opsetclientid)) return FALSE; break; case OP_SETCLIENTID_CONFIRM: if (!xdr_SETCLIENTID_CONFIRM4args (xdrs, &objp->nfs_argop4_u.opsetclientid_confirm)) return FALSE; break; case OP_VERIFY: if (!xdr_VERIFY4args (xdrs, &objp->nfs_argop4_u.opverify)) return FALSE; break; case OP_WRITE: if (!xdr_WRITE4args (xdrs, &objp->nfs_argop4_u.opwrite)) return FALSE; break; case OP_RELEASE_LOCKOWNER: if (!xdr_RELEASE_LOCKOWNER4args (xdrs, &objp->nfs_argop4_u.oprelease_lockowner)) return FALSE; break; case OP_ILLEGAL: break; default: return FALSE; } return TRUE; } bool_t xdr_nfs_resop4 (XDR *xdrs, nfs_resop4 *objp) { register int32_t *buf; if (!xdr_nfs_opnum4 (xdrs, &objp->resop)) return FALSE; switch (objp->resop) { case OP_ACCESS: if (!xdr_ACCESS4res (xdrs, &objp->nfs_resop4_u.opaccess)) return FALSE; break; case OP_CLOSE: if (!xdr_CLOSE4res (xdrs, &objp->nfs_resop4_u.opclose)) return FALSE; break; case OP_COMMIT: if (!xdr_COMMIT4res (xdrs, &objp->nfs_resop4_u.opcommit)) return FALSE; break; case OP_CREATE: if (!xdr_CREATE4res (xdrs, &objp->nfs_resop4_u.opcreate)) return FALSE; break; case OP_DELEGPURGE: if (!xdr_DELEGPURGE4res (xdrs, &objp->nfs_resop4_u.opdelegpurge)) return FALSE; break; case OP_DELEGRETURN: if (!xdr_DELEGRETURN4res (xdrs, &objp->nfs_resop4_u.opdelegreturn)) return FALSE; break; case OP_GETATTR: if (!xdr_GETATTR4res (xdrs, &objp->nfs_resop4_u.opgetattr)) return FALSE; break; case OP_GETFH: if (!xdr_GETFH4res (xdrs, &objp->nfs_resop4_u.opgetfh)) return FALSE; break; case OP_LINK: if (!xdr_LINK4res (xdrs, &objp->nfs_resop4_u.oplink)) return FALSE; break; case OP_LOCK: if (!xdr_LOCK4res (xdrs, &objp->nfs_resop4_u.oplock)) return FALSE; break; case OP_LOCKT: if (!xdr_LOCKT4res (xdrs, &objp->nfs_resop4_u.oplockt)) return FALSE; break; case OP_LOCKU: if (!xdr_LOCKU4res (xdrs, &objp->nfs_resop4_u.oplocku)) return FALSE; break; case OP_LOOKUP: if (!xdr_LOOKUP4res (xdrs, &objp->nfs_resop4_u.oplookup)) return FALSE; break; case OP_LOOKUPP: if (!xdr_LOOKUPP4res (xdrs, &objp->nfs_resop4_u.oplookupp)) return FALSE; break; case OP_NVERIFY: if (!xdr_NVERIFY4res (xdrs, &objp->nfs_resop4_u.opnverify)) return FALSE; break; case OP_OPEN: if (!xdr_OPEN4res (xdrs, &objp->nfs_resop4_u.opopen)) return FALSE; break; case OP_OPENATTR: if (!xdr_OPENATTR4res (xdrs, &objp->nfs_resop4_u.opopenattr)) return FALSE; break; case OP_OPEN_CONFIRM: if (!xdr_OPEN_CONFIRM4res (xdrs, &objp->nfs_resop4_u.opopen_confirm)) return FALSE; break; case OP_OPEN_DOWNGRADE: if (!xdr_OPEN_DOWNGRADE4res (xdrs, &objp->nfs_resop4_u.opopen_downgrade)) return FALSE; break; case OP_PUTFH: if (!xdr_PUTFH4res (xdrs, &objp->nfs_resop4_u.opputfh)) return FALSE; break; case OP_PUTPUBFH: if (!xdr_PUTPUBFH4res (xdrs, &objp->nfs_resop4_u.opputpubfh)) return FALSE; break; case OP_PUTROOTFH: if (!xdr_PUTROOTFH4res (xdrs, &objp->nfs_resop4_u.opputrootfh)) return FALSE; break; case OP_READ: if (!xdr_READ4res (xdrs, &objp->nfs_resop4_u.opread)) return FALSE; break; case OP_READDIR: if (!xdr_READDIR4res (xdrs, &objp->nfs_resop4_u.opreaddir)) return FALSE; break; case OP_READLINK: if (!xdr_READLINK4res (xdrs, &objp->nfs_resop4_u.opreadlink)) return FALSE; break; case OP_REMOVE: if (!xdr_REMOVE4res (xdrs, &objp->nfs_resop4_u.opremove)) return FALSE; break; case OP_RENAME: if (!xdr_RENAME4res (xdrs, &objp->nfs_resop4_u.oprename)) return FALSE; break; case OP_RENEW: if (!xdr_RENEW4res (xdrs, &objp->nfs_resop4_u.oprenew)) return FALSE; break; case OP_RESTOREFH: if (!xdr_RESTOREFH4res (xdrs, &objp->nfs_resop4_u.oprestorefh)) return FALSE; break; case OP_SAVEFH: if (!xdr_SAVEFH4res (xdrs, &objp->nfs_resop4_u.opsavefh)) return FALSE; break; case OP_SECINFO: if (!xdr_SECINFO4res (xdrs, &objp->nfs_resop4_u.opsecinfo)) return FALSE; break; case OP_SETATTR: if (!xdr_SETATTR4res (xdrs, &objp->nfs_resop4_u.opsetattr)) return FALSE; break; case OP_SETCLIENTID: if (!xdr_SETCLIENTID4res (xdrs, &objp->nfs_resop4_u.opsetclientid)) return FALSE; break; case OP_SETCLIENTID_CONFIRM: if (!xdr_SETCLIENTID_CONFIRM4res (xdrs, &objp->nfs_resop4_u.opsetclientid_confirm)) return FALSE; break; case OP_VERIFY: if (!xdr_VERIFY4res (xdrs, &objp->nfs_resop4_u.opverify)) return FALSE; break; case OP_WRITE: if (!xdr_WRITE4res (xdrs, &objp->nfs_resop4_u.opwrite)) return FALSE; break; case OP_RELEASE_LOCKOWNER: if (!xdr_RELEASE_LOCKOWNER4res (xdrs, &objp->nfs_resop4_u.oprelease_lockowner)) return FALSE; break; case OP_ILLEGAL: if (!xdr_ILLEGAL4res (xdrs, &objp->nfs_resop4_u.opillegal)) return FALSE; break; default: return FALSE; } return TRUE; } bool_t xdr_COMPOUND4args (XDR *xdrs, COMPOUND4args *objp) { register int32_t *buf; if (!xdr_utf8str_cs (xdrs, &objp->tag)) return FALSE; if (!xdr_uint32_t (xdrs, &objp->minorversion)) return FALSE; if (!xdr_array (xdrs, (char **)&objp->argarray.argarray_val, (u_int *) &objp->argarray.argarray_len, ~0, sizeof (nfs_argop4), (xdrproc_t) xdr_nfs_argop4)) return FALSE; return TRUE; } bool_t xdr_COMPOUND4res (XDR *xdrs, COMPOUND4res *objp) { register int32_t *buf; if (!xdr_nfsstat4 (xdrs, &objp->status)) return FALSE; if (!xdr_utf8str_cs (xdrs, &objp->tag)) return FALSE; if (!xdr_array (xdrs, (char **)&objp->resarray.resarray_val, (u_int *) &objp->resarray.resarray_len, ~0, sizeof (nfs_resop4), (xdrproc_t) xdr_nfs_resop4)) return FALSE; return TRUE; } bool_t xdr_CB_GETATTR4args (XDR *xdrs, CB_GETATTR4args *objp) { register int32_t *buf; if (!xdr_nfs_fh4 (xdrs, &objp->fh)) return FALSE; if (!xdr_bitmap4 (xdrs, &objp->attr_request)) return FALSE; return TRUE; } bool_t xdr_CB_GETATTR4resok (XDR *xdrs, CB_GETATTR4resok *objp) { register int32_t *buf; if (!xdr_fattr4 (xdrs, &objp->obj_attributes)) return FALSE; return TRUE; } bool_t xdr_CB_GETATTR4res (XDR *xdrs, CB_GETATTR4res *objp) { register int32_t *buf; if (!xdr_nfsstat4 (xdrs, &objp->status)) return FALSE; switch (objp->status) { case NFS4_OK: if (!xdr_CB_GETATTR4resok (xdrs, &objp->CB_GETATTR4res_u.resok4)) return FALSE; break; default: break; } return TRUE; } bool_t xdr_CB_RECALL4args (XDR *xdrs, CB_RECALL4args *objp) { register int32_t *buf; if (!xdr_stateid4 (xdrs, &objp->stateid)) return FALSE; if (!xdr_bool (xdrs, &objp->truncate)) return FALSE; if (!xdr_nfs_fh4 (xdrs, &objp->fh)) return FALSE; return TRUE; } bool_t xdr_CB_RECALL4res (XDR *xdrs, CB_RECALL4res *objp) { register int32_t *buf; if (!xdr_nfsstat4 (xdrs, &objp->status)) return FALSE; return TRUE; } bool_t xdr_CB_ILLEGAL4res (XDR *xdrs, CB_ILLEGAL4res *objp) { register int32_t *buf; if (!xdr_nfsstat4 (xdrs, &objp->status)) return FALSE; return TRUE; } bool_t xdr_nfs_cb_opnum4 (XDR *xdrs, nfs_cb_opnum4 *objp) { register int32_t *buf; if (!xdr_enum (xdrs, (enum_t *) objp)) return FALSE; return TRUE; } bool_t xdr_nfs_cb_argop4 (XDR *xdrs, nfs_cb_argop4 *objp) { register int32_t *buf; if (!xdr_u_int (xdrs, &objp->argop)) return FALSE; switch (objp->argop) { case NFS4_OP_CB_GETATTR: if (!xdr_CB_GETATTR4args (xdrs, &objp->nfs_cb_argop4_u.opcbgetattr)) return FALSE; break; case NFS4_OP_CB_RECALL: if (!xdr_CB_RECALL4args (xdrs, &objp->nfs_cb_argop4_u.opcbrecall)) return FALSE; break; case NFS4_OP_CB_ILLEGAL: break; default: return FALSE; } return TRUE; } bool_t xdr_nfs_cb_resop4 (XDR *xdrs, nfs_cb_resop4 *objp) { register int32_t *buf; if (!xdr_u_int (xdrs, &objp->resop)) return FALSE; switch (objp->resop) { case NFS4_OP_CB_GETATTR: if (!xdr_CB_GETATTR4res (xdrs, &objp->nfs_cb_resop4_u.opcbgetattr)) return FALSE; break; case NFS4_OP_CB_RECALL: if (!xdr_CB_RECALL4res (xdrs, &objp->nfs_cb_resop4_u.opcbrecall)) return FALSE; break; case NFS4_OP_CB_ILLEGAL: if (!xdr_CB_ILLEGAL4res (xdrs, &objp->nfs_cb_resop4_u.opcbillegal)) return FALSE; break; default: return FALSE; } return TRUE; } bool_t xdr_CB_COMPOUND4args (XDR *xdrs, CB_COMPOUND4args *objp) { register int32_t *buf; if (!xdr_utf8str_cs (xdrs, &objp->tag)) return FALSE; if (!xdr_uint32_t (xdrs, &objp->minorversion)) return FALSE; if (!xdr_uint32_t (xdrs, &objp->callback_ident)) return FALSE; if (!xdr_array (xdrs, (char **)&objp->argarray.argarray_val, (u_int *) &objp->argarray.argarray_len, ~0, sizeof (nfs_cb_argop4), (xdrproc_t) xdr_nfs_cb_argop4)) return FALSE; return TRUE; } bool_t xdr_CB_COMPOUND4res (XDR *xdrs, CB_COMPOUND4res *objp) { register int32_t *buf; if (!xdr_nfsstat4 (xdrs, &objp->status)) return FALSE; if (!xdr_utf8str_cs (xdrs, &objp->tag)) return FALSE; if (!xdr_array (xdrs, (char **)&objp->resarray.resarray_val, (u_int *) &objp->resarray.resarray_len, ~0, sizeof (nfs_cb_resop4), (xdrproc_t) xdr_nfs_cb_resop4)) return FALSE; return TRUE; } <file_sep>/* * Please do not edit this file. * It was generated using rpcgen. */ #ifndef _NFS4_H_RPCGEN #define _NFS4_H_RPCGEN #include <rpc/rpc.h> #ifdef __cplusplus extern "C" { #endif typedef int int32_t; typedef u_int uint32_t; typedef quad_t int64_t; typedef u_quad_t uint64_t; #define NFS4_FHSIZE 128 #define NFS4_VERIFIER_SIZE 8 #define NFS4_OPAQUE_LIMIT 1024 enum nfs_ftype4 { NF4REG = 1, NF4DIR = 2, NF4BLK = 3, NF4CHR = 4, NF4LNK = 5, NF4SOCK = 6, NF4FIFO = 7, NF4ATTRDIR = 8, NF4NAMEDATTR = 9, }; typedef enum nfs_ftype4 nfs_ftype4; enum nfsstat4 { NFS4_OK = 0, NFS4ERR_PERM = 1, NFS4ERR_NOENT = 2, NFS4ERR_IO = 5, NFS4ERR_NXIO = 6, NFS4ERR_ACCESS = 13, NFS4ERR_EXIST = 17, NFS4ERR_XDEV = 18, NFS4ERR_NOTDIR = 20, NFS4ERR_ISDIR = 21, NFS4ERR_INVAL = 22, NFS4ERR_FBIG = 27, NFS4ERR_NOSPC = 28, NFS4ERR_ROFS = 30, NFS4ERR_MLINK = 31, NFS4ERR_NAMETOOLONG = 63, NFS4ERR_NOTEMPTY = 66, NFS4ERR_DQUOT = 69, NFS4ERR_STALE = 70, NFS4ERR_BADHANDLE = 10001, NFS4ERR_BAD_COOKIE = 10003, NFS4ERR_NOTSUPP = 10004, NFS4ERR_TOOSMALL = 10005, NFS4ERR_SERVERFAULT = 10006, NFS4ERR_BADTYPE = 10007, NFS4ERR_DELAY = 10008, NFS4ERR_SAME = 10009, NFS4ERR_DENIED = 10010, NFS4ERR_EXPIRED = 10011, NFS4ERR_LOCKED = 10012, NFS4ERR_GRACE = 10013, NFS4ERR_FHEXPIRED = 10014, NFS4ERR_SHARE_DENIED = 10015, NFS4ERR_WRONGSEC = 10016, NFS4ERR_CLID_INUSE = 10017, NFS4ERR_RESOURCE = 10018, NFS4ERR_MOVED = 10019, NFS4ERR_NOFILEHANDLE = 10020, NFS4ERR_MINOR_VERS_MISMATCH = 10021, NFS4ERR_STALE_CLIENTID = 10022, NFS4ERR_STALE_STATEID = 10023, NFS4ERR_OLD_STATEID = 10024, NFS4ERR_BAD_STATEID = 10025, NFS4ERR_BAD_SEQID = 10026, NFS4ERR_NOT_SAME = 10027, NFS4ERR_LOCK_RANGE = 10028, NFS4ERR_SYMLINK = 10029, NFS4ERR_RESTOREFH = 10030, NFS4ERR_LEASE_MOVED = 10031, NFS4ERR_ATTRNOTSUPP = 10032, NFS4ERR_NO_GRACE = 10033, NFS4ERR_RECLAIM_BAD = 10034, NFS4ERR_RECLAIM_CONFLICT = 10035, NFS4ERR_BADXDR = 10036, NFS4ERR_LOCKS_HELD = 10037, NFS4ERR_OPENMODE = 10038, NFS4ERR_BADOWNER = 10039, NFS4ERR_BADCHAR = 10040, NFS4ERR_BADNAME = 10041, NFS4ERR_BAD_RANGE = 10042, NFS4ERR_LOCK_NOTSUPP = 10043, NFS4ERR_OP_ILLEGAL = 10044, NFS4ERR_DEADLOCK = 10045, NFS4ERR_FILE_OPEN = 10046, NFS4ERR_ADMIN_REVOKED = 10047, NFS4ERR_CB_PATH_DOWN = 10048, }; typedef enum nfsstat4 nfsstat4; typedef struct { u_int bitmap4_len; uint32_t *bitmap4_val; } bitmap4; typedef uint64_t offset4; typedef uint32_t count4; typedef uint64_t length4; typedef uint64_t clientid4; typedef uint32_t seqid4; typedef struct { u_int utf8string_len; char *utf8string_val; } utf8string; typedef utf8string utf8str_cis; typedef utf8string utf8str_cs; typedef utf8string utf8str_mixed; typedef utf8str_cs component4; typedef struct { u_int pathname4_len; component4 *pathname4_val; } pathname4; typedef uint64_t nfs_lockid4; typedef uint64_t nfs_cookie4; typedef utf8str_cs linktext4; typedef struct { u_int sec_oid4_len; char *sec_oid4_val; } sec_oid4; typedef uint32_t qop4; typedef uint32_t mode4; typedef uint64_t changeid4; typedef char verifier4[NFS4_VERIFIER_SIZE]; struct nfstime4 { int64_t seconds; uint32_t nseconds; }; typedef struct nfstime4 nfstime4; enum time_how4 { SET_TO_SERVER_TIME4 = 0, SET_TO_CLIENT_TIME4 = 1, }; typedef enum time_how4 time_how4; struct settime4 { time_how4 set_it; union { nfstime4 time; } settime4_u; }; typedef struct settime4 settime4; typedef struct { u_int nfs_fh4_len; char *nfs_fh4_val; } nfs_fh4; struct fsid4 { uint64_t major; uint64_t minor; }; typedef struct fsid4 fsid4; struct fs_location4 { struct { u_int server_len; utf8str_cis *server_val; } server; pathname4 rootpath; }; typedef struct fs_location4 fs_location4; struct fs_locations4 { pathname4 fs_root; struct { u_int locations_len; fs_location4 *locations_val; } locations; }; typedef struct fs_locations4 fs_locations4; #define ACL4_SUPPORT_ALLOW_ACL 0x00000001 #define ACL4_SUPPORT_DENY_ACL 0x00000002 #define ACL4_SUPPORT_AUDIT_ACL 0x00000004 #define ACL4_SUPPORT_ALARM_ACL 0x00000008 typedef uint32_t acetype4; #define ACE4_ACCESS_ALLOWED_ACE_TYPE 0x00000000 #define ACE4_ACCESS_DENIED_ACE_TYPE 0x00000001 #define ACE4_SYSTEM_AUDIT_ACE_TYPE 0x00000002 #define ACE4_SYSTEM_ALARM_ACE_TYPE 0x00000003 typedef uint32_t aceflag4; #define ACE4_FILE_INHERIT_ACE 0x00000001 #define ACE4_DIRECTORY_INHERIT_ACE 0x00000002 #define ACE4_NO_PROPAGATE_INHERIT_ACE 0x00000004 #define ACE4_INHERIT_ONLY_ACE 0x00000008 #define ACE4_SUCCESSFUL_ACCESS_ACE_FLAG 0x00000010 #define ACE4_FAILED_ACCESS_ACE_FLAG 0x00000020 #define ACE4_IDENTIFIER_GROUP 0x00000040 typedef uint32_t acemask4; #define ACE4_READ_DATA 0x00000001 #define ACE4_LIST_DIRECTORY 0x00000001 #define ACE4_WRITE_DATA 0x00000002 #define ACE4_ADD_FILE 0x00000002 #define ACE4_APPEND_DATA 0x00000004 #define ACE4_ADD_SUBDIRECTORY 0x00000004 #define ACE4_READ_NAMED_ATTRS 0x00000008 #define ACE4_WRITE_NAMED_ATTRS 0x00000010 #define ACE4_EXECUTE 0x00000020 #define ACE4_DELETE_CHILD 0x00000040 #define ACE4_READ_ATTRIBUTES 0x00000080 #define ACE4_WRITE_ATTRIBUTES 0x00000100 #define ACE4_DELETE 0x00010000 #define ACE4_READ_ACL 0x00020000 #define ACE4_WRITE_ACL 0x00040000 #define ACE4_WRITE_OWNER 0x00080000 #define ACE4_SYNCHRONIZE 0x00100000 #define ACE4_GENERIC_READ 0x00120081 #define ACE4_GENERIC_WRITE 0x00160106 #define ACE4_GENERIC_EXECUTE 0x001200A0 struct nfsace4 { acetype4 type; aceflag4 flag; acemask4 access_mask; utf8str_mixed who; }; typedef struct nfsace4 nfsace4; #define MODE4_SUID 0x800 #define MODE4_SGID 0x400 #define MODE4_SVTX 0x200 #define MODE4_RUSR 0x100 #define MODE4_WUSR 0x080 #define MODE4_XUSR 0x040 #define MODE4_RGRP 0x020 #define MODE4_WGRP 0x010 #define MODE4_XGRP 0x008 #define MODE4_ROTH 0x004 #define MODE4_WOTH 0x002 #define MODE4_XOTH 0x001 struct specdata4 { uint32_t specdata1; uint32_t specdata2; }; typedef struct specdata4 specdata4; #define FH4_PERSISTENT 0x00000000 #define FH4_NOEXPIRE_WITH_OPEN 0x00000001 #define FH4_VOLATILE_ANY 0x00000002 #define FH4_VOL_MIGRATION 0x00000004 #define FH4_VOL_RENAME 0x00000008 typedef bitmap4 fattr4_supported_attrs; typedef nfs_ftype4 fattr4_type; typedef uint32_t fattr4_fh_expire_type; typedef changeid4 fattr4_change; typedef uint64_t fattr4_size; typedef bool_t fattr4_link_support; typedef bool_t fattr4_symlink_support; typedef bool_t fattr4_named_attr; typedef fsid4 fattr4_fsid; typedef bool_t fattr4_unique_handles; typedef uint32_t fattr4_lease_time; typedef nfsstat4 fattr4_rdattr_error; typedef struct { u_int fattr4_acl_len; nfsace4 *fattr4_acl_val; } fattr4_acl; typedef uint32_t fattr4_aclsupport; typedef bool_t fattr4_archive; typedef bool_t fattr4_cansettime; typedef bool_t fattr4_case_insensitive; typedef bool_t fattr4_case_preserving; typedef bool_t fattr4_chown_restricted; typedef uint64_t fattr4_fileid; typedef uint64_t fattr4_files_avail; typedef nfs_fh4 fattr4_filehandle; typedef uint64_t fattr4_files_free; typedef uint64_t fattr4_files_total; typedef fs_locations4 fattr4_fs_locations; typedef bool_t fattr4_hidden; typedef bool_t fattr4_homogeneous; typedef uint64_t fattr4_maxfilesize; typedef uint32_t fattr4_maxlink; typedef uint32_t fattr4_maxname; typedef uint64_t fattr4_maxread; typedef uint64_t fattr4_maxwrite; typedef utf8str_cs fattr4_mimetype; typedef mode4 fattr4_mode; typedef uint64_t fattr4_mounted_on_fileid; typedef bool_t fattr4_no_trunc; typedef uint32_t fattr4_numlinks; typedef utf8str_mixed fattr4_owner; typedef utf8str_mixed fattr4_owner_group; typedef uint64_t fattr4_quota_avail_hard; typedef uint64_t fattr4_quota_avail_soft; typedef uint64_t fattr4_quota_used; typedef specdata4 fattr4_rawdev; typedef uint64_t fattr4_space_avail; typedef uint64_t fattr4_space_free; typedef uint64_t fattr4_space_total; typedef uint64_t fattr4_space_used; typedef bool_t fattr4_system; typedef nfstime4 fattr4_time_access; typedef settime4 fattr4_time_access_set; typedef nfstime4 fattr4_time_backup; typedef nfstime4 fattr4_time_create; typedef nfstime4 fattr4_time_delta; typedef nfstime4 fattr4_time_metadata; typedef nfstime4 fattr4_time_modify; typedef settime4 fattr4_time_modify_set; #define FATTR4_SUPPORTED_ATTRS 0 #define FATTR4_TYPE 1 #define FATTR4_FH_EXPIRE_TYPE 2 #define FATTR4_CHANGE 3 #define FATTR4_SIZE 4 #define FATTR4_LINK_SUPPORT 5 #define FATTR4_SYMLINK_SUPPORT 6 #define FATTR4_NAMED_ATTR 7 #define FATTR4_FSID 8 #define FATTR4_UNIQUE_HANDLES 9 #define FATTR4_LEASE_TIME 10 #define FATTR4_RDATTR_ERROR 11 #define FATTR4_FILEHANDLE 19 #define FATTR4_ACL 12 #define FATTR4_ACLSUPPORT 13 #define FATTR4_ARCHIVE 14 #define FATTR4_CANSETTIME 15 #define FATTR4_CASE_INSENSITIVE 16 #define FATTR4_CASE_PRESERVING 17 #define FATTR4_CHOWN_RESTRICTED 18 #define FATTR4_FILEID 20 #define FATTR4_FILES_AVAIL 21 #define FATTR4_FILES_FREE 22 #define FATTR4_FILES_TOTAL 23 #define FATTR4_FS_LOCATIONS 24 #define FATTR4_HIDDEN 25 #define FATTR4_HOMOGENEOUS 26 #define FATTR4_MAXFILESIZE 27 #define FATTR4_MAXLINK 28 #define FATTR4_MAXNAME 29 #define FATTR4_MAXREAD 30 #define FATTR4_MAXWRITE 31 #define FATTR4_MIMETYPE 32 #define FATTR4_MODE 33 #define FATTR4_NO_TRUNC 34 #define FATTR4_NUMLINKS 35 #define FATTR4_OWNER 36 #define FATTR4_OWNER_GROUP 37 #define FATTR4_QUOTA_AVAIL_HARD 38 #define FATTR4_QUOTA_AVAIL_SOFT 39 #define FATTR4_QUOTA_USED 40 #define FATTR4_RAWDEV 41 #define FATTR4_SPACE_AVAIL 42 #define FATTR4_SPACE_FREE 43 #define FATTR4_SPACE_TOTAL 44 #define FATTR4_SPACE_USED 45 #define FATTR4_SYSTEM 46 #define FATTR4_TIME_ACCESS 47 #define FATTR4_TIME_ACCESS_SET 48 #define FATTR4_TIME_BACKUP 49 #define FATTR4_TIME_CREATE 50 #define FATTR4_TIME_DELTA 51 #define FATTR4_TIME_METADATA 52 #define FATTR4_TIME_MODIFY 53 #define FATTR4_TIME_MODIFY_SET 54 #define FATTR4_MOUNTED_ON_FILEID 55 typedef struct { u_int attrlist4_len; char *attrlist4_val; } attrlist4; struct fattr4 { bitmap4 attrmask; attrlist4 attr_vals; }; typedef struct fattr4 fattr4; struct change_info4 { bool_t atomic; changeid4 before; changeid4 after; }; typedef struct change_info4 change_info4; struct clientaddr4 { char *r_netid; char *r_addr; }; typedef struct clientaddr4 clientaddr4; struct cb_client4 { uint32_t cb_program; clientaddr4 cb_location; }; typedef struct cb_client4 cb_client4; struct stateid4 { uint32_t seqid; char other[12]; }; typedef struct stateid4 stateid4; struct nfs_client_id4 { verifier4 verifier; struct { u_int id_len; char *id_val; } id; }; typedef struct nfs_client_id4 nfs_client_id4; struct open_owner4 { clientid4 clientid; struct { u_int owner_len; char *owner_val; } owner; }; typedef struct open_owner4 open_owner4; struct lock_owner4 { clientid4 clientid; struct { u_int owner_len; char *owner_val; } owner; }; typedef struct lock_owner4 lock_owner4; enum nfs_lock_type4 { READ_LT = 1, WRITE_LT = 2, READW_LT = 3, WRITEW_LT = 4, }; typedef enum nfs_lock_type4 nfs_lock_type4; #define ACCESS4_READ 0x00000001 #define ACCESS4_LOOKUP 0x00000002 #define ACCESS4_MODIFY 0x00000004 #define ACCESS4_EXTEND 0x00000008 #define ACCESS4_DELETE 0x00000010 #define ACCESS4_EXECUTE 0x00000020 struct ACCESS4args { uint32_t access; }; typedef struct ACCESS4args ACCESS4args; struct ACCESS4resok { uint32_t supported; uint32_t access; }; typedef struct ACCESS4resok ACCESS4resok; struct ACCESS4res { nfsstat4 status; union { ACCESS4resok resok4; } ACCESS4res_u; }; typedef struct ACCESS4res ACCESS4res; struct CLOSE4args { seqid4 seqid; stateid4 open_stateid; }; typedef struct CLOSE4args CLOSE4args; struct CLOSE4res { nfsstat4 status; union { stateid4 open_stateid; } CLOSE4res_u; }; typedef struct CLOSE4res CLOSE4res; struct COMMIT4args { offset4 offset; count4 count; }; typedef struct COMMIT4args COMMIT4args; struct COMMIT4resok { verifier4 writeverf; }; typedef struct COMMIT4resok COMMIT4resok; struct COMMIT4res { nfsstat4 status; union { COMMIT4resok resok4; } COMMIT4res_u; }; typedef struct COMMIT4res COMMIT4res; struct createtype4 { nfs_ftype4 type; union { linktext4 linkdata; specdata4 devdata; } createtype4_u; }; typedef struct createtype4 createtype4; struct CREATE4args { createtype4 objtype; component4 objname; fattr4 createattrs; }; typedef struct CREATE4args CREATE4args; struct CREATE4resok { change_info4 cinfo; bitmap4 attrset; }; typedef struct CREATE4resok CREATE4resok; struct CREATE4res { nfsstat4 status; union { CREATE4resok resok4; } CREATE4res_u; }; typedef struct CREATE4res CREATE4res; struct DELEGPURGE4args { clientid4 clientid; }; typedef struct DELEGPURGE4args DELEGPURGE4args; struct DELEGPURGE4res { nfsstat4 status; }; typedef struct DELEGPURGE4res DELEGPURGE4res; struct DELEGRETURN4args { stateid4 deleg_stateid; }; typedef struct DELEGRETURN4args DELEGRETURN4args; struct DELEGRETURN4res { nfsstat4 status; }; typedef struct DELEGRETURN4res DELEGRETURN4res; struct GETATTR4args { bitmap4 attr_request; }; typedef struct GETATTR4args GETATTR4args; struct GETATTR4resok { fattr4 obj_attributes; }; typedef struct GETATTR4resok GETATTR4resok; struct GETATTR4res { nfsstat4 status; union { GETATTR4resok resok4; } GETATTR4res_u; }; typedef struct GETATTR4res GETATTR4res; struct GETFH4resok { nfs_fh4 object; }; typedef struct GETFH4resok GETFH4resok; struct GETFH4res { nfsstat4 status; union { GETFH4resok resok4; } GETFH4res_u; }; typedef struct GETFH4res GETFH4res; struct LINK4args { component4 newname; }; typedef struct LINK4args LINK4args; struct LINK4resok { change_info4 cinfo; }; typedef struct LINK4resok LINK4resok; struct LINK4res { nfsstat4 status; union { LINK4resok resok4; } LINK4res_u; }; typedef struct LINK4res LINK4res; struct open_to_lock_owner4 { seqid4 open_seqid; stateid4 open_stateid; seqid4 lock_seqid; lock_owner4 lock_owner; }; typedef struct open_to_lock_owner4 open_to_lock_owner4; struct exist_lock_owner4 { stateid4 lock_stateid; seqid4 lock_seqid; }; typedef struct exist_lock_owner4 exist_lock_owner4; struct locker4 { bool_t new_lock_owner; union { open_to_lock_owner4 open_owner; exist_lock_owner4 lock_owner; } locker4_u; }; typedef struct locker4 locker4; struct LOCK4args { nfs_lock_type4 locktype; bool_t reclaim; offset4 offset; length4 length; locker4 locker; }; typedef struct LOCK4args LOCK4args; struct LOCK4denied { offset4 offset; length4 length; nfs_lock_type4 locktype; lock_owner4 owner; }; typedef struct LOCK4denied LOCK4denied; struct LOCK4resok { stateid4 lock_stateid; }; typedef struct LOCK4resok LOCK4resok; struct LOCK4res { nfsstat4 status; union { LOCK4resok resok4; LOCK4denied denied; } LOCK4res_u; }; typedef struct LOCK4res LOCK4res; struct LOCKT4args { nfs_lock_type4 locktype; offset4 offset; length4 length; lock_owner4 owner; }; typedef struct LOCKT4args LOCKT4args; struct LOCKT4res { nfsstat4 status; union { LOCK4denied denied; } LOCKT4res_u; }; typedef struct LOCKT4res LOCKT4res; struct LOCKU4args { nfs_lock_type4 locktype; seqid4 seqid; stateid4 lock_stateid; offset4 offset; length4 length; }; typedef struct LOCKU4args LOCKU4args; struct LOCKU4res { nfsstat4 status; union { stateid4 lock_stateid; } LOCKU4res_u; }; typedef struct LOCKU4res LOCKU4res; struct LOOKUP4args { component4 objname; }; typedef struct LOOKUP4args LOOKUP4args; struct LOOKUP4res { nfsstat4 status; }; typedef struct LOOKUP4res LOOKUP4res; struct LOOKUPP4res { nfsstat4 status; }; typedef struct LOOKUPP4res LOOKUPP4res; struct NVERIFY4args { fattr4 obj_attributes; }; typedef struct NVERIFY4args NVERIFY4args; struct NVERIFY4res { nfsstat4 status; }; typedef struct NVERIFY4res NVERIFY4res; enum createmode4 { UNCHECKED4 = 0, GUARDED4 = 1, EXCLUSIVE4 = 2, }; typedef enum createmode4 createmode4; struct createhow4 { createmode4 mode; union { fattr4 createattrs; verifier4 createverf; } createhow4_u; }; typedef struct createhow4 createhow4; enum opentype4 { OPEN4_NOCREATE = 0, OPEN4_CREATE = 1, }; typedef enum opentype4 opentype4; struct openflag4 { opentype4 opentype; union { createhow4 how; } openflag4_u; }; typedef struct openflag4 openflag4; enum limit_by4 { NFS_LIMIT_SIZE = 1, NFS_LIMIT_BLOCKS = 2, }; typedef enum limit_by4 limit_by4; struct nfs_modified_limit4 { uint32_t num_blocks; uint32_t bytes_per_block; }; typedef struct nfs_modified_limit4 nfs_modified_limit4; struct nfs_space_limit4 { limit_by4 limitby; union { uint64_t filesize; nfs_modified_limit4 mod_blocks; } nfs_space_limit4_u; }; typedef struct nfs_space_limit4 nfs_space_limit4; #define OPEN4_SHARE_ACCESS_READ 0x00000001 #define OPEN4_SHARE_ACCESS_WRITE 0x00000002 #define OPEN4_SHARE_ACCESS_BOTH 0x00000003 #define OPEN4_SHARE_DENY_NONE 0x00000000 #define OPEN4_SHARE_DENY_READ 0x00000001 #define OPEN4_SHARE_DENY_WRITE 0x00000002 #define OPEN4_SHARE_DENY_BOTH 0x00000003 enum open_delegation_type4 { OPEN_DELEGATE_NONE = 0, OPEN_DELEGATE_READ = 1, OPEN_DELEGATE_WRITE = 2, }; typedef enum open_delegation_type4 open_delegation_type4; enum open_claim_type4 { CLAIM_NULL = 0, CLAIM_PREVIOUS = 1, CLAIM_DELEGATE_CUR = 2, CLAIM_DELEGATE_PREV = 3, }; typedef enum open_claim_type4 open_claim_type4; struct open_claim_delegate_cur4 { stateid4 delegate_stateid; component4 file; }; typedef struct open_claim_delegate_cur4 open_claim_delegate_cur4; struct open_claim4 { open_claim_type4 claim; union { component4 file; open_delegation_type4 delegate_type; open_claim_delegate_cur4 delegate_cur_info; component4 file_delegate_prev; } open_claim4_u; }; typedef struct open_claim4 open_claim4; struct OPEN4args { seqid4 seqid; uint32_t share_access; uint32_t share_deny; open_owner4 owner; openflag4 openhow; open_claim4 claim; }; typedef struct OPEN4args OPEN4args; struct open_read_delegation4 { stateid4 stateid; bool_t recall; nfsace4 permissions; }; typedef struct open_read_delegation4 open_read_delegation4; struct open_write_delegation4 { stateid4 stateid; bool_t recall; nfs_space_limit4 space_limit; nfsace4 permissions; }; typedef struct open_write_delegation4 open_write_delegation4; struct open_delegation4 { open_delegation_type4 delegation_type; union { open_read_delegation4 read; open_write_delegation4 write; } open_delegation4_u; }; typedef struct open_delegation4 open_delegation4; #define OPEN4_RESULT_CONFIRM 0x00000002 #define OPEN4_RESULT_LOCKTYPE_POSIX 0x00000004 struct OPEN4resok { stateid4 stateid; change_info4 cinfo; uint32_t rflags; bitmap4 attrset; open_delegation4 delegation; }; typedef struct OPEN4resok OPEN4resok; struct OPEN4res { nfsstat4 status; union { OPEN4resok resok4; } OPEN4res_u; }; typedef struct OPEN4res OPEN4res; struct OPENATTR4args { bool_t createdir; }; typedef struct OPENATTR4args OPENATTR4args; struct OPENATTR4res { nfsstat4 status; }; typedef struct OPENATTR4res OPENATTR4res; struct OPEN_CONFIRM4args { stateid4 open_stateid; seqid4 seqid; }; typedef struct OPEN_CONFIRM4args OPEN_CONFIRM4args; struct OPEN_CONFIRM4resok { stateid4 open_stateid; }; typedef struct OPEN_CONFIRM4resok OPEN_CONFIRM4resok; struct OPEN_CONFIRM4res { nfsstat4 status; union { OPEN_CONFIRM4resok resok4; } OPEN_CONFIRM4res_u; }; typedef struct OPEN_CONFIRM4res OPEN_CONFIRM4res; struct OPEN_DOWNGRADE4args { stateid4 open_stateid; seqid4 seqid; uint32_t share_access; uint32_t share_deny; }; typedef struct OPEN_DOWNGRADE4args OPEN_DOWNGRADE4args; struct OPEN_DOWNGRADE4resok { stateid4 open_stateid; }; typedef struct OPEN_DOWNGRADE4resok OPEN_DOWNGRADE4resok; struct OPEN_DOWNGRADE4res { nfsstat4 status; union { OPEN_DOWNGRADE4resok resok4; } OPEN_DOWNGRADE4res_u; }; typedef struct OPEN_DOWNGRADE4res OPEN_DOWNGRADE4res; struct PUTFH4args { nfs_fh4 object; }; typedef struct PUTFH4args PUTFH4args; struct PUTFH4res { nfsstat4 status; }; typedef struct PUTFH4res PUTFH4res; struct PUTPUBFH4res { nfsstat4 status; }; typedef struct PUTPUBFH4res PUTPUBFH4res; struct PUTROOTFH4res { nfsstat4 status; }; typedef struct PUTROOTFH4res PUTROOTFH4res; struct READ4args { stateid4 stateid; offset4 offset; count4 count; }; typedef struct READ4args READ4args; struct READ4resok { bool_t eof; struct { u_int data_len; char *data_val; } data; }; typedef struct READ4resok READ4resok; struct READ4res { nfsstat4 status; union { READ4resok resok4; } READ4res_u; }; typedef struct READ4res READ4res; struct READDIR4args { nfs_cookie4 cookie; verifier4 cookieverf; count4 dircount; count4 maxcount; bitmap4 attr_request; }; typedef struct READDIR4args READDIR4args; struct entry4 { nfs_cookie4 cookie; component4 name; fattr4 attrs; struct entry4 *nextentry; }; typedef struct entry4 entry4; struct dirlist4 { entry4 *entries; bool_t eof; }; typedef struct dirlist4 dirlist4; struct READDIR4resok { verifier4 cookieverf; dirlist4 reply; }; typedef struct READDIR4resok READDIR4resok; struct READDIR4res { nfsstat4 status; union { READDIR4resok resok4; } READDIR4res_u; }; typedef struct READDIR4res READDIR4res; struct READLINK4resok { linktext4 link; }; typedef struct READLINK4resok READLINK4resok; struct READLINK4res { nfsstat4 status; union { READLINK4resok resok4; } READLINK4res_u; }; typedef struct READLINK4res READLINK4res; struct REMOVE4args { component4 target; }; typedef struct REMOVE4args REMOVE4args; struct REMOVE4resok { change_info4 cinfo; }; typedef struct REMOVE4resok REMOVE4resok; struct REMOVE4res { nfsstat4 status; union { REMOVE4resok resok4; } REMOVE4res_u; }; typedef struct REMOVE4res REMOVE4res; struct RENAME4args { component4 oldname; component4 newname; }; typedef struct RENAME4args RENAME4args; struct RENAME4resok { change_info4 source_cinfo; change_info4 target_cinfo; }; typedef struct RENAME4resok RENAME4resok; struct RENAME4res { nfsstat4 status; union { RENAME4resok resok4; } RENAME4res_u; }; typedef struct RENAME4res RENAME4res; struct RENEW4args { clientid4 clientid; }; typedef struct RENEW4args RENEW4args; struct RENEW4res { nfsstat4 status; }; typedef struct RENEW4res RENEW4res; struct RESTOREFH4res { nfsstat4 status; }; typedef struct RESTOREFH4res RESTOREFH4res; struct SAVEFH4res { nfsstat4 status; }; typedef struct SAVEFH4res SAVEFH4res; struct SECINFO4args { component4 name; }; typedef struct SECINFO4args SECINFO4args; enum rpc_gss_svc_t { RPC_GSS_SVC_NONE = 1, RPC_GSS_SVC_INTEGRITY = 2, RPC_GSS_SVC_PRIVACY = 3, }; typedef enum rpc_gss_svc_t rpc_gss_svc_t; struct rpcsec_gss_info { sec_oid4 oid; qop4 qop; rpc_gss_svc_t service; }; typedef struct rpcsec_gss_info rpcsec_gss_info; struct secinfo4 { uint32_t flavor; union { rpcsec_gss_info flavor_info; } secinfo4_u; }; typedef struct secinfo4 secinfo4; typedef struct { u_int SECINFO4resok_len; secinfo4 *SECINFO4resok_val; } SECINFO4resok; struct SECINFO4res { nfsstat4 status; union { SECINFO4resok resok4; } SECINFO4res_u; }; typedef struct SECINFO4res SECINFO4res; struct SETATTR4args { stateid4 stateid; fattr4 obj_attributes; }; typedef struct SETATTR4args SETATTR4args; struct SETATTR4res { nfsstat4 status; bitmap4 attrsset; }; typedef struct SETATTR4res SETATTR4res; struct SETCLIENTID4args { nfs_client_id4 client; cb_client4 callback; uint32_t callback_ident; }; typedef struct SETCLIENTID4args SETCLIENTID4args; struct SETCLIENTID4resok { clientid4 clientid; verifier4 setclientid_confirm; }; typedef struct SETCLIENTID4resok SETCLIENTID4resok; struct SETCLIENTID4res { nfsstat4 status; union { SETCLIENTID4resok resok4; clientaddr4 client_using; } SETCLIENTID4res_u; }; typedef struct SETCLIENTID4res SETCLIENTID4res; struct SETCLIENTID_CONFIRM4args { clientid4 clientid; verifier4 setclientid_confirm; }; typedef struct SETCLIENTID_CONFIRM4args SETCLIENTID_CONFIRM4args; struct SETCLIENTID_CONFIRM4res { nfsstat4 status; }; typedef struct SETCLIENTID_CONFIRM4res SETCLIENTID_CONFIRM4res; struct VERIFY4args { fattr4 obj_attributes; }; typedef struct VERIFY4args VERIFY4args; struct VERIFY4res { nfsstat4 status; }; typedef struct VERIFY4res VERIFY4res; enum stable_how4 { UNSTABLE4 = 0, DATA_SYNC4 = 1, FILE_SYNC4 = 2, }; typedef enum stable_how4 stable_how4; struct WRITE4args { stateid4 stateid; offset4 offset; stable_how4 stable; struct { u_int data_len; char *data_val; } data; }; typedef struct WRITE4args WRITE4args; struct WRITE4resok { count4 count; stable_how4 committed; verifier4 writeverf; }; typedef struct WRITE4resok WRITE4resok; struct WRITE4res { nfsstat4 status; union { WRITE4resok resok4; } WRITE4res_u; }; typedef struct WRITE4res WRITE4res; struct RELEASE_LOCKOWNER4args { lock_owner4 lock_owner; }; typedef struct RELEASE_LOCKOWNER4args RELEASE_LOCKOWNER4args; struct RELEASE_LOCKOWNER4res { nfsstat4 status; }; typedef struct RELEASE_LOCKOWNER4res RELEASE_LOCKOWNER4res; struct ILLEGAL4res { nfsstat4 status; }; typedef struct ILLEGAL4res ILLEGAL4res; enum nfs_opnum4 { OP_ACCESS = 3, OP_CLOSE = 4, OP_COMMIT = 5, OP_CREATE = 6, OP_DELEGPURGE = 7, OP_DELEGRETURN = 8, OP_GETATTR = 9, OP_GETFH = 10, OP_LINK = 11, OP_LOCK = 12, OP_LOCKT = 13, OP_LOCKU = 14, OP_LOOKUP = 15, OP_LOOKUPP = 16, OP_NVERIFY = 17, OP_OPEN = 18, OP_OPENATTR = 19, OP_OPEN_CONFIRM = 20, OP_OPEN_DOWNGRADE = 21, OP_PUTFH = 22, OP_PUTPUBFH = 23, OP_PUTROOTFH = 24, OP_READ = 25, OP_READDIR = 26, OP_READLINK = 27, OP_REMOVE = 28, OP_RENAME = 29, OP_RENEW = 30, OP_RESTOREFH = 31, OP_SAVEFH = 32, OP_SECINFO = 33, OP_SETATTR = 34, OP_SETCLIENTID = 35, OP_SETCLIENTID_CONFIRM = 36, OP_VERIFY = 37, OP_WRITE = 38, OP_RELEASE_LOCKOWNER = 39, OP_ILLEGAL = 10044, }; typedef enum nfs_opnum4 nfs_opnum4; struct nfs_argop4 { nfs_opnum4 argop; union { ACCESS4args opaccess; CLOSE4args opclose; COMMIT4args opcommit; CREATE4args opcreate; DELEGPURGE4args opdelegpurge; DELEGRETURN4args opdelegreturn; GETATTR4args opgetattr; LINK4args oplink; LOCK4args oplock; LOCKT4args oplockt; LOCKU4args oplocku; LOOKUP4args oplookup; NVERIFY4args opnverify; OPEN4args opopen; OPENATTR4args opopenattr; OPEN_CONFIRM4args opopen_confirm; OPEN_DOWNGRADE4args opopen_downgrade; PUTFH4args opputfh; READ4args opread; READDIR4args opreaddir; REMOVE4args opremove; RENAME4args oprename; RENEW4args oprenew; SECINFO4args opsecinfo; SETATTR4args opsetattr; SETCLIENTID4args opsetclientid; SETCLIENTID_CONFIRM4args opsetclientid_confirm; VERIFY4args opverify; WRITE4args opwrite; RELEASE_LOCKOWNER4args oprelease_lockowner; } nfs_argop4_u; }; typedef struct nfs_argop4 nfs_argop4; struct nfs_resop4 { nfs_opnum4 resop; union { ACCESS4res opaccess; CLOSE4res opclose; COMMIT4res opcommit; CREATE4res opcreate; DELEGPURGE4res opdelegpurge; DELEGRETURN4res opdelegreturn; GETATTR4res opgetattr; GETFH4res opgetfh; LINK4res oplink; LOCK4res oplock; LOCKT4res oplockt; LOCKU4res oplocku; LOOKUP4res oplookup; LOOKUPP4res oplookupp; NVERIFY4res opnverify; OPEN4res opopen; OPENATTR4res opopenattr; OPEN_CONFIRM4res opopen_confirm; OPEN_DOWNGRADE4res opopen_downgrade; PUTFH4res opputfh; PUTPUBFH4res opputpubfh; PUTROOTFH4res opputrootfh; READ4res opread; READDIR4res opreaddir; READLINK4res opreadlink; REMOVE4res opremove; RENAME4res oprename; RENEW4res oprenew; RESTOREFH4res oprestorefh; SAVEFH4res opsavefh; SECINFO4res opsecinfo; SETATTR4res opsetattr; SETCLIENTID4res opsetclientid; SETCLIENTID_CONFIRM4res opsetclientid_confirm; VERIFY4res opverify; WRITE4res opwrite; RELEASE_LOCKOWNER4res oprelease_lockowner; ILLEGAL4res opillegal; } nfs_resop4_u; }; typedef struct nfs_resop4 nfs_resop4; struct COMPOUND4args { utf8str_cs tag; uint32_t minorversion; struct { u_int argarray_len; nfs_argop4 *argarray_val; } argarray; }; typedef struct COMPOUND4args COMPOUND4args; struct COMPOUND4res { nfsstat4 status; utf8str_cs tag; struct { u_int resarray_len; nfs_resop4 *resarray_val; } resarray; }; typedef struct COMPOUND4res COMPOUND4res; struct CB_GETATTR4args { nfs_fh4 fh; bitmap4 attr_request; }; typedef struct CB_GETATTR4args CB_GETATTR4args; struct CB_GETATTR4resok { fattr4 obj_attributes; }; typedef struct CB_GETATTR4resok CB_GETATTR4resok; struct CB_GETATTR4res { nfsstat4 status; union { CB_GETATTR4resok resok4; } CB_GETATTR4res_u; }; typedef struct CB_GETATTR4res CB_GETATTR4res; struct CB_RECALL4args { stateid4 stateid; bool_t truncate; nfs_fh4 fh; }; typedef struct CB_RECALL4args CB_RECALL4args; struct CB_RECALL4res { nfsstat4 status; }; typedef struct CB_RECALL4res CB_RECALL4res; struct CB_ILLEGAL4res { nfsstat4 status; }; typedef struct CB_ILLEGAL4res CB_ILLEGAL4res; enum nfs_cb_opnum4 { NFS4_OP_CB_GETATTR = 3, NFS4_OP_CB_RECALL = 4, NFS4_OP_CB_ILLEGAL = 10044, }; typedef enum nfs_cb_opnum4 nfs_cb_opnum4; struct nfs_cb_argop4 { u_int argop; union { CB_GETATTR4args opcbgetattr; CB_RECALL4args opcbrecall; } nfs_cb_argop4_u; }; typedef struct nfs_cb_argop4 nfs_cb_argop4; struct nfs_cb_resop4 { u_int resop; union { CB_GETATTR4res opcbgetattr; CB_RECALL4res opcbrecall; CB_ILLEGAL4res opcbillegal; } nfs_cb_resop4_u; }; typedef struct nfs_cb_resop4 nfs_cb_resop4; struct CB_COMPOUND4args { utf8str_cs tag; uint32_t minorversion; uint32_t callback_ident; struct { u_int argarray_len; nfs_cb_argop4 *argarray_val; } argarray; }; typedef struct CB_COMPOUND4args CB_COMPOUND4args; struct CB_COMPOUND4res { nfsstat4 status; utf8str_cs tag; struct { u_int resarray_len; nfs_cb_resop4 *resarray_val; } resarray; }; typedef struct CB_COMPOUND4res CB_COMPOUND4res; #define NFS4_PROGRAM 100003 #define NFS_V4 4 #if defined(__STDC__) || defined(__cplusplus) #define NFSPROC4_NULL 0 extern void * nfsproc4_null_4(void *, CLIENT *); extern void * nfsproc4_null_4_svc(void *, struct svc_req *); #define NFSPROC4_COMPOUND 1 extern COMPOUND4res * nfsproc4_compound_4(COMPOUND4args *, CLIENT *); extern COMPOUND4res * nfsproc4_compound_4_svc(COMPOUND4args *, struct svc_req *); extern int nfs4_program_4_freeresult (SVCXPRT *, xdrproc_t, caddr_t); #else /* K&R C */ #define NFSPROC4_NULL 0 extern void * nfsproc4_null_4(); extern void * nfsproc4_null_4_svc(); #define NFSPROC4_COMPOUND 1 extern COMPOUND4res * nfsproc4_compound_4(); extern COMPOUND4res * nfsproc4_compound_4_svc(); extern int nfs4_program_4_freeresult (); #endif /* K&R C */ #define NFS4_CALLBACK 0x40000000 #define NFS_CB 1 #if defined(__STDC__) || defined(__cplusplus) #define CB_NULL 0 extern void * cb_null_1(void *, CLIENT *); extern void * cb_null_1_svc(void *, struct svc_req *); #define CB_COMPOUND 1 extern CB_COMPOUND4res * cb_compound_1(CB_COMPOUND4args *, CLIENT *); extern CB_COMPOUND4res * cb_compound_1_svc(CB_COMPOUND4args *, struct svc_req *); extern int nfs4_callback_1_freeresult (SVCXPRT *, xdrproc_t, caddr_t); #else /* K&R C */ #define CB_NULL 0 extern void * cb_null_1(); extern void * cb_null_1_svc(); #define CB_COMPOUND 1 extern CB_COMPOUND4res * cb_compound_1(); extern CB_COMPOUND4res * cb_compound_1_svc(); extern int nfs4_callback_1_freeresult (); #endif /* K&R C */ /* the xdr functions */ #if defined(__STDC__) || defined(__cplusplus) extern bool_t xdr_nfs_ftype4 (XDR *, nfs_ftype4*); extern bool_t xdr_nfsstat4 (XDR *, nfsstat4*); extern bool_t xdr_bitmap4 (XDR *, bitmap4*); extern bool_t xdr_offset4 (XDR *, offset4*); extern bool_t xdr_count4 (XDR *, count4*); extern bool_t xdr_length4 (XDR *, length4*); extern bool_t xdr_clientid4 (XDR *, clientid4*); extern bool_t xdr_seqid4 (XDR *, seqid4*); extern bool_t xdr_utf8string (XDR *, utf8string*); extern bool_t xdr_utf8str_cis (XDR *, utf8str_cis*); extern bool_t xdr_utf8str_cs (XDR *, utf8str_cs*); extern bool_t xdr_utf8str_mixed (XDR *, utf8str_mixed*); extern bool_t xdr_component4 (XDR *, component4*); extern bool_t xdr_pathname4 (XDR *, pathname4*); extern bool_t xdr_nfs_lockid4 (XDR *, nfs_lockid4*); extern bool_t xdr_nfs_cookie4 (XDR *, nfs_cookie4*); extern bool_t xdr_linktext4 (XDR *, linktext4*); extern bool_t xdr_sec_oid4 (XDR *, sec_oid4*); extern bool_t xdr_qop4 (XDR *, qop4*); extern bool_t xdr_mode4 (XDR *, mode4*); extern bool_t xdr_changeid4 (XDR *, changeid4*); extern bool_t xdr_verifier4 (XDR *, verifier4); extern bool_t xdr_nfstime4 (XDR *, nfstime4*); extern bool_t xdr_time_how4 (XDR *, time_how4*); extern bool_t xdr_settime4 (XDR *, settime4*); extern bool_t xdr_nfs_fh4 (XDR *, nfs_fh4*); extern bool_t xdr_fsid4 (XDR *, fsid4*); extern bool_t xdr_fs_location4 (XDR *, fs_location4*); extern bool_t xdr_fs_locations4 (XDR *, fs_locations4*); extern bool_t xdr_acetype4 (XDR *, acetype4*); extern bool_t xdr_aceflag4 (XDR *, aceflag4*); extern bool_t xdr_acemask4 (XDR *, acemask4*); extern bool_t xdr_nfsace4 (XDR *, nfsace4*); extern bool_t xdr_specdata4 (XDR *, specdata4*); extern bool_t xdr_fattr4_supported_attrs (XDR *, fattr4_supported_attrs*); extern bool_t xdr_fattr4_type (XDR *, fattr4_type*); extern bool_t xdr_fattr4_fh_expire_type (XDR *, fattr4_fh_expire_type*); extern bool_t xdr_fattr4_change (XDR *, fattr4_change*); extern bool_t xdr_fattr4_size (XDR *, fattr4_size*); extern bool_t xdr_fattr4_link_support (XDR *, fattr4_link_support*); extern bool_t xdr_fattr4_symlink_support (XDR *, fattr4_symlink_support*); extern bool_t xdr_fattr4_named_attr (XDR *, fattr4_named_attr*); extern bool_t xdr_fattr4_fsid (XDR *, fattr4_fsid*); extern bool_t xdr_fattr4_unique_handles (XDR *, fattr4_unique_handles*); extern bool_t xdr_fattr4_lease_time (XDR *, fattr4_lease_time*); extern bool_t xdr_fattr4_rdattr_error (XDR *, fattr4_rdattr_error*); extern bool_t xdr_fattr4_acl (XDR *, fattr4_acl*); extern bool_t xdr_fattr4_aclsupport (XDR *, fattr4_aclsupport*); extern bool_t xdr_fattr4_archive (XDR *, fattr4_archive*); extern bool_t xdr_fattr4_cansettime (XDR *, fattr4_cansettime*); extern bool_t xdr_fattr4_case_insensitive (XDR *, fattr4_case_insensitive*); extern bool_t xdr_fattr4_case_preserving (XDR *, fattr4_case_preserving*); extern bool_t xdr_fattr4_chown_restricted (XDR *, fattr4_chown_restricted*); extern bool_t xdr_fattr4_fileid (XDR *, fattr4_fileid*); extern bool_t xdr_fattr4_files_avail (XDR *, fattr4_files_avail*); extern bool_t xdr_fattr4_filehandle (XDR *, fattr4_filehandle*); extern bool_t xdr_fattr4_files_free (XDR *, fattr4_files_free*); extern bool_t xdr_fattr4_files_total (XDR *, fattr4_files_total*); extern bool_t xdr_fattr4_fs_locations (XDR *, fattr4_fs_locations*); extern bool_t xdr_fattr4_hidden (XDR *, fattr4_hidden*); extern bool_t xdr_fattr4_homogeneous (XDR *, fattr4_homogeneous*); extern bool_t xdr_fattr4_maxfilesize (XDR *, fattr4_maxfilesize*); extern bool_t xdr_fattr4_maxlink (XDR *, fattr4_maxlink*); extern bool_t xdr_fattr4_maxname (XDR *, fattr4_maxname*); extern bool_t xdr_fattr4_maxread (XDR *, fattr4_maxread*); extern bool_t xdr_fattr4_maxwrite (XDR *, fattr4_maxwrite*); extern bool_t xdr_fattr4_mimetype (XDR *, fattr4_mimetype*); extern bool_t xdr_fattr4_mode (XDR *, fattr4_mode*); extern bool_t xdr_fattr4_mounted_on_fileid (XDR *, fattr4_mounted_on_fileid*); extern bool_t xdr_fattr4_no_trunc (XDR *, fattr4_no_trunc*); extern bool_t xdr_fattr4_numlinks (XDR *, fattr4_numlinks*); extern bool_t xdr_fattr4_owner (XDR *, fattr4_owner*); extern bool_t xdr_fattr4_owner_group (XDR *, fattr4_owner_group*); extern bool_t xdr_fattr4_quota_avail_hard (XDR *, fattr4_quota_avail_hard*); extern bool_t xdr_fattr4_quota_avail_soft (XDR *, fattr4_quota_avail_soft*); extern bool_t xdr_fattr4_quota_used (XDR *, fattr4_quota_used*); extern bool_t xdr_fattr4_rawdev (XDR *, fattr4_rawdev*); extern bool_t xdr_fattr4_space_avail (XDR *, fattr4_space_avail*); extern bool_t xdr_fattr4_space_free (XDR *, fattr4_space_free*); extern bool_t xdr_fattr4_space_total (XDR *, fattr4_space_total*); extern bool_t xdr_fattr4_space_used (XDR *, fattr4_space_used*); extern bool_t xdr_fattr4_system (XDR *, fattr4_system*); extern bool_t xdr_fattr4_time_access (XDR *, fattr4_time_access*); extern bool_t xdr_fattr4_time_access_set (XDR *, fattr4_time_access_set*); extern bool_t xdr_fattr4_time_backup (XDR *, fattr4_time_backup*); extern bool_t xdr_fattr4_time_create (XDR *, fattr4_time_create*); extern bool_t xdr_fattr4_time_delta (XDR *, fattr4_time_delta*); extern bool_t xdr_fattr4_time_metadata (XDR *, fattr4_time_metadata*); extern bool_t xdr_fattr4_time_modify (XDR *, fattr4_time_modify*); extern bool_t xdr_fattr4_time_modify_set (XDR *, fattr4_time_modify_set*); extern bool_t xdr_attrlist4 (XDR *, attrlist4*); extern bool_t xdr_fattr4 (XDR *, fattr4*); extern bool_t xdr_change_info4 (XDR *, change_info4*); extern bool_t xdr_clientaddr4 (XDR *, clientaddr4*); extern bool_t xdr_cb_client4 (XDR *, cb_client4*); extern bool_t xdr_stateid4 (XDR *, stateid4*); extern bool_t xdr_nfs_client_id4 (XDR *, nfs_client_id4*); extern bool_t xdr_open_owner4 (XDR *, open_owner4*); extern bool_t xdr_lock_owner4 (XDR *, lock_owner4*); extern bool_t xdr_nfs_lock_type4 (XDR *, nfs_lock_type4*); extern bool_t xdr_ACCESS4args (XDR *, ACCESS4args*); extern bool_t xdr_ACCESS4resok (XDR *, ACCESS4resok*); extern bool_t xdr_ACCESS4res (XDR *, ACCESS4res*); extern bool_t xdr_CLOSE4args (XDR *, CLOSE4args*); extern bool_t xdr_CLOSE4res (XDR *, CLOSE4res*); extern bool_t xdr_COMMIT4args (XDR *, COMMIT4args*); extern bool_t xdr_COMMIT4resok (XDR *, COMMIT4resok*); extern bool_t xdr_COMMIT4res (XDR *, COMMIT4res*); extern bool_t xdr_createtype4 (XDR *, createtype4*); extern bool_t xdr_CREATE4args (XDR *, CREATE4args*); extern bool_t xdr_CREATE4resok (XDR *, CREATE4resok*); extern bool_t xdr_CREATE4res (XDR *, CREATE4res*); extern bool_t xdr_DELEGPURGE4args (XDR *, DELEGPURGE4args*); extern bool_t xdr_DELEGPURGE4res (XDR *, DELEGPURGE4res*); extern bool_t xdr_DELEGRETURN4args (XDR *, DELEGRETURN4args*); extern bool_t xdr_DELEGRETURN4res (XDR *, DELEGRETURN4res*); extern bool_t xdr_GETATTR4args (XDR *, GETATTR4args*); extern bool_t xdr_GETATTR4resok (XDR *, GETATTR4resok*); extern bool_t xdr_GETATTR4res (XDR *, GETATTR4res*); extern bool_t xdr_GETFH4resok (XDR *, GETFH4resok*); extern bool_t xdr_GETFH4res (XDR *, GETFH4res*); extern bool_t xdr_LINK4args (XDR *, LINK4args*); extern bool_t xdr_LINK4resok (XDR *, LINK4resok*); extern bool_t xdr_LINK4res (XDR *, LINK4res*); extern bool_t xdr_open_to_lock_owner4 (XDR *, open_to_lock_owner4*); extern bool_t xdr_exist_lock_owner4 (XDR *, exist_lock_owner4*); extern bool_t xdr_locker4 (XDR *, locker4*); extern bool_t xdr_LOCK4args (XDR *, LOCK4args*); extern bool_t xdr_LOCK4denied (XDR *, LOCK4denied*); extern bool_t xdr_LOCK4resok (XDR *, LOCK4resok*); extern bool_t xdr_LOCK4res (XDR *, LOCK4res*); extern bool_t xdr_LOCKT4args (XDR *, LOCKT4args*); extern bool_t xdr_LOCKT4res (XDR *, LOCKT4res*); extern bool_t xdr_LOCKU4args (XDR *, LOCKU4args*); extern bool_t xdr_LOCKU4res (XDR *, LOCKU4res*); extern bool_t xdr_LOOKUP4args (XDR *, LOOKUP4args*); extern bool_t xdr_LOOKUP4res (XDR *, LOOKUP4res*); extern bool_t xdr_LOOKUPP4res (XDR *, LOOKUPP4res*); extern bool_t xdr_NVERIFY4args (XDR *, NVERIFY4args*); extern bool_t xdr_NVERIFY4res (XDR *, NVERIFY4res*); extern bool_t xdr_createmode4 (XDR *, createmode4*); extern bool_t xdr_createhow4 (XDR *, createhow4*); extern bool_t xdr_opentype4 (XDR *, opentype4*); extern bool_t xdr_openflag4 (XDR *, openflag4*); extern bool_t xdr_limit_by4 (XDR *, limit_by4*); extern bool_t xdr_nfs_modified_limit4 (XDR *, nfs_modified_limit4*); extern bool_t xdr_nfs_space_limit4 (XDR *, nfs_space_limit4*); extern bool_t xdr_open_delegation_type4 (XDR *, open_delegation_type4*); extern bool_t xdr_open_claim_type4 (XDR *, open_claim_type4*); extern bool_t xdr_open_claim_delegate_cur4 (XDR *, open_claim_delegate_cur4*); extern bool_t xdr_open_claim4 (XDR *, open_claim4*); extern bool_t xdr_OPEN4args (XDR *, OPEN4args*); extern bool_t xdr_open_read_delegation4 (XDR *, open_read_delegation4*); extern bool_t xdr_open_write_delegation4 (XDR *, open_write_delegation4*); extern bool_t xdr_open_delegation4 (XDR *, open_delegation4*); extern bool_t xdr_OPEN4resok (XDR *, OPEN4resok*); extern bool_t xdr_OPEN4res (XDR *, OPEN4res*); extern bool_t xdr_OPENATTR4args (XDR *, OPENATTR4args*); extern bool_t xdr_OPENATTR4res (XDR *, OPENATTR4res*); extern bool_t xdr_OPEN_CONFIRM4args (XDR *, OPEN_CONFIRM4args*); extern bool_t xdr_OPEN_CONFIRM4resok (XDR *, OPEN_CONFIRM4resok*); extern bool_t xdr_OPEN_CONFIRM4res (XDR *, OPEN_CONFIRM4res*); extern bool_t xdr_OPEN_DOWNGRADE4args (XDR *, OPEN_DOWNGRADE4args*); extern bool_t xdr_OPEN_DOWNGRADE4resok (XDR *, OPEN_DOWNGRADE4resok*); extern bool_t xdr_OPEN_DOWNGRADE4res (XDR *, OPEN_DOWNGRADE4res*); extern bool_t xdr_PUTFH4args (XDR *, PUTFH4args*); extern bool_t xdr_PUTFH4res (XDR *, PUTFH4res*); extern bool_t xdr_PUTPUBFH4res (XDR *, PUTPUBFH4res*); extern bool_t xdr_PUTROOTFH4res (XDR *, PUTROOTFH4res*); extern bool_t xdr_READ4args (XDR *, READ4args*); extern bool_t xdr_READ4resok (XDR *, READ4resok*); extern bool_t xdr_READ4res (XDR *, READ4res*); extern bool_t xdr_READDIR4args (XDR *, READDIR4args*); extern bool_t xdr_entry4 (XDR *, entry4*); extern bool_t xdr_dirlist4 (XDR *, dirlist4*); extern bool_t xdr_READDIR4resok (XDR *, READDIR4resok*); extern bool_t xdr_READDIR4res (XDR *, READDIR4res*); extern bool_t xdr_READLINK4resok (XDR *, READLINK4resok*); extern bool_t xdr_READLINK4res (XDR *, READLINK4res*); extern bool_t xdr_REMOVE4args (XDR *, REMOVE4args*); extern bool_t xdr_REMOVE4resok (XDR *, REMOVE4resok*); extern bool_t xdr_REMOVE4res (XDR *, REMOVE4res*); extern bool_t xdr_RENAME4args (XDR *, RENAME4args*); extern bool_t xdr_RENAME4resok (XDR *, RENAME4resok*); extern bool_t xdr_RENAME4res (XDR *, RENAME4res*); extern bool_t xdr_RENEW4args (XDR *, RENEW4args*); extern bool_t xdr_RENEW4res (XDR *, RENEW4res*); extern bool_t xdr_RESTOREFH4res (XDR *, RESTOREFH4res*); extern bool_t xdr_SAVEFH4res (XDR *, SAVEFH4res*); extern bool_t xdr_SECINFO4args (XDR *, SECINFO4args*); extern bool_t xdr_rpc_gss_svc_t (XDR *, rpc_gss_svc_t*); extern bool_t xdr_rpcsec_gss_info (XDR *, rpcsec_gss_info*); extern bool_t xdr_secinfo4 (XDR *, secinfo4*); extern bool_t xdr_SECINFO4resok (XDR *, SECINFO4resok*); extern bool_t xdr_SECINFO4res (XDR *, SECINFO4res*); extern bool_t xdr_SETATTR4args (XDR *, SETATTR4args*); extern bool_t xdr_SETATTR4res (XDR *, SETATTR4res*); extern bool_t xdr_SETCLIENTID4args (XDR *, SETCLIENTID4args*); extern bool_t xdr_SETCLIENTID4resok (XDR *, SETCLIENTID4resok*); extern bool_t xdr_SETCLIENTID4res (XDR *, SETCLIENTID4res*); extern bool_t xdr_SETCLIENTID_CONFIRM4args (XDR *, SETCLIENTID_CONFIRM4args*); extern bool_t xdr_SETCLIENTID_CONFIRM4res (XDR *, SETCLIENTID_CONFIRM4res*); extern bool_t xdr_VERIFY4args (XDR *, VERIFY4args*); extern bool_t xdr_VERIFY4res (XDR *, VERIFY4res*); extern bool_t xdr_stable_how4 (XDR *, stable_how4*); extern bool_t xdr_WRITE4args (XDR *, WRITE4args*); extern bool_t xdr_WRITE4resok (XDR *, WRITE4resok*); extern bool_t xdr_WRITE4res (XDR *, WRITE4res*); extern bool_t xdr_RELEASE_LOCKOWNER4args (XDR *, RELEASE_LOCKOWNER4args*); extern bool_t xdr_RELEASE_LOCKOWNER4res (XDR *, RELEASE_LOCKOWNER4res*); extern bool_t xdr_ILLEGAL4res (XDR *, ILLEGAL4res*); extern bool_t xdr_nfs_opnum4 (XDR *, nfs_opnum4*); extern bool_t xdr_nfs_argop4 (XDR *, nfs_argop4*); extern bool_t xdr_nfs_resop4 (XDR *, nfs_resop4*); extern bool_t xdr_COMPOUND4args (XDR *, COMPOUND4args*); extern bool_t xdr_COMPOUND4res (XDR *, COMPOUND4res*); extern bool_t xdr_CB_GETATTR4args (XDR *, CB_GETATTR4args*); extern bool_t xdr_CB_GETATTR4resok (XDR *, CB_GETATTR4resok*); extern bool_t xdr_CB_GETATTR4res (XDR *, CB_GETATTR4res*); extern bool_t xdr_CB_RECALL4args (XDR *, CB_RECALL4args*); extern bool_t xdr_CB_RECALL4res (XDR *, CB_RECALL4res*); extern bool_t xdr_CB_ILLEGAL4res (XDR *, CB_ILLEGAL4res*); extern bool_t xdr_nfs_cb_opnum4 (XDR *, nfs_cb_opnum4*); extern bool_t xdr_nfs_cb_argop4 (XDR *, nfs_cb_argop4*); extern bool_t xdr_nfs_cb_resop4 (XDR *, nfs_cb_resop4*); extern bool_t xdr_CB_COMPOUND4args (XDR *, CB_COMPOUND4args*); extern bool_t xdr_CB_COMPOUND4res (XDR *, CB_COMPOUND4res*); #else /* K&R C */ extern bool_t xdr_nfs_ftype4 (); extern bool_t xdr_nfsstat4 (); extern bool_t xdr_bitmap4 (); extern bool_t xdr_offset4 (); extern bool_t xdr_count4 (); extern bool_t xdr_length4 (); extern bool_t xdr_clientid4 (); extern bool_t xdr_seqid4 (); extern bool_t xdr_utf8string (); extern bool_t xdr_utf8str_cis (); extern bool_t xdr_utf8str_cs (); extern bool_t xdr_utf8str_mixed (); extern bool_t xdr_component4 (); extern bool_t xdr_pathname4 (); extern bool_t xdr_nfs_lockid4 (); extern bool_t xdr_nfs_cookie4 (); extern bool_t xdr_linktext4 (); extern bool_t xdr_sec_oid4 (); extern bool_t xdr_qop4 (); extern bool_t xdr_mode4 (); extern bool_t xdr_changeid4 (); extern bool_t xdr_verifier4 (); extern bool_t xdr_nfstime4 (); extern bool_t xdr_time_how4 (); extern bool_t xdr_settime4 (); extern bool_t xdr_nfs_fh4 (); extern bool_t xdr_fsid4 (); extern bool_t xdr_fs_location4 (); extern bool_t xdr_fs_locations4 (); extern bool_t xdr_acetype4 (); extern bool_t xdr_aceflag4 (); extern bool_t xdr_acemask4 (); extern bool_t xdr_nfsace4 (); extern bool_t xdr_specdata4 (); extern bool_t xdr_fattr4_supported_attrs (); extern bool_t xdr_fattr4_type (); extern bool_t xdr_fattr4_fh_expire_type (); extern bool_t xdr_fattr4_change (); extern bool_t xdr_fattr4_size (); extern bool_t xdr_fattr4_link_support (); extern bool_t xdr_fattr4_symlink_support (); extern bool_t xdr_fattr4_named_attr (); extern bool_t xdr_fattr4_fsid (); extern bool_t xdr_fattr4_unique_handles (); extern bool_t xdr_fattr4_lease_time (); extern bool_t xdr_fattr4_rdattr_error (); extern bool_t xdr_fattr4_acl (); extern bool_t xdr_fattr4_aclsupport (); extern bool_t xdr_fattr4_archive (); extern bool_t xdr_fattr4_cansettime (); extern bool_t xdr_fattr4_case_insensitive (); extern bool_t xdr_fattr4_case_preserving (); extern bool_t xdr_fattr4_chown_restricted (); extern bool_t xdr_fattr4_fileid (); extern bool_t xdr_fattr4_files_avail (); extern bool_t xdr_fattr4_filehandle (); extern bool_t xdr_fattr4_files_free (); extern bool_t xdr_fattr4_files_total (); extern bool_t xdr_fattr4_fs_locations (); extern bool_t xdr_fattr4_hidden (); extern bool_t xdr_fattr4_homogeneous (); extern bool_t xdr_fattr4_maxfilesize (); extern bool_t xdr_fattr4_maxlink (); extern bool_t xdr_fattr4_maxname (); extern bool_t xdr_fattr4_maxread (); extern bool_t xdr_fattr4_maxwrite (); extern bool_t xdr_fattr4_mimetype (); extern bool_t xdr_fattr4_mode (); extern bool_t xdr_fattr4_mounted_on_fileid (); extern bool_t xdr_fattr4_no_trunc (); extern bool_t xdr_fattr4_numlinks (); extern bool_t xdr_fattr4_owner (); extern bool_t xdr_fattr4_owner_group (); extern bool_t xdr_fattr4_quota_avail_hard (); extern bool_t xdr_fattr4_quota_avail_soft (); extern bool_t xdr_fattr4_quota_used (); extern bool_t xdr_fattr4_rawdev (); extern bool_t xdr_fattr4_space_avail (); extern bool_t xdr_fattr4_space_free (); extern bool_t xdr_fattr4_space_total (); extern bool_t xdr_fattr4_space_used (); extern bool_t xdr_fattr4_system (); extern bool_t xdr_fattr4_time_access (); extern bool_t xdr_fattr4_time_access_set (); extern bool_t xdr_fattr4_time_backup (); extern bool_t xdr_fattr4_time_create (); extern bool_t xdr_fattr4_time_delta (); extern bool_t xdr_fattr4_time_metadata (); extern bool_t xdr_fattr4_time_modify (); extern bool_t xdr_fattr4_time_modify_set (); extern bool_t xdr_attrlist4 (); extern bool_t xdr_fattr4 (); extern bool_t xdr_change_info4 (); extern bool_t xdr_clientaddr4 (); extern bool_t xdr_cb_client4 (); extern bool_t xdr_stateid4 (); extern bool_t xdr_nfs_client_id4 (); extern bool_t xdr_open_owner4 (); extern bool_t xdr_lock_owner4 (); extern bool_t xdr_nfs_lock_type4 (); extern bool_t xdr_ACCESS4args (); extern bool_t xdr_ACCESS4resok (); extern bool_t xdr_ACCESS4res (); extern bool_t xdr_CLOSE4args (); extern bool_t xdr_CLOSE4res (); extern bool_t xdr_COMMIT4args (); extern bool_t xdr_COMMIT4resok (); extern bool_t xdr_COMMIT4res (); extern bool_t xdr_createtype4 (); extern bool_t xdr_CREATE4args (); extern bool_t xdr_CREATE4resok (); extern bool_t xdr_CREATE4res (); extern bool_t xdr_DELEGPURGE4args (); extern bool_t xdr_DELEGPURGE4res (); extern bool_t xdr_DELEGRETURN4args (); extern bool_t xdr_DELEGRETURN4res (); extern bool_t xdr_GETATTR4args (); extern bool_t xdr_GETATTR4resok (); extern bool_t xdr_GETATTR4res (); extern bool_t xdr_GETFH4resok (); extern bool_t xdr_GETFH4res (); extern bool_t xdr_LINK4args (); extern bool_t xdr_LINK4resok (); extern bool_t xdr_LINK4res (); extern bool_t xdr_open_to_lock_owner4 (); extern bool_t xdr_exist_lock_owner4 (); extern bool_t xdr_locker4 (); extern bool_t xdr_LOCK4args (); extern bool_t xdr_LOCK4denied (); extern bool_t xdr_LOCK4resok (); extern bool_t xdr_LOCK4res (); extern bool_t xdr_LOCKT4args (); extern bool_t xdr_LOCKT4res (); extern bool_t xdr_LOCKU4args (); extern bool_t xdr_LOCKU4res (); extern bool_t xdr_LOOKUP4args (); extern bool_t xdr_LOOKUP4res (); extern bool_t xdr_LOOKUPP4res (); extern bool_t xdr_NVERIFY4args (); extern bool_t xdr_NVERIFY4res (); extern bool_t xdr_createmode4 (); extern bool_t xdr_createhow4 (); extern bool_t xdr_opentype4 (); extern bool_t xdr_openflag4 (); extern bool_t xdr_limit_by4 (); extern bool_t xdr_nfs_modified_limit4 (); extern bool_t xdr_nfs_space_limit4 (); extern bool_t xdr_open_delegation_type4 (); extern bool_t xdr_open_claim_type4 (); extern bool_t xdr_open_claim_delegate_cur4 (); extern bool_t xdr_open_claim4 (); extern bool_t xdr_OPEN4args (); extern bool_t xdr_open_read_delegation4 (); extern bool_t xdr_open_write_delegation4 (); extern bool_t xdr_open_delegation4 (); extern bool_t xdr_OPEN4resok (); extern bool_t xdr_OPEN4res (); extern bool_t xdr_OPENATTR4args (); extern bool_t xdr_OPENATTR4res (); extern bool_t xdr_OPEN_CONFIRM4args (); extern bool_t xdr_OPEN_CONFIRM4resok (); extern bool_t xdr_OPEN_CONFIRM4res (); extern bool_t xdr_OPEN_DOWNGRADE4args (); extern bool_t xdr_OPEN_DOWNGRADE4resok (); extern bool_t xdr_OPEN_DOWNGRADE4res (); extern bool_t xdr_PUTFH4args (); extern bool_t xdr_PUTFH4res (); extern bool_t xdr_PUTPUBFH4res (); extern bool_t xdr_PUTROOTFH4res (); extern bool_t xdr_READ4args (); extern bool_t xdr_READ4resok (); extern bool_t xdr_READ4res (); extern bool_t xdr_READDIR4args (); extern bool_t xdr_entry4 (); extern bool_t xdr_dirlist4 (); extern bool_t xdr_READDIR4resok (); extern bool_t xdr_READDIR4res (); extern bool_t xdr_READLINK4resok (); extern bool_t xdr_READLINK4res (); extern bool_t xdr_REMOVE4args (); extern bool_t xdr_REMOVE4resok (); extern bool_t xdr_REMOVE4res (); extern bool_t xdr_RENAME4args (); extern bool_t xdr_RENAME4resok (); extern bool_t xdr_RENAME4res (); extern bool_t xdr_RENEW4args (); extern bool_t xdr_RENEW4res (); extern bool_t xdr_RESTOREFH4res (); extern bool_t xdr_SAVEFH4res (); extern bool_t xdr_SECINFO4args (); extern bool_t xdr_rpc_gss_svc_t (); extern bool_t xdr_rpcsec_gss_info (); extern bool_t xdr_secinfo4 (); extern bool_t xdr_SECINFO4resok (); extern bool_t xdr_SECINFO4res (); extern bool_t xdr_SETATTR4args (); extern bool_t xdr_SETATTR4res (); extern bool_t xdr_SETCLIENTID4args (); extern bool_t xdr_SETCLIENTID4resok (); extern bool_t xdr_SETCLIENTID4res (); extern bool_t xdr_SETCLIENTID_CONFIRM4args (); extern bool_t xdr_SETCLIENTID_CONFIRM4res (); extern bool_t xdr_VERIFY4args (); extern bool_t xdr_VERIFY4res (); extern bool_t xdr_stable_how4 (); extern bool_t xdr_WRITE4args (); extern bool_t xdr_WRITE4resok (); extern bool_t xdr_WRITE4res (); extern bool_t xdr_RELEASE_LOCKOWNER4args (); extern bool_t xdr_RELEASE_LOCKOWNER4res (); extern bool_t xdr_ILLEGAL4res (); extern bool_t xdr_nfs_opnum4 (); extern bool_t xdr_nfs_argop4 (); extern bool_t xdr_nfs_resop4 (); extern bool_t xdr_COMPOUND4args (); extern bool_t xdr_COMPOUND4res (); extern bool_t xdr_CB_GETATTR4args (); extern bool_t xdr_CB_GETATTR4resok (); extern bool_t xdr_CB_GETATTR4res (); extern bool_t xdr_CB_RECALL4args (); extern bool_t xdr_CB_RECALL4res (); extern bool_t xdr_CB_ILLEGAL4res (); extern bool_t xdr_nfs_cb_opnum4 (); extern bool_t xdr_nfs_cb_argop4 (); extern bool_t xdr_nfs_cb_resop4 (); extern bool_t xdr_CB_COMPOUND4args (); extern bool_t xdr_CB_COMPOUND4res (); #endif /* K&R C */ #ifdef __cplusplus } #endif #endif /* !_NFS4_H_RPCGEN */ <file_sep>/* $FreeBSD: src/include/rpc/auth_kerb.h,v 1.2 2002/09/04 23:58:23 * alfred Exp $ */ /* * Copyright (c) 2009, Sun Microsystems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - Neither the name of Sun Microsystems, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* * auth_kerb.h, Protocol for Kerberos style authentication for RPC * * Copyright (C) 1986, Sun Microsystems, Inc. */ #ifndef _RPC_AUTH_KERB_H #define _RPC_AUTH_KERB_H #ifdef KERBEROS #include <kerberos/krb.h> #include <sys/socket.h> #include <sys/t_kuser.h> #include <netinet/in.h> #include <rpc/svc.h> /* * There are two kinds of "names": fullnames and nicknames */ enum authkerb_namekind { AKN_FULLNAME, AKN_NICKNAME }; /* * A fullname contains the ticket and the window */ struct authkerb_fullname { KTEXT_ST ticket; u_long window; /* associated window */ }; /* * cooked credential stored in rq_clntcred */ struct authkerb_clnt_cred { /* start of AUTH_DAT */ unsigned char k_flags; /* Flags from ticket */ char pname[ANAME_SZ]; /* Principal's name */ char pinst[INST_SZ]; /* His Instance */ char prealm[REALM_SZ]; /* His Realm */ unsigned long checksum; /* Data checksum (opt) */ C_Block session; /* Session Key */ int life; /* Life of ticket */ unsigned long time_sec; /* Time ticket issued */ unsigned long address; /* Address in ticket */ /* KTEXT_ST reply; Auth reply (opt) */ /* end of AUTH_DAT */ unsigned long expiry; /* time the ticket is expiring */ u_long nickname; /* Nickname into cache */ u_long window; /* associated window */ }; typedef struct authkerb_clnt_cred authkerb_clnt_cred; /* * A credential */ struct authkerb_cred { enum authkerb_namekind akc_namekind; struct authkerb_fullname akc_fullname; u_long akc_nickname; }; /* * A kerb authentication verifier */ struct authkerb_verf { union { struct timeval akv_ctime; /* clear time */ des_block akv_xtime; /* crypt time */ } akv_time_u; u_long akv_int_u; }; /* * des authentication verifier: client variety * * akv_timestamp is the current time. * akv_winverf is the credential window + 1. * Both are encrypted using the conversation key. */ #ifndef akv_timestamp #define akv_timestamp akv_time_u.akv_ctime #define akv_xtimestamp akv_time_u.akv_xtime #define akv_winverf akv_int_u #endif /* * des authentication verifier: server variety * * akv_timeverf is the client's timestamp + client's window * akv_nickname is the server's nickname for the client. * akv_timeverf is encrypted using the conversation key. */ #ifndef akv_timeverf #define akv_timeverf akv_time_u.akv_ctime #define akv_xtimeverf akv_time_u.akv_xtime #define akv_nickname akv_int_u #endif /* * Register the service name, instance and realm. */ extern int authkerb_ncreate(char *, char *, char *, u_int, struct netbuf *, int *, dev_t, int, AUTH **); extern bool xdr_authkerb_cred(XDR *, struct authkerb_cred *); extern bool xdr_authkerb_verf(XDR *, struct authkerb_verf *); extern int svc_kerb_reg(SVCXPRT *, char *, char *, char *); extern enum auth_stat _svcauth_kerb(struct svc_req *, struct rpc_msg *); /* for backward compatibility */ #include <rpc/tirpc_compat.h> #endif /* KERBEROS */ #endif /* !_RPC_AUTH_KERB_H */ <file_sep>/* * Copyright (c) 2009, Sun Microsystems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - Neither the name of Sun Microsystems, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <config.h> #include <sys/cdefs.h> /* * pmap_clnt.c * Client interface to pmap rpc service. * * Copyright (C) 1984, Sun Microsystems, Inc. */ #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <rpc/rpc.h> #include <rpc/pmap_prot.h> #include <rpc/pmap_clnt.h> #include <rpc/nettype.h> #include <netinet/in.h> #include <stdio.h> #include <stdlib.h> #include "rpc_com.h" bool pmap_set(u_long program, u_long version, int protocol, int port) { bool rslt; struct netbuf *na; struct netconfig *nconf; char buf[32]; if ((protocol != IPPROTO_UDP) && (protocol != IPPROTO_TCP)) return (false); nconf = __rpc_getconfip(protocol == IPPROTO_UDP ? "udp" : "tcp"); if (nconf == NULL) return (false); if (strcmp(nconf->nc_protofmly, NC_INET) == 0) { snprintf(buf, sizeof(buf), "0.0.0.0.%d.%d", (((u_int32_t) port) >> 8) & 0xff, port & 0xff); } else if (strcmp(nconf->nc_protofmly, NC_INET6) == 0) { snprintf(buf, sizeof(buf), "::.%d.%d", (((u_int32_t) port) >> 8) & 0xff, port & 0xff); } na = uaddr2taddr(nconf, buf); if (na == NULL) { freenetconfigent(nconf); return (false); } rslt = rpcb_set((rpcprog_t) program, (rpcvers_t) version, nconf, na); mem_free(na->buf, na->len); mem_free(na, sizeof *na); freenetconfigent(nconf); return (rslt); } /* * Remove the mapping between program, version and port. * Calls the pmap service remotely to do the un-mapping. */ bool pmap_unset(u_long program, u_long version) { struct netconfig *nconf; bool udp_rslt = false; bool tcp_rslt = false; nconf = __rpc_getconfip("udp"); if (nconf != NULL) { udp_rslt = rpcb_unset((rpcprog_t) program, (rpcvers_t) version, nconf); freenetconfigent(nconf); } nconf = __rpc_getconfip("tcp"); if (nconf != NULL) { tcp_rslt = rpcb_unset((rpcprog_t) program, (rpcvers_t) version, nconf); freenetconfigent(nconf); } /* * XXX: The call may still succeed even if only one of the * calls succeeded. This was the best that could be * done for backward compatibility. */ return (tcp_rslt || udp_rslt); } <file_sep>/* * Copyright (c) 2009, Sun Microsystems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - Neither the name of Sun Microsystems, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* * Copyright (c) 1986-1991 by Sun Microsystems Inc. * In addition, portions of such source code were derived from Berkeley * 4.3 BSD under license from the Regents of the University of * California. */ #ifdef PORTMAP /* * rpc_soc.c * * The backward compatibility routines for the earlier implementation * of RPC, where the only transports supported were tcp/ip and udp/ip. * Based on berkeley socket abstraction, now implemented on the top * of TLI/Streams */ #include <config.h> #include <pthread.h> #include <reentrant.h> #include <sys/types.h> #include <sys/socket.h> #include <stdio.h> #include <rpc/rpc.h> #include <rpc/pmap_clnt.h> #include <rpc/pmap_prot.h> #include <rpc/nettype.h> #include <syslog.h> #include <netinet/in.h> #include <netdb.h> #include <errno.h> #include <syslog.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include "rpc_com.h" extern mutex_t rpcsoc_lock; static CLIENT *clnt_com_ncreate(struct sockaddr_in *, rpcprog_t, rpcvers_t, int *, u_int, u_int, char *, int); static SVCXPRT *svc_com_ncreate(int, u_int, u_int, char *); static bool rpc_wrap_bcast(char *, struct netbuf *, struct netconfig *); /* XXX */ #define IN4_LOCALHOST_STRING "127.0.0.1" #define IN6_LOCALHOST_STRING "::1" /* XXX */ #ifndef SOCK_CLOEXEC #define SOCK_CLOEXEC 02000000 #endif /* * A common clnt create routine */ static CLIENT * clnt_com_ncreate(struct sockaddr_in *raddr, rpcprog_t prog, rpcvers_t vers, int *sockp, u_int sendsz, u_int recvsz, char *tp, int flags) { CLIENT *cl; int madefd = FALSE; int fd = *sockp; struct netconfig *nconf; struct netbuf bindaddr; mutex_lock(&rpcsoc_lock); nconf = __rpc_getconfip(tp); if (!nconf) { rpc_createerr.cf_stat = RPC_UNKNOWNPROTO; mutex_unlock(&rpcsoc_lock); return (NULL); } if (fd == RPC_ANYSOCK) { static int have_cloexec; fd = __rpc_nconf2fd_flags(nconf, flags); if (fd == -1) { if ((flags & SOCK_CLOEXEC) && have_cloexec <= 0) { fd = __rpc_nconf2fd(nconf); if (fd == -1) goto syserror; if (flags & SOCK_CLOEXEC) { have_cloexec = -1; (void) fcntl(fd, F_SETFD, FD_CLOEXEC); } } else goto syserror; } else if (flags & SOCK_CLOEXEC) have_cloexec = 1; madefd = TRUE; } if (raddr->sin_port == 0) { u_int proto; u_short sport; mutex_unlock(&rpcsoc_lock); /* pmap_getport is recursive */ proto = strcmp(tp, "udp") == 0 ? IPPROTO_UDP : IPPROTO_TCP; sport = pmap_getport(raddr, (u_long) prog, (u_long) vers, proto); if (sport == 0) goto err; raddr->sin_port = htons(sport); mutex_lock(&rpcsoc_lock); /* pmap_getport is recursive */ } /* Transform sockaddr_in to netbuf */ bindaddr.maxlen = bindaddr.len = sizeof(struct sockaddr_in); bindaddr.buf = raddr; bindresvport(fd, NULL); cl = clnt_tli_ncreate(fd, nconf, &bindaddr, prog, vers, sendsz, recvsz); if (cl) { if (madefd == TRUE) { /* * The fd should be closed while destroying the handle. */ (void)CLNT_CONTROL(cl, CLSET_FD_CLOSE, NULL); *sockp = fd; } (void)freenetconfigent(nconf); mutex_unlock(&rpcsoc_lock); return (cl); } goto err; syserror: rpc_createerr.cf_stat = RPC_SYSTEMERROR; rpc_createerr.cf_error.re_errno = errno; err: if (madefd == TRUE) (void)close(fd); (void)freenetconfigent(nconf); mutex_unlock(&rpcsoc_lock); return (NULL); } /* XXX suspicious */ CLIENT * __libc_clntudp_nbufcreate(struct sockaddr_in *raddr, u_long prog, u_long vers, struct timeval wait, int *sockp, u_int sendsz, u_int recvsz, int flags) { CLIENT *cl; cl = clnt_com_ncreate(raddr, (rpcprog_t) prog, (rpcvers_t) vers, sockp, sendsz, recvsz, "udp", flags); if (cl == NULL) return (NULL); (void)CLNT_CONTROL(cl, CLSET_RETRY_TIMEOUT, &wait); return (cl); } CLIENT * clntudp_nbufcreate(struct sockaddr_in *raddr, u_long prog, u_long vers, struct timeval wait, int *sockp, u_int sendsz, u_int recvsz) { CLIENT *cl; cl = clnt_com_ncreate(raddr, (rpcprog_t) prog, (rpcvers_t) vers, sockp, sendsz, recvsz, "udp", 0); if (cl == NULL) return (NULL); (void)CLNT_CONTROL(cl, CLSET_RETRY_TIMEOUT, &wait); return (cl); } CLIENT * clntudp_create(struct sockaddr_in *raddr, u_long program, u_long version, struct timeval wait, int *sockp) { return clntudp_nbufcreate(raddr, program, version, wait, sockp, UDPMSGSIZE, UDPMSGSIZE); } CLIENT * clnttcp_create(struct sockaddr_in *raddr, u_long prog, u_long vers, int *sockp, u_int sendsz, u_int recvsz) { return clnt_com_ncreate(raddr, (rpcprog_t) prog, (rpcvers_t) vers, sockp, sendsz, recvsz, "tcp", 0); } /* IPv6 version of clnt*_*create */ #ifdef INET6_NOT_USED CLIENT * clntudp6_nbufcreate(struct sockaddr_in6 *raddr, u_long prog, u_long vers, struct timeval wait, int *sockp, u_int sendsz, u_int recvsz) { CLIENT *cl; cl = clnt_com_ncreate(raddr, (rpcprog_t) prog, (rpcvers_t) vers, sockp, sendsz, recvsz, "udp6", 0); if (cl == NULL) return (NULL); (void)CLNT_CONTROL(cl, CLSET_RETRY_TIMEOUT, &wait); return (cl); } CLIENT * clntudp6_ncreate(struct sockaddr_in6 *raddr, u_long program, u_long version, struct timeval wait, int *sockp) { return clntudp6_nbufcreate(raddr, program, version, wait, sockp, UDPMSGSIZE, UDPMSGSIZE); } CLIENT * clnttcp6_ncreate(struct sockaddr_in6 *raddr, u_long prog, u_long vers, int *sockp, u_int sendsz, u_int recvsz) { return clnt_com_ncreate(raddr, (rpcprog_t) prog, (rpcvers_t) vers, sockp, sendsz, recvsz, "tcp6", 0); } #endif CLIENT * clntraw_create(u_long prog, u_long vers) { return clnt_raw_create((rpcprog_t) prog, (rpcvers_t) vers); } /* * A common server create routine */ static SVCXPRT * svc_com_ncreate(int fd, u_int sendsize, u_int recvsize, char *netid) { struct netconfig *nconf; SVCXPRT *svc; int madefd = FALSE; int port; struct sockaddr_in sin; nconf = __rpc_getconfip(netid); if (!nconf) { (void)syslog(LOG_ERR, "Could not get %s transport", netid); return (NULL); } if (fd == RPC_ANYSOCK) { fd = __rpc_nconf2fd(nconf); if (fd == -1) { (void)freenetconfigent(nconf); (void)syslog(LOG_ERR, "svc%s_create: could not open connection", netid); return (NULL); } madefd = TRUE; } memset(&sin, 0, sizeof(sin)); sin.sin_family = AF_INET; bindresvport(fd, &sin); listen(fd, SOMAXCONN); svc = svc_tli_ncreate(fd, nconf, NULL, sendsize, recvsize); (void)freenetconfigent(nconf); if (svc == NULL) { if (madefd) (void)close(fd); return (NULL); } port = (((struct sockaddr_in *)&svc->xp_local.ss)->sin_port); svc->xp_port = ntohs(port); return (svc); } SVCXPRT * svctcp_create(int fd, u_int sendsize, u_int recvsize) { return svc_com_ncreate(fd, sendsize, recvsize, "tcp"); } SVCXPRT * svcudp_bufcreate(int fd, u_int sendsz, u_int recvsz) { return svc_com_ncreate(fd, sendsz, recvsz, "udp"); } SVCXPRT * svcfd_create(int fd, u_int sendsize, u_int recvsize) { return svc_fd_ncreate(fd, sendsize, recvsize); } SVCXPRT * svcudp_create(int fd) { return svc_com_ncreate(fd, UDPMSGSIZE, UDPMSGSIZE, "udp"); } SVCXPRT * svcraw_create() { return svc_raw_ncreate(); } /* IPV6 version */ #ifdef INET6_NOT_USED SVCXPRT *svcudp6_nbufcreate(int fd, u_int sendsz, u_int recvsz) { return svc_com_ncreate(fd, sendsz, recvsz, "udp6"); } SVCXPRT * svctcp6_ncreate(int fd, u_int sendsize, u_int recvsize) { return svc_com_ncreate(fd, sendsize, recvsize, "tcp6"); } SVCXPRT * svcudp6_ncreate(int fd) { return svc_com_ncreate(fd, UDPMSGSIZE, UDPMSGSIZE, "udp6"); } #endif int get_myaddress(struct sockaddr_in *addr) { memset((void *)addr, 0, sizeof(*addr)); addr->sin_family = AF_INET; addr->sin_port = htons(PMAPPORT); addr->sin_addr.s_addr = htonl(INADDR_LOOPBACK); return (0); } /* * For connectionless "udp" transport. Obsoleted by rpc_call(). */ int callrpc(const char *host, int prognum, int versnum, int procnum, xdrproc_t inproc, void *in, xdrproc_t outproc, void *out) { return (int)rpc_call(host, (rpcprog_t) prognum, (rpcvers_t) versnum, (rpcproc_t) procnum, inproc, in, outproc, out, "udp"); } /* * For connectionless kind of transport. Obsoleted by rpc_reg() */ int registerrpc(int prognum, int versnum, int procnum, char *(*progname) (char[UDPMSGSIZE]), xdrproc_t inproc, xdrproc_t outproc) { return rpc_reg((rpcprog_t) prognum, (rpcvers_t) versnum, (rpcproc_t) procnum, progname, inproc, outproc, "udp"); } /* * All the following clnt_broadcast stuff is convulated; it supports * the earlier calling style of the callback function */ extern thread_key_t clnt_broadcast_key; /* * Need to translate the netbuf address into sockaddr_in address. * Dont care about netid here. */ /* ARGSUSED */ static bool rpc_wrap_bcast(char *resultp, /* results of the call */ struct netbuf *addr, /* address of the guy who responded */ struct netconfig *nconf /* Netconf of the transport */) { resultproc_t clnt_broadcast_result; if (strcmp(nconf->nc_netid, "udp")) return (FALSE); clnt_broadcast_result = (resultproc_t) thr_getspecific(clnt_broadcast_key); return (*clnt_broadcast_result) (resultp, (struct sockaddr_in *)addr->buf); } /* * Broadcasts on UDP transport. Obsoleted by rpc_broadcast(). */ enum clnt_stat clnt_broadcast(u_long prog, /* program number */ u_long vers, /* version number */ u_long proc, /* procedure number */ xdrproc_t xargs, /* xdr routine for args */ void *argsp, /* pointer to args */ xdrproc_t xresults, /* xdr routine for results */ void *resultsp, /* pointer to results */ resultproc_t eachresult /* call with each result obtained */) { extern mutex_t tsd_lock; if (clnt_broadcast_key == -1) { mutex_lock(&tsd_lock); if (clnt_broadcast_key == -1) thr_keycreate(&clnt_broadcast_key, thr_keyfree); mutex_unlock(&tsd_lock); } thr_setspecific(clnt_broadcast_key, (void *)eachresult); return rpc_broadcast((rpcprog_t) prog, (rpcvers_t) vers, (rpcproc_t) proc, xargs, argsp, xresults, resultsp, (resultproc_t) rpc_wrap_bcast, "udp"); } #if !defined(__APPLE__) #if USE_DES /* * Create the client des authentication object. Obsoleted by * authdes_seccreate(). */ AUTH * authdes_ncreate(char *servername, /* network name of server */ u_int window, /* time to live */ struct sockaddr *syncaddr, /* optional hostaddr to sync with */ des_block *ckey /* optional conversation key to use */) { AUTH *dummy; AUTH *nauth; char hostname[NI_MAXHOST]; if (syncaddr) { /* * Change addr to hostname, because that is the way * new interface takes it. */ if (getnameinfo (syncaddr, sizeof(syncaddr), hostname, sizeof(hostname), NULL, 0, 0) != 0) goto fallback; nauth = authdes_nseccreate(servername, window, hostname, ckey); return (nauth); } fallback: dummy = authdes_nseccreate(servername, window, NULL, ckey); return (dummy); } #endif /* USE_DES */ #endif /* !APPLE */ /* * Create a client handle for a unix connection. Obsoleted by clnt_vc_create() */ CLIENT * clntunix_ncreate(struct sockaddr_un *raddr, u_long prog, u_long vers, int *sockp, u_int sendsz, u_int recvsz) { struct netbuf svcaddr; CLIENT *cl = NULL; int len; if (*sockp < 0) { *sockp = socket(AF_LOCAL, SOCK_STREAM, 0); len = SUN_LEN(raddr); if ((*sockp < 0) || (connect(*sockp, (struct sockaddr *)raddr, len) < 0)) { rpc_createerr.cf_stat = RPC_SYSTEMERROR; rpc_createerr.cf_error.re_errno = errno; if (*sockp != -1) (void)close(*sockp); goto done; } } svcaddr.buf = raddr; svcaddr.len = sizeof(*raddr); svcaddr.maxlen = sizeof(struct sockaddr_un); cl = clnt_vc_ncreate(*sockp, &svcaddr, prog, vers, sendsz, recvsz); done: return (cl); } /* * Creates, registers, and returns a (rpc) unix based transporter. * Obsoleted by svc_vc_create(). */ SVCXPRT * svcunix_ncreate(int sock, u_int sendsize, u_int recvsize, char *path) { struct netconfig *nconf; void *localhandle; struct sockaddr_un sun; struct sockaddr *sa; struct t_bind taddr; SVCXPRT *xprt; int addrlen; xprt = (SVCXPRT *) NULL; localhandle = setnetconfig(); while ((nconf = getnetconfig(localhandle)) != NULL) { if (nconf->nc_protofmly != NULL && strcmp(nconf->nc_protofmly, NC_LOOPBACK) == 0) break; } if (nconf == NULL) goto done; sock = __rpc_nconf2fd(nconf); if (sock < 0) goto done; memset(&sun, 0, sizeof(sun)); sun.sun_family = AF_LOCAL; strncpy(sun.sun_path, path, sizeof(sun.sun_path)); sun.sun_path[sizeof(sun.sun_path)-1] = '\0'; addrlen = sizeof(struct sockaddr_un); sa = (struct sockaddr *)&sun; if (bind(sock, sa, addrlen) < 0) goto done; taddr.addr.len = taddr.addr.maxlen = addrlen; taddr.addr.buf = mem_alloc(addrlen); memcpy(taddr.addr.buf, sa, addrlen); if (nconf->nc_semantics != NC_TPI_CLTS) { if (listen(sock, SOMAXCONN) < 0) { mem_free(taddr.addr.buf, addrlen); goto done; } } xprt = (SVCXPRT *) svc_tli_ncreate(sock, nconf, &taddr, sendsize, recvsize); done: endnetconfig(localhandle); if (! xprt) close(sock); return (xprt); } /* * Like svunix_create(), except the routine takes any *open* UNIX file * descriptor as its first input. Obsoleted by svc_fd_create(); */ SVCXPRT * svcunixfd_ncreate(int fd, u_int sendsize, u_int recvsize) { return (svc_fd_create(fd, sendsize, recvsize)); } #endif /* PORTMAP */ <file_sep>/* * Copyright (c) 2012 Linux Box Corporation. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR `AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TIRPC_COMPAT_H #define TIRPC_COMPAT_H /* clnt_soc.h */ #define clnttcp_create(a, b, c, d, e, f) clnttcp_ncreate(a, b, c, d, e, f) #define clntraw_create(a, b) clntraw_ncreate(a, b) #define clnttcp6_create(a, b, c, d, e, f) clnttcp6_ncreate(a, b, c, d, e, f) #define clntudp_create(a, b, c, d, e) clntudp_ncreate(a, b, c, d, e) #define clntudp_bufcreate(a, b, c, d, e, f, g) \ clntudp_nbufcreate(a, b, c, d, e, f, g) #define clntudp6_create(a, b, c, d, e) clntudp6_ncreate(a, b, c, d, e) #define clntudp6_bufcreate(a, b, c, d, e, f, g) \ clntudp6_nbufcreate(a, b, c, d, e, f, g) /* clnt.h */ #define clnt_create(a, b, c, d) clnt_ncreate(a, b, c, d) #define clnt_create_time(a, b, c, d, e) clnt_ncreate_time(a, b, c, d, e) #define clnt_create_vers(a, b, c, d, e, f) clnt_ncreate_vers(a, b, c, d, e, f) #define clnt_create_vers_timed(a, b, c, d, e, f, g) \ clnt_ncreate_vers_timed(a, b, c, d, e, f, g) #define clnt_tp_create(a, b, c, d) clnt_tp_ncreate(a, b, c, d) #define clnt_tp_create_timed(a, b, c, d, e) clnt_tp_ncreate_timed(a, b, c, d, e) #define clnt_tli_create(a, b, c, d, e, f, g) \ clnt_tli_ncreate(a, b, c, d, e, f, g) #define clnt_vc_create(a, b, c, d, e, f) clnt_vc_ncreate(a, b, c, d, e, f) #define clnt_vc_create2(a, b, c, d, e, f, g) \ clnt_vc_ncreate2(a, b, c, d, e, f, g) #define clntunix_create(a, b, c, d, e) clntunix_ncreate(a, b, c, d, e) #define clnt_dg_create(a, b, c, d, e, f) clnt_dg_ncreate(a, b, c, d, e, f) #define clnt_raw_create(a, b) clnt_raw_ncreate(a, b) /* svc_soc.h */ #define svcraw_create() svcraw_ncreate() #define svcudp_create(a) svcudp_ncreate(a) #define svcudp_bufcreate(a, b, c) svcudp_nbufcreate(a, b, c) #define svcudp6_create(a) svcudp6_ncreate(a) #define svcudp6_bufcreate(a, b, c) svcudp6_nbufcreate(a, b, c) #define svctcp_create(a, b, c) svctcp_ncreate(a, b, c) #define svctcp6_create(a, b, c) svctcp6_ncreate(a, b, c) /* svc.h */ #define svc_create(a, b, c, d) svc_ncreate(a, b, c, d) #define svc_tp_create(a, b, c, d) svc_tp_ncreate(a, b, c, d) #define svc_tli_create(a, b, c, d, e) svc_tli_ncreate(a, b, c, d, e) #define svc_vc_create(a, b, c) svc_vc_ncreate(a, b, c) #define svc_vc_create2(a, b, c, d) svc_vc_ncreate2(a, b, c, d) #define clnt_vc_create_svc(a, b, c, d) clnt_vc_ncreate_svc(a, b, c, d) #define svc_vc_create_clnt(a, b, c, d) svc_vc_ncreate_clnt(a, b, c, d) #define svcunix_create(a, b, c, d) svcunix_ncreate(a, b, c, d) #define svc_dg_create(a, b, c) svc_dg_ncreate(a, b, c) #define svc_fd_create(a, b, c) svc_fd_ncreate(a, b, c) #define svcunixfd_create(a, b, c) svcunixfd_ncreate(a, b, c) #define svc_raw_create() svc_raw_ncreate() #define svc_rdma_create(a, b, c, d) svc_rdma_ncreate(a, b, c, d) /* auth */ #define authunix_create(a, b, c, d, e) authunix_ncreate(a, b, c, d, e) #define authunix_create_default() authunix_ncreate_default() #define authnone_create() authnone_ncreate() #define authdes_create(a, b, c, d) authdes_ncreate(a, b, c, d) #define authdes_seccreate(a, b, c, d) authdes_nseccreate(a, b, c, d) #define authsys_create(c, i1, i2, i3, ip) \ authunix_ncreate((c), (i1), (i2), (i3), (ip)) #define authsys_create_default() authunix_ncreate_default() #define authkerb_seccreate(a, b, c, d, e, f) \ authkerb_nseccreate(a, b, c, d, e, f) #define authkerb_create(a, b, c, d, e, f, g, h, i) \ authkerb_ncreate(a, b, c, d, e, f, g, h, i) #define authgss_create(a, b, c) authgss_ncreate(a, b, c) #define authgss_create_default(a, b, c) authgss_ncreate_default(a, b, c) /* rpc_msg */ #define xdr_callmsg xdr_ncallmsg #define xdr_callhdr xdr_ncallhdr #define xdr_replymsg xdr_nreplymsg #define xdr_accepted_reply xdr_naccepted_reply #define xdr_rejected_reply xdr_nrejected_reply /* xdr */ #define xdr_netobj xdr_nnetobj #define xdrmem_create(a, b, c, d) xdrmem_ncreate(a, b, c, d) #define xdr_free xdr_nfree #endif /* !TIRPC_COMPAT_H */ <file_sep>/* * Copyright (c) 2012 Linux Box Corporation. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR `AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TIRPC_SVC_INTERNAL_H #define TIRPC_SVC_INTERNAL_H #include <misc/os_epoll.h> extern int __svc_maxiov; extern int __svc_maxrec; /* threading fdsets around is annoying */ struct svc_params { bool initialized; mutex_t mtx; u_long flags; /* package global event handling--may be overridden using the * svc_rqst interface */ enum svc_event_type ev_type; union { struct { uint32_t id; uint32_t max_events; } evchan; struct { fd_set set; /* select/fd_set (currently unhooked) */ } fd; } ev_u; int32_t idle_timeout; u_int max_connections; u_int svc_ioq_maxbuf; union { struct { mutex_t mtx; u_int nconns; } vc; } xprt_u; struct { int ctx_hash_partitions; int max_ctx; int max_idle_gen; int max_gc; } gss; struct { u_int thrd_max; } ioq; }; extern struct svc_params __svc_params[1]; #define svc_cond_init() \ do { \ if (!__svc_params->initialized) { \ (void)svc_init(&(svc_init_params) \ { .flags = SVC_INIT_EPOLL, \ .max_connections = 8192, \ .max_events = 512, \ .gss_ctx_hash_partitions = 13,\ .gss_max_ctx = 1024, \ .gss_max_idle_gen = 1024, \ .gss_max_gc = 200 \ }); \ } \ } while (0) static inline bool svc_vc_new_conn_ok(void) { bool ok = false; svc_cond_init(); mutex_lock((&__svc_params->xprt_u.vc.mtx)); if (__svc_params->xprt_u.vc.nconns < __svc_params->max_connections) { ++(__svc_params->xprt_u.vc.nconns); ok = true; } mutex_unlock(&(__svc_params->xprt_u.vc.mtx)); return (ok); } #define svc_vc_dec_nconns() \ do { \ mutex_lock((&__svc_params->xprt_u.vc.mtx)); \ --(__svc_params->xprt_u.vc.nconns); \ mutex_unlock(&(__svc_params->xprt_u.vc.mtx)); \ } while (0) struct __svc_ops { bool (*svc_clean_idle) (fd_set *fds, int timeout, bool cleanblock); void (*svc_run) (void); void (*svc_getreq) (int rdfds); /* XXX */ void (*svc_getreqset) (fd_set *readfds); /* XXX */ void (*svc_exit) (void); }; extern struct __svc_ops *svc_ops; #define su_data(xprt) ((struct svc_dg_data *)(xprt->xp_p2)) /* The CACHING COMPONENT */ /* * Could have been a separate file, but some part of it depends upon the * private structure of the client handle. * * Fifo cache for cl server * Copies pointers to reply buffers into fifo cache * Buffers are sent again if retransmissions are detected. */ #define SPARSENESS 4 /* 75% sparse */ /* * An entry in the cache */ typedef struct cache_node *cache_ptr; struct cache_node { /* * Index into cache is xid, proc, vers, prog and address */ u_int32_t cache_xid; rpcproc_t cache_proc; rpcvers_t cache_vers; rpcprog_t cache_prog; struct netbuf cache_addr; /* * The cached reply and length */ char *cache_reply; size_t cache_replylen; /* * Next node on the list, if there is a collision */ cache_ptr cache_next; }; /* * the hashing function */ #define CACHE_LOC(transp, xid) \ (xid % (SPARSENESS * ((struct cl_cache *) \ su_data(transp)->su_cache)->uc_size)) extern mutex_t dupreq_lock; /* * The entire cache */ struct cl_cache { u_int uc_size; /* size of cache */ cache_ptr *uc_entries; /* hash table of entries in cache */ cache_ptr *uc_fifo; /* fifo list of entries in cache */ u_int uc_nextvictim; /* points to next victim in fifo list */ rpcprog_t uc_prog; /* saved program number */ rpcvers_t uc_vers; /* saved version number */ rpcproc_t uc_proc; /* saved procedure number */ }; /* Epoll interface change */ #ifndef EPOLL_CLOEXEC #define EPOLL_CLOEXEC 02000000 static inline int epoll_create_wr(size_t size, int flags) { return (epoll_create(size)); } #else static inline int epoll_create_wr(size_t size, int flags) { return (epoll_create1(flags)); } #endif #if defined(HAVE_BLKIN) extern void __rpc_set_blkin_endpoint(SVCXPRT *xprt, const char *tag); #endif void svc_rqst_shutdown(void); #endif /* TIRPC_SVC_INTERNAL_H */ <file_sep> #include <config.h> #include <sys/cdefs.h> #include <pthread.h> #include <reentrant.h> #include <rpc/rpc.h> #include <sys/time.h> #include <stdlib.h> #include <string.h> #include "rpc_com.h" /* protects the services list (svc.c) */ pthread_rwlock_t svc_lock = RWLOCK_INITIALIZER; /* protects the RPCBIND address cache */ pthread_rwlock_t rpcbaddr_cache_lock = RWLOCK_INITIALIZER; /* protects authdes cache (svcauth_des.c) */ pthread_mutex_t authdes_lock = MUTEX_INITIALIZER; /* serializes authdes ops initializations */ pthread_mutex_t authdes_ops_lock = MUTEX_INITIALIZER; /* protects des stats list */ pthread_mutex_t svcauthdesstats_lock = MUTEX_INITIALIZER; #ifdef KERBEROS /* auth_kerb.c serialization */ pthread_mutex_t authkerb_lock = MUTEX_INITIALIZER; /* protects kerb stats list */ pthread_mutex_t svcauthkerbstats_lock = MUTEX_INITIALIZER; #endif /* KERBEROS */ /* protects the Auths list (svc_auth.c) */ pthread_mutex_t authsvc_lock = MUTEX_INITIALIZER; /* clnt_raw.c serialization */ pthread_mutex_t clntraw_lock = MUTEX_INITIALIZER; /* domainname and domain_fd (getdname.c) and default_domain (rpcdname.c) */ pthread_mutex_t dname_lock = MUTEX_INITIALIZER; /* dupreq variables (svc_dg.c) */ pthread_mutex_t dupreq_lock = MUTEX_INITIALIZER; /* protects first_time and hostname (key_call.c) */ pthread_mutex_t keyserv_lock = MUTEX_INITIALIZER; /* serializes rpc_trace() (rpc_trace.c) */ pthread_mutex_t libnsl_trace_lock = MUTEX_INITIALIZER; /* loopnconf (rpcb_clnt.c) */ pthread_mutex_t loopnconf_lock = MUTEX_INITIALIZER; /* serializes ops initializations */ pthread_mutex_t ops_lock = MUTEX_INITIALIZER; /* protect svc counters */ pthread_mutex_t svc_ctr_lock = MUTEX_INITIALIZER; /* protects ``port'' static in bindresvport() */ pthread_mutex_t portnum_lock = MUTEX_INITIALIZER; /* protects proglst list (svc_simple.c) */ pthread_mutex_t proglst_lock = MUTEX_INITIALIZER; /* serializes clnt_com_create() (rpc_soc.c) */ pthread_mutex_t rpcsoc_lock = MUTEX_INITIALIZER; /* svc_raw.c serialization */ pthread_mutex_t svcraw_lock = MUTEX_INITIALIZER; /* protects TSD key creation */ pthread_mutex_t tsd_lock = MUTEX_INITIALIZER; /* Library global tsd keys */ thread_key_t clnt_broadcast_key; thread_key_t rpc_call_key = -1; thread_key_t tcp_key = -1; thread_key_t udp_key = -1; thread_key_t nc_key = -1; thread_key_t rce_key = -1; thread_key_t vsock_key = -1; /* xprtlist (svc_generic.c) */ pthread_mutex_t xprtlist_lock = MUTEX_INITIALIZER; /* serializes calls to public key routines */ pthread_mutex_t serialize_pkey = MUTEX_INITIALIZER; #undef rpc_createerr struct rpc_createerr rpc_createerr; struct rpc_createerr *__rpc_createerr(void) { struct rpc_createerr *rce_addr; mutex_lock(&tsd_lock); if (rce_key == -1) thr_keycreate(&rce_key, thr_keyfree); mutex_unlock(&tsd_lock); rce_addr = (struct rpc_createerr *)thr_getspecific(rce_key); if (!rce_addr) { rce_addr = (struct rpc_createerr *) mem_alloc(sizeof(struct rpc_createerr)); if (thr_setspecific(rce_key, (void *)rce_addr) != 0) { mem_free(rce_addr, sizeof(*rce_addr)); return (&rpc_createerr); } memset(rce_addr, 0, sizeof(*rce_addr)); } return (rce_addr); } void tsd_key_delete(void) { if (clnt_broadcast_key != -1) pthread_key_delete(clnt_broadcast_key); if (rpc_call_key != -1) pthread_key_delete(rpc_call_key); if (tcp_key != -1) pthread_key_delete(tcp_key); if (udp_key != -1) pthread_key_delete(udp_key); if (nc_key != -1) pthread_key_delete(nc_key); if (rce_key != -1) pthread_key_delete(rce_key); return; } <file_sep>/* * Copyright (c) 2013 Linux Box Corporation. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR `AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <config.h> #include <sys/types.h> #if !defined(_WIN32) #include <netinet/in.h> #include <err.h> #endif #include <rpc/types.h> #include "rpc_com.h" #include <sys/types.h> #include <reentrant.h> #include <misc/portable.h> #include <stddef.h> #include <assert.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <intrinsic.h> #include <misc/thrdpool.h> int thrdpool_init(struct thrdpool *pool, const char *name, struct thrdpool_params *params) { memset(pool, 0, sizeof(struct thrdpool)); init_wait_entry(&pool->we); mutex_lock(&pool->we.mtx); pool->name = mem_strdup(name); pool->params = *params; TAILQ_INIT(&pool->idle_q); TAILQ_INIT(&pool->work_q); (void)pthread_attr_init(&pool->attr); (void)pthread_attr_setscope(&pool->attr, PTHREAD_SCOPE_SYSTEM); (void)pthread_attr_setdetachstate(&pool->attr, PTHREAD_CREATE_DETACHED); mutex_unlock(&pool->we.mtx); return 0; } static bool thrd_wait(struct thrd *thrd) { bool code = false; struct thrdpool *pool = thrd->pool; struct timespec ts; struct work *work; int rc; mutex_lock(&pool->we.mtx); if (pool->flags & THRD_FLAG_SHUTDOWN) { mutex_unlock(&pool->we.mtx); goto out; } TAILQ_FOREACH(work, &pool->work_q, tailq) { TAILQ_REMOVE(&pool->work_q, work, tailq); thrd->ctx.work = work; code = true; mutex_unlock(&pool->we.mtx); goto out; } TAILQ_INSERT_TAIL(&pool->idle_q, thrd, tailq); ++(pool->n_idle); mutex_lock(&thrd->ctx.we.mtx); thrd->idle = true; mutex_unlock(&pool->we.mtx); while (1) { clock_gettime(CLOCK_REALTIME_FAST, &ts); timespec_addms(&ts, 1000 * 120); if (pool->flags & THRD_FLAG_SHUTDOWN) { rc = ETIMEDOUT; } else { rc = cond_timedwait(&thrd->ctx.we.cv, &thrd->ctx.we.mtx, &ts); } if (rc == ETIMEDOUT) { mutex_unlock(&thrd->ctx.we.mtx); mutex_lock(&pool->we.mtx); mutex_lock(&thrd->ctx.we.mtx); if (!thrd->idle) { /* raced */ code = true; mutex_unlock(&thrd->ctx.we.mtx); mutex_unlock(&pool->we.mtx); goto out; } code = false; TAILQ_REMOVE(&pool->idle_q, thrd, tailq); --(pool->n_idle); thrd->idle = false; mutex_unlock(&thrd->ctx.we.mtx); mutex_unlock(&pool->we.mtx); goto out; } /* signalled */ code = !thrd->idle; mutex_unlock(&thrd->ctx.we.mtx); break; } out: return (code); } static void *thrdpool_start_routine(void *arg) { struct thrd *thrd = arg; struct thrdpool *pool = thrd->pool; bool reschedule; do { struct work *work = thrd->ctx.work; work->func(work->arg); thrd->ctx.work = 0; mem_free(work, sizeof(struct work)); reschedule = thrd_wait(thrd); } while (reschedule); /* cleanup thread context */ destroy_wait_entry(&thrd->ctx.we); --(thrd->pool->n_threads); mutex_lock(&pool->we.mtx); cond_signal(&pool->we.cv); mutex_unlock(&pool->we.mtx); mem_free(thrd, 0); return (NULL); } static inline bool thrdpool_dispatch(struct thrdpool *pool, struct work *work) { struct thrd *thrd; TAILQ_FOREACH(thrd, &pool->idle_q, tailq) { mutex_lock(&thrd->ctx.we.mtx); TAILQ_REMOVE(&pool->idle_q, thrd, tailq); --(pool->n_idle); thrd->idle = false; thrd->ctx.work = work; cond_signal(&thrd->ctx.we.cv); mutex_unlock(&thrd->ctx.we.mtx); break; } return (true); } static inline bool thrdpool_spawn(struct thrdpool *pool, struct work *work) { int code; struct thrd *thrd = mem_alloc(sizeof(struct thrd)); memset(thrd, 0, sizeof(struct thrd)); init_wait_entry(&thrd->ctx.we); thrd->pool = pool; thrd->ctx.work = work; ++(pool->n_threads); code = pthread_create(&thrd->ctx.id, &pool->attr, thrdpool_start_routine, thrd); if (code != 0) { __warnx(TIRPC_DEBUG_FLAG_SVC_VC, "pthread_create failed %d\n", __func__, errno); } return (true); } int thrdpool_submit_work(struct thrdpool *pool, thrd_func_t func, void *arg) { int code = 0; struct work *work; /* queue is draining */ mutex_lock(&pool->we.mtx); if (unlikely(pool->flags & THRD_FLAG_SHUTDOWN)) goto unlock; work = mem_zalloc(sizeof(struct work)); if (unlikely(!work)) { code = -1; goto unlock; } work->func = func; work->arg = arg; /* idle thread(s) available */ if (pool->n_idle > 0) { if (thrdpool_dispatch(pool, work)) goto unlock; } /* need a thread */ if ((pool->params.thrd_max == 0) || (pool->n_threads < pool->params.thrd_max)) { code = thrdpool_spawn(pool, work); goto unlock; } TAILQ_INSERT_TAIL(&pool->work_q, work, tailq); unlock: mutex_unlock(&pool->we.mtx); return (code); } int thrdpool_shutdown(struct thrdpool *pool) { struct timespec ts; int wait = 1; struct thrd *thrd; struct work *work; mutex_lock(&pool->we.mtx); pool->flags |= THRD_FLAG_SHUTDOWN; TAILQ_FOREACH(thrd, &pool->idle_q, tailq) { cond_signal(&thrd->ctx.we.cv); } TAILQ_FOREACH(work, &pool->work_q, tailq) { work->func(work->arg); } while (pool->n_threads > 0) { clock_gettime(CLOCK_REALTIME_FAST, &ts); timespec_addms(&ts, 1000 * wait); (void)cond_timedwait(&pool->we.cv, &pool->we.mtx, &ts); /* wait a bit longer */ wait = 5; } mem_free(pool->name, 0); mutex_unlock(&pool->we.mtx); destroy_wait_entry(&pool->we); return (0); } <file_sep> /* * Copyright (c) 2009, Sun Microsystems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - Neither the name of Sun Microsystems, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* * Copyright (c) 1986-1991 by Sun Microsystems Inc. */ /* * svc_raw.c, This a toy for simple testing and timing. * Interface to create an rpc client and server in the same UNIX process. * This lets us similate rpc and get rpc (round trip) overhead, without * any interference from the kernel. * */ #include <config.h> #include <pthread.h> #include <reentrant.h> #include <rpc/rpc.h> #include <sys/types.h> #include <rpc/raw.h> #include <stdlib.h> #ifndef UDPMSGSIZE #define UDPMSGSIZE 8800 #endif /* * This is the "network" that we will be moving data over */ static struct svc_raw_private { char *raw_buf; /* should be shared with the cl handle */ SVCXPRT server; XDR xdr_stream; char verf_body[MAX_AUTH_BYTES]; } *svc_raw_private; extern mutex_t svcraw_lock; static void svc_raw_ops(SVCXPRT *); char *__rpc_rawcombuf = NULL; SVCXPRT * svc_raw_ncreate(void) { struct svc_raw_private *srp; /* VARIABLES PROTECTED BY svcraw_lock: svc_raw_private, srp */ mutex_lock(&svcraw_lock); srp = svc_raw_private; if (srp == NULL) { srp = (struct svc_raw_private *)mem_alloc(sizeof(*srp)); if (__rpc_rawcombuf == NULL) __rpc_rawcombuf = mem_alloc(UDPMSGSIZE * sizeof(char)); srp->raw_buf = __rpc_rawcombuf; /* Share it with the client */ svc_raw_private = srp; } srp->server.xp_fd = FD_SETSIZE; srp->server.xp_port = 0; srp->server.xp_p3 = NULL; svc_raw_ops(&srp->server); /* XXX check and or fixme */ #if 0 srp->server.xp_verf.oa_base = srp->verf_body; #endif xdrmem_create(&srp->xdr_stream, srp->raw_buf, UDPMSGSIZE, XDR_DECODE); xprt_register(&srp->server); mutex_unlock(&svcraw_lock); return (&srp->server); } /*ARGSUSED*/ static enum xprt_stat svc_raw_stat(SVCXPRT *xprt) { return (XPRT_IDLE); } /*ARGSUSED*/ static bool svc_raw_recv(SVCXPRT *xprt, struct svc_req *req) { struct rpc_msg *msg = req->rq_msg; struct svc_raw_private *srp; XDR *xdrs; mutex_lock(&svcraw_lock); srp = svc_raw_private; if (srp == NULL) { mutex_unlock(&svcraw_lock); return (false); } mutex_unlock(&svcraw_lock); xdrs = &srp->xdr_stream; xdrs->x_op = XDR_DECODE; (void)XDR_SETPOS(xdrs, 0); if (!xdr_callmsg(xdrs, msg)) return (false); return (true); } /*ARGSUSED*/ static bool svc_raw_reply(SVCXPRT *xprt, struct svc_req *req, struct rpc_msg *msg) { struct svc_raw_private *srp; XDR *xdrs; mutex_lock(&svcraw_lock); srp = svc_raw_private; if (srp == NULL) { mutex_unlock(&svcraw_lock); return (false); } mutex_unlock(&svcraw_lock); xdrs = &srp->xdr_stream; xdrs->x_op = XDR_ENCODE; (void)XDR_SETPOS(xdrs, 0); if (!xdr_replymsg(xdrs, msg)) return (false); (void)XDR_GETPOS(xdrs); /* called just for overhead */ return (true); } /*ARGSUSED*/ static bool svc_raw_freeargs(SVCXPRT *xprt, struct svc_req *req, xdrproc_t xdr_args, void *args_ptr) { struct svc_raw_private *srp; XDR *xdrs; mutex_lock(&svcraw_lock); srp = svc_raw_private; if (srp == NULL) { mutex_unlock(&svcraw_lock); return (false); } mutex_unlock(&svcraw_lock); xdrs = &srp->xdr_stream; xdrs->x_op = XDR_FREE; return (*xdr_args) (xdrs, args_ptr); } /*ARGSUSED*/ static bool svc_raw_getargs(SVCXPRT *xprt, struct svc_req *req, xdrproc_t xdr_args, void *args_ptr, void *u_data) { struct svc_raw_private *srp; mutex_lock(&svcraw_lock); srp = svc_raw_private; if (srp == NULL) { mutex_unlock(&svcraw_lock); return (false); } mutex_unlock(&svcraw_lock); return (*xdr_args) (&srp->xdr_stream, args_ptr); } /*ARGSUSED*/ static void svc_raw_destroy(SVCXPRT *xprt, u_int flags, const char *tag, const int line) { } /*ARGSUSED*/ static bool svc_raw_control(SVCXPRT *xprt, const u_int rq, void *in) { return (false); } static void svc_raw_ops(SVCXPRT *xprt) { static struct xp_ops ops; extern mutex_t ops_lock; /* VARIABLES PROTECTED BY ops_lock: ops */ mutex_lock(&ops_lock); if (ops.xp_recv == NULL) { ops.xp_recv = svc_raw_recv; ops.xp_stat = svc_raw_stat; ops.xp_getargs = svc_raw_getargs; ops.xp_reply = svc_raw_reply; ops.xp_freeargs = svc_raw_freeargs; ops.xp_destroy = svc_raw_destroy; ops.xp_control = svc_raw_control; ops.xp_lock = NULL; /* no default */ ops.xp_unlock = NULL; /* no default */ ops.xp_getreq = svc_getreq_default; ops.xp_dispatch = svc_dispatch_default; ops.xp_recv_user_data = NULL; /* no default */ ops.xp_free_user_data = NULL; /* no default */ } xprt->xp_ops = &ops; mutex_unlock(&ops_lock); } <file_sep>/* * Copyright (c) 2009, Sun Microsystems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - Neither the name of Sun Microsystems, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* * Copyright (c) 1985 by Sun Microsystems, Inc. */ #include <config.h> #include <sys/types.h> #include <sys/socket.h> #include <assert.h> #include <netdb.h> #include <stdio.h> #include <string.h> #include <rpc/rpc.h> #include <rpc/pmap_clnt.h> int getrpcport(char *host, int prognum, int versnum, int proto) { struct sockaddr_in addr; struct hostent *hp; assert(host != NULL); hp = gethostbyname(host); if (!hp) return (0); memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_port = 0; if (hp->h_length > sizeof(addr)) hp->h_length = sizeof(addr); memcpy(&addr.sin_addr.s_addr, hp->h_addr, (size_t) hp->h_length); /* Inconsistent interfaces need casts! :-( */ return (pmap_getport (&addr, (u_long) prognum, (u_long) versnum, (u_int) proto)); } <file_sep>/* * Copyright (c) 2012-2014 CEA * <NAME> <<EMAIL>> * contributeur : <NAME> <<EMAIL>> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - Neither the name of Sun Microsystems, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* * Implements connection server side RPC/RDMA. */ #include <config.h> #include <sys/cdefs.h> #include <pthread.h> #include <reentrant.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/param.h> #include <sys/poll.h> #if defined(TIRPC_EPOLL) #include <sys/epoll.h> /* before rpc.h */ #endif #include <rpc/rpc.h> #include <errno.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <netconfig.h> #include <err.h> #include "rpc_com.h" #include "misc/city.h" #include "rpc/xdr_inrec.h" #include "svc_internal.h" #include "clnt_internal.h" #include "svc_xprt.h" #include "rpc_rdma.h" #include <rpc/svc_rqst.h> #include <rpc/svc_auth.h> /* * kept in xprt->xp_p2 (sm_data(xprt)) */ struct svc_rdma_xdr { XDR sm_xdrs; /* XDR handle *MUST* be top */ char sm_verfbody[MAX_AUTH_BYTES]; /* verifier body */ struct msghdr sm_msghdr; /* msghdr received from clnt */ unsigned char sm_cmsg[64]; /* cmsghdr received from clnt */ size_t sm_iosz; /* size of send.recv buffer */ }; #define sm_data(xprt) ((struct svc_rdma_xdr *)(xprt->xp_p2)) extern struct svc_params __svc_params[1]; static void svc_rdma_ops(SVCXPRT *); /* * svc_rdma_ncreate: waits for connection request and returns transport */ SVCXPRT * svc_rdma_ncreate(void *arg, const u_int sendsize, const u_int recvsize, const u_int flags) { struct svc_rdma_xdr *sm; struct sockaddr_storage *ss; RDMAXPRT *l_xprt = arg; RDMAXPRT *xprt = rpc_rdma_accept_wait(l_xprt, l_xprt->xa->timeout); if (!xprt) { __warnx(TIRPC_DEBUG_FLAG_ERROR, "%s:%u ERROR (return)", __func__, __LINE__); return (NULL); } sm = mem_zalloc(sizeof (*sm)); sm->sm_xdrs.x_lib[1] = xprt; xprt->xprt.xp_p2 = sm; xprt->xprt.xp_flags = flags; /* fixme: put something here, but make it not work on fd operations. */ xprt->xprt.xp_fd = -1; ss = (struct sockaddr_storage *)rdma_get_local_addr(xprt->cm_id); __rpc_set_address(&xprt->xprt.xp_local, ss, 0); ss = (struct sockaddr_storage *)rdma_get_peer_addr(xprt->cm_id); __rpc_set_address(&xprt->xprt.xp_remote, ss, 0); svc_rdma_ops(&xprt->xprt); if (xdr_rdma_create(&sm->sm_xdrs, xprt, sendsize, recvsize, flags)) { goto freedata; } if (rpc_rdma_accept_finalize(xprt)) { goto freedata; } return (&xprt->xprt); freedata: mem_free(sm, sizeof (*sm)); xprt->xprt.xp_p2 = NULL; xprt_unregister(&xprt->xprt); return (NULL); } /*ARGSUSED*/ static enum xprt_stat svc_rdma_stat(SVCXPRT *xprt) { /* note: RDMAXPRT is this xprt! */ switch(((RDMAXPRT *)xprt)->state) { case RDMAXS_LISTENING: case RDMAXS_CONNECTED: return (XPRT_IDLE); /* any point in adding a break? */ default: /* suppose anything else means a problem */ return (XPRT_DIED); } } static bool svc_rdma_recv(SVCXPRT *xprt, struct svc_req *req) { struct rpc_rdma_cbc *cbc = req->rq_context; XDR *xdrs = cbc->holdq.xdrs; __warnx(TIRPC_DEBUG_FLAG_SVC_RDMA, "%s() xprt %p cbc %p incoming xdr %p\n", __func__, xprt, cbc, xdrs); req->rq_msg = alloc_rpc_msg(); if (!xdr_rdma_svc_recv(cbc, 0)){ __warnx(TIRPC_DEBUG_FLAG_SVC_RDMA, "%s: xdr_rdma_svc_recv failed", __func__); return (FALSE); } xdrs->x_op = XDR_DECODE; /* No need, already positioned to beginning ... XDR_SETPOS(xdrs, 0); */ if (!xdr_dplx_decode(xdrs, req->rq_msg)) { __warnx(TIRPC_DEBUG_FLAG_SVC_RDMA, "%s: xdr_dplx_decode failed", __func__); return (FALSE); } req->rq_xprt = xprt; req->rq_prog = req->rq_msg->rm_call.cb_prog; req->rq_vers = req->rq_msg->rm_call.cb_vers; req->rq_proc = req->rq_msg->rm_call.cb_proc; req->rq_xid = req->rq_msg->rm_xid; req->rq_clntcred = req->rq_msg->rq_cred_body; /* the checksum */ req->rq_cksum = 0; return (TRUE); } static bool svc_rdma_reply(SVCXPRT *xprt, struct svc_req *req, struct rpc_msg *msg) { struct rpc_rdma_cbc *cbc = req->rq_context; XDR *xdrs = cbc->holdq.xdrs; xdrproc_t proc; void *where; bool has_args; __warnx(TIRPC_DEBUG_FLAG_SVC_RDMA, "%s() xprt %p cbc %p outgoing xdr %p\n", __func__, xprt, cbc, xdrs); if (msg->rm_reply.rp_stat == MSG_ACCEPTED && msg->rm_reply.rp_acpt.ar_stat == SUCCESS) { has_args = TRUE; proc = msg->acpted_rply.ar_results.proc; where = msg->acpted_rply.ar_results.where; msg->acpted_rply.ar_results.proc = (xdrproc_t)xdr_void; msg->acpted_rply.ar_results.where = NULL; } else { has_args = FALSE; proc = NULL; where = NULL; } if (!xdr_rdma_svc_reply(cbc, 0)){ __warnx(TIRPC_DEBUG_FLAG_SVC_RDMA, "%s: xdr_rdma_svc_reply failed (will set dead)", __func__); return (FALSE); } xdrs->x_op = XDR_ENCODE; if (!xdr_reply_encode(xdrs, msg)) { __warnx(TIRPC_DEBUG_FLAG_SVC_RDMA, "%s: xdr_reply_encode failed (will set dead)", __func__); return (FALSE); } xdr_tail_update(xdrs); if (has_args && req->rq_auth && !SVCAUTH_WRAP(req->rq_auth, req, xdrs, proc, where)) { __warnx(TIRPC_DEBUG_FLAG_SVC_RDMA, "%s: SVCAUTH_WRAP failed (will set dead)", __func__); return (FALSE); } xdr_tail_update(xdrs); return xdr_rdma_svc_flushout(cbc); } static bool svc_rdma_freeargs(SVCXPRT *xprt, struct svc_req *req, xdrproc_t xdr_args, void *args_ptr) { struct rpc_rdma_cbc *cbc = req->rq_context; XDR *xdrs = cbc->holdq.xdrs; xdrs->x_op = XDR_FREE; return (*xdr_args)(xdrs, args_ptr); } static bool svc_rdma_getargs(SVCXPRT *xprt, struct svc_req *req, xdrproc_t xdr_args, void *args_ptr, void *u_data) { struct rpc_rdma_cbc *cbc = req->rq_context; XDR *xdrs = cbc->holdq.xdrs; bool rslt; /* threads u_data for advanced decoders*/ xdrs->x_public = u_data; rslt = SVCAUTH_UNWRAP(req->rq_auth, req, xdrs, xdr_args, args_ptr); if (!rslt) svc_rdma_freeargs(xprt, req, xdr_args, args_ptr); return (rslt); } static void svc_rdma_destroy(SVCXPRT *xprt, u_int flags, const char *tag, const int line) { struct svc_rdma_xdr *sm = sm_data(xprt); __warnx(TIRPC_DEBUG_FLAG_REFCNT, "%s() %p xp_refs %" PRId32 " should actually destroy things @ %s:%d", __func__, xprt, xprt->xp_refs, tag, line); xdr_rdma_destroy(&(sm->sm_xdrs)); mem_free(sm, sizeof (*sm)); if (xprt->xp_ops->xp_free_user_data) { /* call free hook */ xprt->xp_ops->xp_free_user_data(xprt); } rpc_rdma_destroy(xprt); } extern mutex_t ops_lock; static void svc_rdma_lock(SVCXPRT *xprt, uint32_t flags, const char *file, int line) { /* pretend we lock for now */ } static void svc_rdma_unlock(SVCXPRT *xprt, uint32_t flags, const char *file, int line) { } static bool /*ARGSUSED*/ svc_rdma_control(SVCXPRT *xprt, const u_int rq, void *in) { switch (rq) { case SVCGET_XP_FLAGS: *(u_int *)in = xprt->xp_flags; break; case SVCSET_XP_FLAGS: xprt->xp_flags = *(u_int *)in; break; case SVCGET_XP_RECV: mutex_lock(&ops_lock); *(xp_recv_t *)in = xprt->xp_ops->xp_recv; mutex_unlock(&ops_lock); break; case SVCSET_XP_RECV: mutex_lock(&ops_lock); xprt->xp_ops->xp_recv = *(xp_recv_t)in; mutex_unlock(&ops_lock); break; case SVCGET_XP_GETREQ: mutex_lock(&ops_lock); *(xp_getreq_t *)in = xprt->xp_ops->xp_getreq; mutex_unlock(&ops_lock); break; case SVCSET_XP_GETREQ: mutex_lock(&ops_lock); xprt->xp_ops->xp_getreq = *(xp_getreq_t)in; mutex_unlock(&ops_lock); break; case SVCGET_XP_DISPATCH: mutex_lock(&ops_lock); *(xp_dispatch_t *)in = xprt->xp_ops->xp_dispatch; mutex_unlock(&ops_lock); break; case SVCSET_XP_DISPATCH: mutex_lock(&ops_lock); xprt->xp_ops->xp_dispatch = *(xp_dispatch_t)in; mutex_unlock(&ops_lock); break; case SVCGET_XP_FREE_USER_DATA: mutex_lock(&ops_lock); *(xp_free_user_data_t *)in = xprt->xp_ops->xp_free_user_data; mutex_unlock(&ops_lock); break; case SVCSET_XP_FREE_USER_DATA: mutex_lock(&ops_lock); xprt->xp_ops->xp_free_user_data = *(xp_free_user_data_t)in; mutex_unlock(&ops_lock); break; default: return (FALSE); } return (TRUE); } static void svc_rdma_ops(SVCXPRT *xprt) { static struct xp_ops ops; /* VARIABLES PROTECTED BY ops_lock: ops, xp_type */ mutex_lock(&ops_lock); /* Fill in type of service */ xprt->xp_type = XPRT_RDMA; if (ops.xp_recv == NULL) { ops.xp_recv = svc_rdma_recv; ops.xp_stat = svc_rdma_stat; ops.xp_getargs = svc_rdma_getargs; ops.xp_reply = svc_rdma_reply; ops.xp_freeargs = svc_rdma_freeargs; ops.xp_destroy = svc_rdma_destroy, ops.xp_control = svc_rdma_control; ops.xp_lock = svc_rdma_lock; ops.xp_unlock = svc_rdma_unlock; ops.xp_getreq = svc_getreq_default; ops.xp_dispatch = svc_dispatch_default; ops.xp_recv_user_data = NULL; /* no default */ ops.xp_free_user_data = NULL; /* no default */ } xprt->xp_ops = &ops; mutex_unlock(&ops_lock); } <file_sep>/* * Copyright (c) 2010, Oracle America, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - Neither the name of the "Oracle America, Inc." nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <config.h> #include <pthread.h> #include <reentrant.h> #include <sys/types.h> #include <sys/fcntl.h> #include <fcntl.h> #include <sys/socket.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <stdio.h> #include <errno.h> #include <netdb.h> #include <err.h> #include <rpc/rpc.h> #include <rpc/nettype.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include "rpc_com.h" int __rpc_raise_fd(int); #ifndef NETIDLEN #define NETIDLEN 32 #endif /* * Generic client creation with version checking the value of * vers_out is set to the highest server supported value * vers_low <= vers_out <= vers_high AND an error results * if this can not be done. * * It calls clnt_create_vers_timed() with a NULL value for the timeout * pointer, which indicates that the default timeout should be used. */ CLIENT * clnt_ncreate_vers(const char *hostname, rpcprog_t prog, rpcvers_t *vers_out, rpcvers_t vers_low, rpcvers_t vers_high, const char *nettype) { return (clnt_ncreate_vers_timed (hostname, prog, vers_out, vers_low, vers_high, nettype, NULL)); } /* * This the routine has the same definition as clnt_create_vers(), * except it takes an additional timeout parameter - a pointer to * a timeval structure. A NULL value for the pointer indicates * that the default timeout value should be used. */ CLIENT * clnt_ncreate_vers_timed(const char *hostname, rpcprog_t prog, rpcvers_t *vers_out, rpcvers_t vers_low, rpcvers_t vers_high, const char *nettype, const struct timeval *tp) { CLIENT *clnt; struct timeval to; enum clnt_stat rpc_stat; struct rpc_err rpcerr; AUTH *auth = authnone_ncreate(); /* idempotent */ clnt = clnt_ncreate_timed(hostname, prog, vers_high, nettype, tp); if (clnt == NULL) return (NULL); to.tv_sec = 10; to.tv_usec = 0; rpc_stat = clnt_call(clnt, auth, NULLPROC, (xdrproc_t) xdr_void, (char *)NULL, (xdrproc_t) xdr_void, (char *)NULL, to); if (rpc_stat == RPC_SUCCESS) { *vers_out = vers_high; return (clnt); } while (rpc_stat == RPC_PROGVERSMISMATCH && vers_high > vers_low) { unsigned int minvers, maxvers; clnt_geterr(clnt, &rpcerr); minvers = rpcerr.re_vers.low; maxvers = rpcerr.re_vers.high; if (maxvers < vers_high) vers_high = maxvers; else vers_high--; if (minvers > vers_low) vers_low = minvers; if (vers_low > vers_high) goto error; CLNT_CONTROL(clnt, CLSET_VERS, (char *)&vers_high); rpc_stat = clnt_call(clnt, auth, NULLPROC, (xdrproc_t) xdr_void, (char *)NULL, (xdrproc_t) xdr_void, (char *)NULL, to); if (rpc_stat == RPC_SUCCESS) { *vers_out = vers_high; return (clnt); } } clnt_geterr(clnt, &rpcerr); error: rpc_createerr.cf_stat = rpc_stat; rpc_createerr.cf_error = rpcerr; clnt_destroy(clnt); return (NULL); } /* * Top level client creation routine. * Generic client creation: takes (servers name, program-number, nettype) and * returns client handle. Default options are set, which the user can * change using the rpc equivalent of _ioctl()'s. * * It tries for all the netids in that particular class of netid until * it succeeds. * XXX The error message in the case of failure will be the one * pertaining to the last create error. * * It calls clnt_ncreate_timed() with the default timeout. */ CLIENT * clnt_ncreate(const char *hostname, rpcprog_t prog, rpcvers_t vers, const char *nettype) { return (clnt_ncreate_timed(hostname, prog, vers, nettype, NULL)); } /* * This the routine has the same definition as clnt_create(), * except it takes an additional timeout parameter - a pointer to * a timeval structure. A NULL value for the pointer indicates * that the default timeout value should be used. * * This function calls clnt_tp_create_timed(). */ CLIENT * clnt_ncreate_timed(const char *hostname, rpcprog_t prog, rpcvers_t vers, const char *netclass, const struct timeval *tp) { struct netconfig *nconf; CLIENT *clnt = NULL; void *handle; enum clnt_stat save_cf_stat = RPC_SUCCESS; struct rpc_err save_cf_error; char nettype_array[NETIDLEN]; char *nettype = &nettype_array[0]; if (netclass == NULL) nettype = NULL; else { size_t len = strlen(netclass); if (len >= sizeof(nettype_array)) { rpc_createerr.cf_stat = RPC_UNKNOWNPROTO; return (NULL); } strcpy(nettype, netclass); } handle = __rpc_setconf((char *)nettype); if (handle == NULL) { rpc_createerr.cf_stat = RPC_UNKNOWNPROTO; return (NULL); } rpc_createerr.cf_stat = RPC_SUCCESS; while (clnt == NULL) { nconf = __rpc_getconf(handle); if (nconf == NULL) { if (rpc_createerr.cf_stat == RPC_SUCCESS) rpc_createerr.cf_stat = RPC_UNKNOWNPROTO; break; } #ifdef CLNT_DEBUG __warnx(TIRPC_DEBUG_FLAG_CLNT_GEN, "%s: trying netid %s", __func__, nconf->nc_netid); #endif clnt = clnt_tp_ncreate_timed(hostname, prog, vers, nconf, tp); if (clnt) break; else { /* * Since we didn't get a name-to-address * translation failure here, we remember * this particular error. The object of * this is to enable us to return to the * caller a more-specific error than the * unhelpful ``Name to address translation * failed'' which might well occur if we * merely returned the last error (because * the local loopbacks are typically the * last ones in /etc/netconfig and the most * likely to be unable to translate a host * name). We also check for a more * meaningful error than ``unknown host * name'' for the same reasons. */ if (rpc_createerr.cf_stat != RPC_N2AXLATEFAILURE && rpc_createerr.cf_stat != RPC_UNKNOWNHOST) { save_cf_stat = rpc_createerr.cf_stat; save_cf_error = rpc_createerr.cf_error; } } } /* * Attempt to return an error more specific than ``Name to address * translation failed'' or ``unknown host name'' */ if ((rpc_createerr.cf_stat == RPC_N2AXLATEFAILURE || rpc_createerr.cf_stat == RPC_UNKNOWNHOST) && (save_cf_stat != RPC_SUCCESS)) { rpc_createerr.cf_stat = save_cf_stat; rpc_createerr.cf_error = save_cf_error; } __rpc_endconf(handle); return (clnt); } /* * Generic client creation: takes (servers name, program-number, netconf) and * returns client handle. Default options are set, which the user can * change using the rpc equivalent of _ioctl()'s : clnt_control() * It finds out the server address from rpcbind and calls clnt_tli_create(). * * It calls clnt_tp_create_timed() with the default timeout. */ CLIENT * clnt_tp_ncreate(const char *hostname, rpcprog_t prog, rpcvers_t vers, const struct netconfig *nconf) { return (clnt_tp_ncreate_timed(hostname, prog, vers, nconf, NULL)); } /* * This has the same definition as clnt_tp_ncreate(), except it * takes an additional parameter - a pointer to a timeval structure. * A NULL value for the timeout pointer indicates that the default * value for the timeout should be used. */ CLIENT * clnt_tp_ncreate_timed(const char *hostname, rpcprog_t prog, rpcvers_t vers, const struct netconfig *nconf, const struct timeval *tp) { struct netbuf *svcaddr; /* servers address */ CLIENT *cl = NULL; /* client handle */ if (nconf == NULL) { rpc_createerr.cf_stat = RPC_UNKNOWNPROTO; return (NULL); } /* * Get the address of the server */ svcaddr = __rpcb_findaddr_timed(prog, vers, (struct netconfig *)nconf, (char *)hostname, &cl, (struct timeval *)tp); if (svcaddr == NULL) { /* appropriate error number is set by rpcbind libraries */ return (NULL); } if (cl == NULL) { /* __rpc_findaddr_timed failed? */ cl = clnt_tli_ncreate(RPC_ANYFD, nconf, svcaddr, prog, vers, 0, 0); } else { /* Reuse the CLIENT handle and change the appropriate fields */ if (CLNT_CONTROL(cl, CLSET_SVC_ADDR, (void *)svcaddr) == true) { if (cl->cl_netid == NULL) cl->cl_netid = mem_strdup(nconf->nc_netid); if (cl->cl_tp == NULL) cl->cl_tp = mem_strdup(nconf->nc_device); (void)CLNT_CONTROL(cl, CLSET_PROG, (void *)&prog); (void)CLNT_CONTROL(cl, CLSET_VERS, (void *)&vers); } else { CLNT_DESTROY(cl); cl = clnt_tli_ncreate(RPC_ANYFD, nconf, svcaddr, prog, vers, 0, 0); } } mem_free(svcaddr->buf, sizeof(*svcaddr->buf)); mem_free(svcaddr, sizeof(*svcaddr)); return (cl); } /* * Generic client creation: returns client handle. * Default options are set, which the user can * change using the rpc equivalent of _ioctl()'s : clnt_control(). * If fd is RPC_ANYFD, it will be opened using nconf. * It will be bound if not so. * If sizes are 0; appropriate defaults will be chosen. */ CLIENT * clnt_tli_ncreate(int fd, const struct netconfig *nconf, struct netbuf *svcaddr, rpcprog_t prog, rpcvers_t vers, u_int sendsz, u_int recvsz) { CLIENT *cl; /* client handle */ bool madefd = false; /* whether fd opened here */ long servtype; int one = 1; struct __rpc_sockinfo si; extern int __rpc_minfd; if (fd == RPC_ANYFD) { if (nconf == NULL) { rpc_createerr.cf_stat = RPC_UNKNOWNPROTO; return (NULL); } fd = __rpc_nconf2fd(nconf); if (fd == -1) goto err; if (fd < __rpc_minfd) fd = __rpc_raise_fd(fd); madefd = true; servtype = nconf->nc_semantics; if (!__rpc_fd2sockinfo(fd, &si)) goto err; bindresvport(fd, NULL); } else { if (!__rpc_fd2sockinfo(fd, &si)) goto err; servtype = __rpc_socktype2seman(si.si_socktype); if (servtype == -1) { rpc_createerr.cf_stat = RPC_UNKNOWNPROTO; return (NULL); } } if (si.si_af != ((struct sockaddr *)svcaddr->buf)->sa_family) { rpc_createerr.cf_stat = RPC_UNKNOWNHOST; /* XXX */ goto err1; } switch (servtype) { case NC_TPI_COTS: cl = clnt_vc_ncreate(fd, svcaddr, prog, vers, sendsz, recvsz); break; case NC_TPI_COTS_ORD: if (nconf && ((strcmp(nconf->nc_protofmly, "inet") == 0) || (strcmp(nconf->nc_protofmly, "inet6") == 0))) { (void) setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one)); } cl = clnt_vc_ncreate(fd, svcaddr, prog, vers, sendsz, recvsz); break; case NC_TPI_CLTS: cl = clnt_dg_ncreate(fd, svcaddr, prog, vers, sendsz, recvsz); break; default: goto err; } if (cl == NULL) goto err1; /* borrow errors from clnt_dg/vc ncreates */ if (nconf) { cl->cl_netid = mem_strdup(nconf->nc_netid); cl->cl_tp = mem_strdup(nconf->nc_device); } else { cl->cl_netid = ""; cl->cl_tp = ""; } if (madefd) { (void)CLNT_CONTROL(cl, CLSET_FD_CLOSE, NULL); /* (void) CLNT_CONTROL(cl, CLSET_POP_TIMOD, NULL); */ }; return (cl); err: rpc_createerr.cf_stat = RPC_SYSTEMERROR; rpc_createerr.cf_error.re_errno = errno; err1: if (madefd) (void)close(fd); return (NULL); } /* * To avoid conflicts with the "magic" file descriptors (0, 1, and 2), * we try to not use them. The __rpc_raise_fd() routine will dup * a descriptor to a higher value. If we fail to do it, we continue * to use the old one (and hope for the best). */ int __rpc_minfd = 3; int __rpc_raise_fd(int fd) { int nfd; if (fd >= __rpc_minfd) return (fd); nfd = fcntl(fd, F_DUPFD, __rpc_minfd); if (nfd == -1) return (fd); if (fsync(nfd) == -1) { close(nfd); return (fd); } if (close(fd) == -1) { /* this is okay, we will log an error, then use the new fd */ __warnx(TIRPC_DEBUG_FLAG_CLNT_GEN, "could not close() fd %d; mem & fd leak", fd); } return (nfd); } <file_sep>/* * Copyright (c) 2012 Linux Box Corporation. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR `AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <config.h> #include <sys/types.h> #include <sys/poll.h> #include <sys/uio.h> #include <stdint.h> #include <assert.h> #include <err.h> #include <errno.h> #include <rpc/types.h> #include <unistd.h> #include <signal.h> #include <misc/timespec.h> #include <rpc/types.h> #include <misc/portable.h> #include <rpc/xdr.h> #include <rpc/rpc.h> #include <rpc/svc.h> #include <rpc/clnt.h> #include <rpc/auth.h> #include <rpc/svc_auth.h> #include <rpc/svc_rqst.h> #include "rpc_com.h" #include <misc/rbtree_x.h> #include "clnt_internal.h" #include "svc_internal.h" #include "rpc_dplx_internal.h" #include "rpc_ctx.h" static inline int clnt_read_vc(XDR *xdrs, void *ctp, void *buf, int len) { struct x_vc_data *xd = (struct x_vc_data *)ctp; struct ct_data *ct = &xd->cx.data; rpc_ctx_t *ctx = (rpc_ctx_t *) xdrs->x_lib[1]; struct pollfd fd; int milliseconds = (int)((ct->ct_wait.tv_sec * 1000) + (ct->ct_wait.tv_usec / 1000)); if (len == 0) return (0); fd.fd = xd->cx.data.ct_fd; fd.events = POLLIN; for (;;) { switch (poll(&fd, 1, milliseconds)) { case 0: ctx->error.re_status = RPC_TIMEDOUT; return (-1); case -1: if (errno == EINTR) continue; ctx->error.re_status = RPC_CANTRECV; ctx->error.re_errno = errno; return (-1); } break; } len = read(xd->cx.data.ct_fd, buf, (size_t) len); switch (len) { case 0: /* premature eof */ ctx->error.re_errno = ECONNRESET; ctx->error.re_status = RPC_CANTRECV; len = -1; /* it's really an error */ break; case -1: ctx->error.re_errno = errno; ctx->error.re_status = RPC_CANTRECV; break; } return (len); } static inline int clnt_write_vc(XDR *xdrs, void *ctp, void *buf, int len) { struct x_vc_data *xd = (struct x_vc_data *)ctp; rpc_ctx_t *ctx = (rpc_ctx_t *) xdrs->x_lib[1]; int i = 0, cnt; for (cnt = len; cnt > 0; cnt -= i, buf += i) { i = write(xd->cx.data.ct_fd, buf, (size_t) cnt); if (i == -1) { ctx->error.re_errno = errno; ctx->error.re_status = RPC_CANTSEND; return (-1); } } return (len); } static inline void cfconn_set_dead(SVCXPRT *xprt, struct x_vc_data *xd) { mutex_lock(&xprt->xp_lock); xd->sx.strm_stat = XPRT_DIED; mutex_unlock(&xprt->xp_lock); } /* * reads data from the tcp or udp connection. * any error is fatal and the connection is closed. * (And a read of zero bytes is a half closed stream => error.) * All read operations timeout after 35 seconds. A timeout is * fatal for the connection. */ #define EARLY_DEATH_DEBUG 1 static inline int svc_read_vc(XDR *xdrs, void *ctp, void *buf, int len) { SVCXPRT *xprt; int milliseconds = 35 * 1000; /* XXX configurable? */ struct pollfd pollfd; struct x_vc_data *xd; xd = (struct x_vc_data *)ctp; xprt = xd->rec->hdl.xprt; if (xd->shared.nonblock) { len = read(xprt->xp_fd, buf, (size_t) len); if (len < 0) { if (errno == EAGAIN) len = 0; else goto fatal_err; } if (len != 0) (void)clock_gettime(CLOCK_MONOTONIC_FAST, &xd->sx.last_recv); return len; } do { pollfd.fd = xprt->xp_fd; pollfd.events = POLLIN; pollfd.revents = 0; switch (poll(&pollfd, 1, milliseconds)) { case -1: if (errno == EINTR) continue; /*FALLTHROUGH*/ case 0: __warnx(TIRPC_DEBUG_FLAG_SVC_VC, "%s: poll returns 0 (will set dead)", __func__); goto fatal_err; default: break; } } while ((pollfd.revents & POLLIN) == 0); len = read(xprt->xp_fd, buf, (size_t) len); if (len > 0) { (void) clock_gettime(CLOCK_MONOTONIC_FAST, &xd->sx.last_recv); return (len); } fatal_err: cfconn_set_dead(xprt, xd); return (-1); } /* * writes data to the tcp connection. * Any error is fatal and the connection is closed. */ static inline int svc_write_vc(XDR *xdrs, void *ctp, void *buf, int len) { SVCXPRT *xprt; struct x_vc_data *xd; struct timespec ts0, ts1; int i, cnt; xd = (struct x_vc_data *)ctp; xprt = xd->rec->hdl.xprt; if (xd->shared.nonblock) (void)clock_gettime(CLOCK_MONOTONIC_FAST, &ts0); for (cnt = len; cnt > 0; cnt -= i, buf += i) { i = write(xprt->xp_fd, buf, (size_t) cnt); if (i < 0) { if (errno != EAGAIN || !xd->shared.nonblock) { __warnx(TIRPC_DEBUG_FLAG_SVC_VC, "%s: short write !EAGAIN (will set dead)", __func__); cfconn_set_dead(xprt, xd); return (-1); } if (xd->shared.nonblock && i != cnt) { /* * For non-blocking connections, do not * take more than 2 seconds writing the * data out. * * XXX 2 is an arbitrary amount. */ (void)clock_gettime(CLOCK_MONOTONIC_FAST, &ts1); if (ts1.tv_sec - ts0.tv_sec >= 2) { __warnx(TIRPC_DEBUG_FLAG_SVC_VC, "%s: short write !EAGAIN (will set dead)", __func__); cfconn_set_dead(xprt, xd); return (-1); } } } } return (len); } /* generic read and write callbacks */ int generic_read_vc(XDR *xdrs, void *ctp, void *buf, int len) { switch ((enum rpc_duplex_callpath)xdrs->x_lib[0]) { case RPC_DPLX_CLNT: return (clnt_read_vc(xdrs, ctp, buf, len)); break; case RPC_DPLX_SVC: return (svc_read_vc(xdrs, ctp, buf, len)); break; default: /* better not */ abort(); } } int generic_write_vc(XDR *xdrs, void *ctp, void *buf, int len) { switch ((enum rpc_duplex_callpath)xdrs->x_lib[0]) { case RPC_DPLX_CLNT: return (clnt_write_vc(xdrs, ctp, buf, len)); break; case RPC_DPLX_SVC: return (svc_write_vc(xdrs, ctp, buf, len)); break; default: /* better not */ abort(); } } void vc_shared_destroy(struct x_vc_data *xd) { struct rpc_dplx_rec *rec = xd->rec; struct ct_data *ct = &xd->cx.data; SVCXPRT *xprt; bool closed = false; /* RECLOCKED */ if (ct->ct_closeit && ct->ct_fd != RPC_ANYFD) { (void)close(ct->ct_fd); closed = true; } if (ct->ct_addr.buf) mem_free(ct->ct_addr.buf, 0); /* XXX */ /* svc_vc */ xprt = rec->hdl.xprt; if (xprt) { xprt->xp_p1 = NULL; xd->refcnt--; } rec->hdl.xd = NULL; xd->refcnt--; rpc_dplx_unref(rec, RPC_DPLX_FLAG_LOCKED | RPC_DPLX_FLAG_UNLOCK); /* free xd itself */ if (xd->refcnt == 0) { /* destroy shared XDR record streams (once) */ XDR_DESTROY(&xd->shared.xdrs_in); XDR_DESTROY(&xd->shared.xdrs_out); mem_free(xd, sizeof(struct x_vc_data)); } else __warnx(TIRPC_DEBUG_FLAG_REFCNT, "%s: xd_refcnt %u on destroyed %p omit " , __func__, xd->refcnt, xd); } <file_sep>/* * Copyright (c) 2012-2014 CEA * <NAME> <<EMAIL>> * contributeur : <NAME> <<EMAIL>> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - Neither the name of Sun Microsystems, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* * Implements an msk connection client side RPC. */ #include <config.h> #include <pthread.h> #include <reentrant.h> #include <sys/types.h> #include <sys/socket.h> #include <stdint.h> #include <sys/poll.h> #include <sys/time.h> #include <sys/ioctl.h> #include <rpc/clnt.h> #include <arpa/inet.h> #include <rpc/rpc.h> #include <rpc/xdr.h> #include <errno.h> #include <stdlib.h> #include <string.h> #include <signal.h> #include <unistd.h> #include <err.h> #include "rpc_com.h" #ifdef IP_RECVERR #include <asm/types.h> #include <linux/errqueue.h> #include <sys/uio.h> #endif #include "clnt_internal.h" #include "rpc_rdma.h" #include "rpc_dplx_internal.h" #define MAX_DEFAULT_FDS 20000 static struct clnt_ops *clnt_rdma_ops(void); /* * Make sure that the time is not garbage. -1 value is allowed. */ static bool time_not_ok(struct timeval *t) { return (t->tv_sec < -1 || t->tv_sec > 100000000 || t->tv_usec < -1 || t->tv_usec > 1000000); } /* * client mooshika create */ CLIENT * clnt_rdma_create(RDMAXPRT *xprt, /* init but NOT connect()ed descriptor */ rpcprog_t program, /* program number */ rpcvers_t version, const u_int flags) { CLIENT *cl = NULL; /* client handle */ struct cx_data *cx = NULL; /* private data */ struct cm_data *cm = NULL; struct timeval now; if (!xprt || xprt->state != RDMAXS_INITIAL) { rpc_createerr.cf_stat = RPC_UNKNOWNADDR; /* FIXME, add a warnx? */ rpc_createerr.cf_error.re_errno = 0; return (NULL); } /* * Find the receive and the send size */ // u_int sendsz = 8*1024; // u_int recvsz = 4*8*1024; u_int sendsz = 1024; u_int recvsz = 1024; cl = mem_alloc(sizeof (CLIENT)); /* * Should be multiple of 4 for XDR. */ cx = alloc_cx_data(CX_MSK_DATA, sendsz, recvsz); cm = CM_DATA(cx); /* Other values can also be set through clnt_control() */ cm->cm_xdrs.x_lib[1] = (void *)xprt; cm->cm_wait.tv_sec = 15; /* heuristically chosen */ cm->cm_wait.tv_usec = 0; (void) gettimeofday(&now, NULL); // cm->call_msg.rm_xid = __RPC_GETXID(&now); cm->call_msg.rm_xid = 1; cm->call_msg.rm_call.cb_prog = program; cm->call_msg.rm_call.cb_vers = version; rpc_rdma_connect(xprt); xdr_rdma_create(&cm->cm_xdrs, xprt, sendsz, recvsz, flags); rpc_rdma_connect_finalize(xprt); /* * By default, closeit is always FALSE. It is users responsibility * to do a close on it, else the user may use clnt_control * to let clnt_destroy do it for him/her. */ cm->cm_closeit = FALSE; cl->cl_ops = clnt_rdma_ops(); // cl->cl_private = (caddr_t)(void *) cx; cl->cl_p1 = (caddr_t)(void *) cx; cl->cl_p2 = NULL; // cl->cl_p2 = rec; // cl->cl_auth = authnone_create(); cl->cl_tp = NULL; cl->cl_netid = NULL; return (cl); } static enum clnt_stat clnt_rdma_call(CLIENT *cl, /* client handle */ AUTH *auth, rpcproc_t proc, /* procedure number */ xdrproc_t xargs, /* xdr routine for args */ void *argsp, /* pointer to args */ xdrproc_t xresults, /* xdr routine for results */ void *resultsp, /* pointer to results */ struct timeval utimeout /* seconds to wait before giving up */) { struct cm_data *cm = CM_DATA((struct cx_data *) cl->cl_p1); XDR *xdrs; struct rpc_msg reply_msg; bool ok; #if 0 struct timeval timeout; int total_time; #endif // sigset_t mask; socklen_t __attribute__((unused)) inlen, salen; int nrefreshes = 2; /* number of times to refresh cred */ // thr_sigsetmask(SIG_SETMASK, (sigset_t *) 0, &mask); /* XXX */ // vc_fd_lock_c(cl, &mask); //What does that do? #if 0 if (cm->cm_total.tv_usec == -1) { timeout = utimeout; /* use supplied timeout */ } else { timeout = cm->cm_total; /* use default timeout */ } total_time = timeout.tv_sec * 1000 + timeout.tv_usec / 1000; #endif /* Clean up in case the last call ended in a longjmp(3) call. */ call_again: xdrs = &(cm->cm_xdrs); if (0) //FIXME check for async goto get_reply; if (! xdr_rdma_clnt_call(&cm->cm_xdrs, cm->call_msg.rm_xid) || ! xdr_callhdr(&(cm->cm_xdrs), &cm->call_msg)) { rpc_createerr.cf_stat = RPC_CANTENCODEARGS; /* XXX */ rpc_createerr.cf_error.re_errno = 0; goto out; } if ((! XDR_PUTINT32(xdrs, (int32_t *)&proc)) || (! AUTH_MARSHALL(auth, xdrs)) || (! AUTH_WRAP(auth, xdrs, xargs, argsp))) { cm->cm_error.re_status = RPC_CANTENCODEARGS; goto out; } if (! xdr_rdma_clnt_flushout(&cm->cm_xdrs)) { cm->cm_error.re_errno = errno; cm->cm_error.re_status = RPC_CANTSEND; goto out; } get_reply: /* * sub-optimal code appears here because we have * some clock time to spare while the packets are in flight. * (We assume that this is actually only executed once.) */ reply_msg.acpted_rply.ar_verf = _null_auth; reply_msg.acpted_rply.ar_results.where = NULL; reply_msg.acpted_rply.ar_results.proc = (xdrproc_t)xdr_void; if (! xdr_rdma_clnt_reply(&cm->cm_xdrs, cm->call_msg.rm_xid)) { //FIXME add timeout cm->cm_error.re_status = RPC_TIMEDOUT; goto out; } /* * now decode and validate the response */ ok = xdr_replymsg(&cm->cm_xdrs, &reply_msg); if (ok) { if ((reply_msg.rm_reply.rp_stat == MSG_ACCEPTED) && (reply_msg.acpted_rply.ar_stat == SUCCESS)) cm->cm_error.re_status = RPC_SUCCESS; else _seterr_reply(&reply_msg, &(cm->cm_error)); if (cm->cm_error.re_status == RPC_SUCCESS) { if (! AUTH_VALIDATE(auth, &reply_msg.acpted_rply.ar_verf)) { cm->cm_error.re_status = RPC_AUTHERROR; cm->cm_error.re_why = AUTH_INVALIDRESP; } else if (! AUTH_UNWRAP(auth, &cm->cm_xdrs, xresults, resultsp)) { if (cm->cm_error.re_status == RPC_SUCCESS) cm->cm_error.re_status = RPC_CANTDECODERES; } if (reply_msg.acpted_rply.ar_verf.oa_base != NULL) { xdrs->x_op = XDR_FREE; (void) xdr_opaque_auth(xdrs, &(reply_msg.acpted_rply.ar_verf)); } } /* end successful completion */ /* * If unsuccesful AND error is an authentication error * then refresh credentials and try again, else break */ else if (cm->cm_error.re_status == RPC_AUTHERROR) /* maybe our credentials need to be refreshed ... */ if (nrefreshes > 0 && AUTH_REFRESH(auth, &reply_msg)) { nrefreshes--; goto call_again; } /* end of unsuccessful completion */ } /* end of valid reply message */ else { cm->cm_error.re_status = RPC_CANTDECODERES; } out: cm->call_msg.rm_xid++; // vc_fd_unlock_c(cl, &mask); return (cm->cm_error.re_status); } static void clnt_rdma_geterr(CLIENT *cl, struct rpc_err *errp) { struct cm_data *cm = CM_DATA((struct cx_data *) cl->cl_p1); *errp = cm->cm_error; } static bool clnt_rdma_freeres(CLIENT *cl, xdrproc_t xdr_res, void *res_ptr) { struct cm_data *cm = CM_DATA((struct cx_data *)cl->cl_p1); XDR *xdrs; sigset_t mask, newmask; bool dummy = 0; /* XXX guard against illegal invocation from libc (will fix) */ if (! xdr_res) goto out; xdrs = &(cm->cm_xdrs); /* Handle our own signal mask here, the signal section is * larger than the wait (not 100% clear why) */ /* barrier recv channel */ // rpc_dplx_rwc(clnt, rpc_flag_clear); sigfillset(&newmask); thr_sigsetmask(SIG_SETMASK, &newmask, &mask); xdrs->x_op = XDR_FREE; if (xdr_res) dummy = (*xdr_res)(xdrs, res_ptr); thr_sigsetmask(SIG_SETMASK, &mask, NULL); rpc_dplx_rsc(cl, RPC_DPLX_FLAG_NONE); out: return (dummy); } /*ARGSUSED*/ static void clnt_rdma_abort(CLIENT *h) { } static bool clnt_rdma_control(CLIENT *cl, u_int request, void *info) { struct cm_data *cm = CM_DATA((struct cx_data *) cl->cl_p1); sigset_t mask; bool result = TRUE; thr_sigsetmask(SIG_SETMASK, (sigset_t *) 0, &mask); /* XXX */ /* always take recv lock first if taking together */ rpc_dplx_rlc(cl); //receive lock clnt rpc_dplx_slc(cl); //send lock clnt switch (request) { case CLSET_FD_CLOSE: cm->cm_closeit = TRUE; result = TRUE; goto unlock; case CLSET_FD_NCLOSE: cm->cm_closeit = FALSE; result = TRUE; goto unlock; } /* for other requests which use info */ if (info == NULL) { result = FALSE; goto unlock; } switch (request) { case CLSET_TIMEOUT: if (time_not_ok((struct timeval *)info)) { result = FALSE; goto unlock; } cm->cm_total = *(struct timeval *)info; break; case CLGET_TIMEOUT: *(struct timeval *)info = cm->cm_total; break; case CLSET_RETRY_TIMEOUT: if (time_not_ok((struct timeval *)info)) { result = FALSE; goto unlock; } cm->cm_wait = *(struct timeval *)info; break; case CLGET_RETRY_TIMEOUT: *(struct timeval *)info = cm->cm_wait; break; case CLGET_FD: *(RDMAXPRT **)info = cm->cm_xdrs.x_lib[1]; break; case CLGET_XID: /* * use the knowledge that xid is the * first element in the call structure *. * This will get the xid of the PREVIOUS call */ *(u_int32_t *)info = cm->call_msg.rm_xid - 1; break; case CLSET_XID: /* This will set the xid of the NEXT call */ cm->call_msg.rm_xid = *(u_int32_t *)info; break; case CLGET_VERS: *(u_int32_t *)info = cm->call_msg.rm_call.cb_vers; break; case CLSET_VERS: cm->call_msg.rm_call.cb_vers = *(u_int32_t *)info; break; case CLGET_PROG: *(u_int32_t *)info = cm->call_msg.rm_call.cb_prog; break; case CLSET_PROG: cm->call_msg.rm_call.cb_prog = *(u_int32_t *)info; break; case CLSET_ASYNC: //FIXME cm->cm_async = *(int *)info; break; case CLSET_CONNECT: //FIXMEcm->cm_connect = *(int *)info; break; default: break; } unlock: rpc_dplx_ruc(cl); rpc_dplx_suc(cl); return (result); } static void clnt_rdma_destroy(CLIENT *cl) { // struct cx_data *cx = (struct cx_data *)cl->cl_private; //FIXME } static struct clnt_ops * clnt_rdma_ops(void) { static struct clnt_ops ops; extern mutex_t ops_lock; sigset_t mask; sigset_t newmask; /* VARIABLES PROTECTED BY ops_lock: ops */ sigfillset(&newmask); thr_sigsetmask(SIG_SETMASK, &newmask, &mask); mutex_lock(&ops_lock); if (ops.cl_call == NULL) { ops.cl_call = clnt_rdma_call; ops.cl_abort = clnt_rdma_abort; ops.cl_geterr = clnt_rdma_geterr; ops.cl_freeres = clnt_rdma_freeres; ops.cl_destroy = clnt_rdma_destroy; ops.cl_control = clnt_rdma_control; } mutex_unlock(&ops_lock); thr_sigsetmask(SIG_SETMASK, &mask, NULL); return (&ops); } <file_sep>/* * Copyright (c) 2013 Linux Box Corporation. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR `AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef THRDPOOL_H #define THRDPOOL_H #include <misc/queue.h> #include <misc/wait_queue.h> #define THRD_FLAG_NONE 0x0000 #define THRD_FLAG_SHUTDOWN 0x0001 #define THRD_FLAG_ACTIVE 0x0002 struct work { TAILQ_ENTRY(work) tailq; void (*func) (void*); void *arg; }; struct thrdpool; struct thrd { TAILQ_ENTRY(thrd) tailq; struct thrd_context { pthread_t id; struct wait_entry we; struct work *work; } ctx; struct thrdpool *pool; bool idle; }; struct thrdpool_params { int32_t thrd_max; int32_t thrd_min; }; struct thrdpool { char *name; uint32_t flags; struct thrdpool_params params; pthread_attr_t attr; struct wait_entry we; TAILQ_HEAD(idle_tailq, thrd) idle_q; TAILQ_HEAD(work_tailq, work) work_q; int32_t n_idle; int32_t n_threads; }; typedef void (*thrd_func_t) (void *); int thrdpool_init(struct thrdpool *, const char *, struct thrdpool_params *); int thrdpool_submit_work(struct thrdpool *, thrd_func_t, void *); int thrdpool_shutdown(struct thrdpool *); #endif /* THRDPOOL_H */ <file_sep> /* * Copyright (c) 2009, Sun Microsystems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - Neither the name of Sun Microsystems, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* * Copyright (c) 1986-1991 by Sun Microsystems Inc. */ #include <config.h> /* * svc_dg.c, Server side for connectionless RPC. * * Does some caching in the hopes of achieving execute-at-most-once semantics. */ #include <sys/cdefs.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/param.h> #include <sys/poll.h> #include <rpc/types.h> #include <misc/portable.h> #include <rpc/rpc.h> #include <rpc/svc_dg.h> #include <rpc/svc_auth.h> #include <errno.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <netconfig.h> #include <err.h> #include "rpc_com.h" #include "svc_internal.h" #include "clnt_internal.h" #include "svc_xprt.h" #include "rpc_dplx_internal.h" #include <rpc/svc_rqst.h> #include <misc/city.h> #include <rpc/rpc_cksum.h> extern struct svc_params __svc_params[1]; #define su_data(xprt) ((struct svc_dg_data *)(xprt->xp_p2)) /* XXX */ #define rpc_buffer(xprt) ((xprt)->xp_p1) #ifndef MAX #define MAX(a, b) (((a) > (b)) ? (a) : (b)) #endif static void svc_dg_ops(SVCXPRT *); static int svc_dg_cache_get(SVCXPRT *, struct rpc_msg *, char **, size_t *); static void svc_dg_cache_set(SVCXPRT *, size_t); static void svc_dg_enable_pktinfo(int, const struct __rpc_sockinfo *); static int svc_dg_store_pktinfo(struct msghdr *, struct svc_req *); /* * Usage: * xprt = svc_dg_ncreate(sock, sendsize, recvsize); * Does other connectionless specific initializations. * Once *xprt is initialized, it is registered. * see (svc.h, xprt_register). If recvsize or sendsize are 0 suitable * system defaults are chosen. * The routines returns NULL if a problem occurred. */ static const char svc_dg_str[] = "svc_dg_ncreate: %s"; static const char svc_dg_err1[] = "could not get transport information"; static const char svc_dg_err2[] = " transport does not support data transfer"; static const char __no_mem_str[] = "out of memory"; SVCXPRT * svc_dg_ncreate(int fd, u_int sendsize, u_int recvsize) { SVCXPRT *xprt; struct svc_dg_data *su = NULL; struct __rpc_sockinfo si; struct sockaddr_storage ss; socklen_t slen; if (!__rpc_fd2sockinfo(fd, &si)) { __warnx(TIRPC_DEBUG_FLAG_SVC_DG, svc_dg_str, svc_dg_err1); return (NULL); } /* * Find the receive and the send size */ sendsize = __rpc_get_t_size(si.si_af, si.si_proto, (int)sendsize); recvsize = __rpc_get_t_size(si.si_af, si.si_proto, (int)recvsize); if ((sendsize == 0) || (recvsize == 0)) { __warnx(TIRPC_DEBUG_FLAG_SVC_DG, svc_dg_str, svc_dg_err2); return (NULL); } xprt = mem_zalloc(sizeof(SVCXPRT)); /* Init SVCXPRT locks, etc */ mutex_init(&xprt->xp_lock, NULL); mutex_init(&xprt->xp_auth_lock, NULL); su = mem_alloc(sizeof(*su)); su->su_iosz = ((MAX(sendsize, recvsize) + 3) / 4) * 4; rpc_buffer(xprt) = mem_alloc(su->su_iosz); xdrmem_create(&(su->su_xdrs), rpc_buffer(xprt), su->su_iosz, XDR_DECODE); su->su_cache = NULL; xprt->xp_flags = SVC_XPRT_FLAG_NONE; xprt->xp_refs = 1; xprt->xp_fd = fd; xprt->xp_p2 = su; svc_dg_ops(xprt); slen = sizeof(ss); if (getsockname(fd, (struct sockaddr *)(void *)&ss, &slen) < 0) goto freedata; __rpc_set_address(&xprt->xp_local, &ss, slen); switch (ss.ss_family) { case AF_INET: xprt->xp_port = ntohs(((struct sockaddr_in *)&ss)->sin_port); break; #ifdef INET6 case AF_INET6: xprt->xp_port = ntohs(((struct sockaddr_in6 *)&ss)->sin6_port); break; #endif case AF_LOCAL: /* no port */ break; default: break; } /* Enable reception of IP*_PKTINFO control msgs */ svc_dg_enable_pktinfo(fd, &si); /* Make reachable - ref+1 */ xprt->xp_p5 = rpc_dplx_lookup_rec(xprt->xp_fd, RPC_DPLX_FLAG_NONE); svc_rqst_init_xprt(xprt); /* Conditional xprt_register */ if (!(__svc_params->flags & SVC_FLAG_NOREG_XPRTS)) xprt_register(xprt); #if defined(HAVE_BLKIN) __rpc_set_blkin_endpoint(xprt, "svc_dg"); #endif return (xprt); freedata: __warnx(TIRPC_DEBUG_FLAG_SVC_DG, svc_dg_str, __no_mem_str); mem_free(su, sizeof(*su)); xprt_unregister(xprt); mem_free(xprt, sizeof(SVCXPRT)); return (NULL); } /*ARGSUSED*/ static enum xprt_stat svc_dg_stat(SVCXPRT *xprt) { return (XPRT_IDLE); } static void svc_dg_set_pktinfo(struct cmsghdr *cmsg, struct svc_req *req) { switch (req->rq_daddr.ss_family) { case AF_INET: { struct in_pktinfo *pki = (struct in_pktinfo *)CMSG_DATA(cmsg); struct sockaddr_in *daddr = (struct sockaddr_in *)&req->rq_daddr; cmsg->cmsg_level = SOL_IP; cmsg->cmsg_type = IP_PKTINFO; pki->ipi_ifindex = 0; #ifdef __FreeBSD__ pki->ipi_addr = daddr->sin_addr; #else pki->ipi_spec_dst = daddr->sin_addr; #endif cmsg->cmsg_len = CMSG_LEN(sizeof(*pki)); break; } case AF_INET6: { struct in6_pktinfo *pki = (struct in6_pktinfo *)CMSG_DATA(cmsg); struct sockaddr_in6 *daddr = (struct sockaddr_in6 *)&req->rq_daddr; cmsg->cmsg_level = SOL_IPV6; cmsg->cmsg_type = IPV6_PKTINFO; pki->ipi6_ifindex = daddr->sin6_scope_id; pki->ipi6_addr = daddr->sin6_addr; cmsg->cmsg_len = CMSG_LEN(sizeof(*pki)); break; } default: break; } } static bool svc_dg_recv(SVCXPRT *xprt, struct svc_req *req) { struct svc_dg_data *su = su_data(xprt); XDR *xdrs = &(su->su_xdrs); char *reply; struct sockaddr_storage ss; struct sockaddr *sp = (struct sockaddr *)&ss; struct msghdr *mesgp; struct iovec iov; size_t replylen; ssize_t rlen; memset(&ss, 0xff, sizeof(struct sockaddr_storage)); /* Magic marker value to see if we didn't get the header. */ req->rq_msg = alloc_rpc_msg(); again: iov.iov_base = rpc_buffer(xprt); iov.iov_len = su->su_iosz; mesgp = &su->su_msghdr; memset(mesgp, 0, sizeof(*mesgp)); mesgp->msg_iov = &iov; mesgp->msg_iovlen = 1; mesgp->msg_name = (struct sockaddr *)(void *)&ss; sp->sa_family = (sa_family_t) 0xffff; mesgp->msg_namelen = sizeof(struct sockaddr_storage); mesgp->msg_control = su->su_cmsg; mesgp->msg_controllen = sizeof(su->su_cmsg); rlen = recvmsg(xprt->xp_fd, mesgp, 0); if (sp->sa_family == (sa_family_t) 0xffff) return false; if (rlen == -1 && errno == EINTR) goto again; if (rlen == -1 || (rlen < (ssize_t) (4 * sizeof(u_int32_t)))) return (false); __rpc_set_address(&xprt->xp_remote, &ss, mesgp->msg_namelen); /* Check whether there's an IP_PKTINFO or IP6_PKTINFO control message. * If yes, preserve it for svc_dg_reply; otherwise just zap any cmsgs */ if (!svc_dg_store_pktinfo(mesgp, req)) { mesgp->msg_control = NULL; mesgp->msg_controllen = 0; req->rq_daddr_len = 0; } xdrs->x_op = XDR_DECODE; XDR_SETPOS(xdrs, 0); if (!xdr_callmsg(xdrs, req->rq_msg)) return (false); req->rq_xprt = xprt; req->rq_prog = req->rq_msg->rm_call.cb_prog; req->rq_vers = req->rq_msg->rm_call.cb_vers; req->rq_proc = req->rq_msg->rm_call.cb_proc; req->rq_xid = req->rq_msg->rm_xid; req->rq_clntcred = req->rq_msg->rq_cred_body; /* save remote address */ req->rq_raddr_len = xprt->xp_remote.nb.len; memcpy(&req->rq_raddr, xprt->xp_remote.nb.buf, req->rq_raddr_len); /* the checksum */ req->rq_cksum = #if 1 CityHash64WithSeed(iov.iov_base, MIN(256, iov.iov_len), 103); #else calculate_crc32c(0, iov.iov_base, MIN(256, iov.iov_len)); #endif /* XXX su->su_xid !MT-SAFE */ su->su_xid = req->rq_msg->rm_xid; if (su->su_cache != NULL) { if (svc_dg_cache_get(xprt, req->rq_msg, &reply, &replylen)) { iov.iov_base = reply; iov.iov_len = replylen; /* Set source IP address of the reply message in * PKTINFO */ if (req->rq_daddr_len != 0) { struct cmsghdr *cmsg; cmsg = (struct cmsghdr *)mesgp->msg_control; svc_dg_set_pktinfo(cmsg, req); #ifndef CMSG_ALIGN #define CMSG_ALIGN(len) (len) #endif mesgp->msg_controllen = CMSG_ALIGN(cmsg->cmsg_len); } (void)sendmsg(xprt->xp_fd, mesgp, 0); return (false); } } return (true); } static bool svc_dg_reply(SVCXPRT *xprt, struct svc_req *req, struct rpc_msg *msg) { struct svc_dg_data *su = su_data(xprt); XDR *xdrs = &(su->su_xdrs); bool stat = false; size_t slen; xdrproc_t xdr_results; caddr_t xdr_location; bool has_args; if (msg->rm_reply.rp_stat == MSG_ACCEPTED && msg->rm_reply.rp_acpt.ar_stat == SUCCESS) { has_args = true; xdr_results = msg->acpted_rply.ar_results.proc; xdr_location = msg->acpted_rply.ar_results.where; msg->acpted_rply.ar_results.proc = (xdrproc_t) xdr_void; msg->acpted_rply.ar_results.where = NULL; } else { xdr_results = NULL; xdr_location = NULL; has_args = false; } xdrs->x_op = XDR_ENCODE; XDR_SETPOS(xdrs, 0); if (xdr_replymsg(xdrs, msg) && req->rq_raddr_len && (!has_args || (SVCAUTH_WRAP (req->rq_auth, req, xdrs, xdr_results, xdr_location)))) { struct msghdr *msg = &su->su_msghdr; struct cmsghdr *cmsg; struct iovec iov; iov.iov_base = rpc_buffer(xprt); iov.iov_len = slen = XDR_GETPOS(xdrs); msg->msg_iov = &iov; msg->msg_iovlen = 1; msg->msg_name = (struct sockaddr *)&req->rq_raddr; msg->msg_namelen = req->rq_raddr_len; /* Set source IP address of the reply message in PKTINFO */ if (req->rq_daddr_len != 0) { msg->msg_control = su->su_cmsg; cmsg = (struct cmsghdr *)msg->msg_control; svc_dg_set_pktinfo(cmsg, req); msg->msg_controllen = CMSG_ALIGN(cmsg->cmsg_len); } if (sendmsg(xprt->xp_fd, msg, 0) == (ssize_t) slen) { stat = true; if (su->su_cache) svc_dg_cache_set(xprt, slen); } } return (stat); } static bool svc_dg_freeargs(SVCXPRT *xprt, struct svc_req *req, xdrproc_t xdr_args, void *args_ptr) { return xdr_free(xdr_args, args_ptr); } static bool svc_dg_getargs(SVCXPRT *xprt, struct svc_req *req, xdrproc_t xdr_args, void *args_ptr, void *u_data) { struct svc_dg_data *su = su_data(xprt); XDR *xdrs = &(su->su_xdrs); bool rslt; /* threads u_data for advanced decoders */ xdrs->x_public = u_data; rslt = SVCAUTH_UNWRAP(req->rq_auth, req, xdrs, xdr_args, args_ptr); if (!rslt) { svc_dg_freeargs(xprt, req, xdr_args, args_ptr); } return (rslt); } static void svc_dg_lock(SVCXPRT *xprt, uint32_t flags, const char *file, int line) { rpc_dplx_rlxi(xprt, file, line); rpc_dplx_slxi(xprt, file, line); } static void svc_dg_unlock(SVCXPRT *xprt, uint32_t flags, const char *file, int line) { rpc_dplx_rux(xprt); rpc_dplx_sux(xprt); } static void svc_dg_destroy(SVCXPRT *xprt, u_int flags, const char *tag, const int line) { struct svc_dg_data *su = su_data(xprt); /* clears xprt from the xprt table (eg, idle scans) */ xprt_unregister(xprt); __warnx(TIRPC_DEBUG_FLAG_REFCNT, "%s() %p xp_refs %" PRIu32 " should actually destroy things @ %s:%d", __func__, xprt, xprt->xp_refs, tag, line); if (xprt->xp_fd != -1) (void)close(xprt->xp_fd); XDR_DESTROY(&(su->su_xdrs)); mem_free(rpc_buffer(xprt), su->su_iosz); mem_free(su, sizeof(*su)); if (xprt->xp_tp) mem_free(xprt->xp_tp, 0); rpc_dplx_unref((struct rpc_dplx_rec *)xprt->xp_p5, RPC_DPLX_FLAG_NONE); if (xprt->xp_ops->xp_free_user_data) { /* call free hook */ xprt->xp_ops->xp_free_user_data(xprt); } #if defined(HAVE_BLKIN) if (xprt->blkin.svc_name) mem_free(xprt->blkin.svc_name, 2*INET6_ADDRSTRLEN); #endif mem_free(xprt, sizeof(SVCXPRT)); } extern mutex_t ops_lock; /*ARGSUSED*/ static bool svc_dg_control(SVCXPRT *xprt, const u_int rq, void *in) { switch (rq) { case SVCGET_XP_FLAGS: *(u_int *) in = xprt->xp_flags; break; case SVCSET_XP_FLAGS: xprt->xp_flags = *(u_int *) in; break; case SVCGET_XP_RECV: mutex_lock(&ops_lock); *(xp_recv_t *) in = xprt->xp_ops->xp_recv; mutex_unlock(&ops_lock); break; case SVCSET_XP_RECV: mutex_lock(&ops_lock); xprt->xp_ops->xp_recv = *(xp_recv_t) in; mutex_unlock(&ops_lock); break; case SVCGET_XP_GETREQ: mutex_lock(&ops_lock); *(xp_getreq_t *) in = xprt->xp_ops->xp_getreq; mutex_unlock(&ops_lock); break; case SVCSET_XP_GETREQ: mutex_lock(&ops_lock); xprt->xp_ops->xp_getreq = *(xp_getreq_t) in; mutex_unlock(&ops_lock); break; case SVCGET_XP_DISPATCH: mutex_lock(&ops_lock); *(xp_dispatch_t *) in = xprt->xp_ops->xp_dispatch; mutex_unlock(&ops_lock); break; case SVCSET_XP_DISPATCH: mutex_lock(&ops_lock); xprt->xp_ops->xp_dispatch = *(xp_dispatch_t) in; mutex_unlock(&ops_lock); break; case SVCGET_XP_FREE_USER_DATA: mutex_lock(&ops_lock); *(xp_free_user_data_t *) in = xprt->xp_ops->xp_free_user_data; mutex_unlock(&ops_lock); break; case SVCSET_XP_FREE_USER_DATA: mutex_lock(&ops_lock); xprt->xp_ops->xp_free_user_data = *(xp_free_user_data_t) in; mutex_unlock(&ops_lock); break; default: return (false); } return (true); } static void svc_dg_ops(SVCXPRT *xprt) { static struct xp_ops ops; /* VARIABLES PROTECTED BY ops_lock: ops, xp_type */ mutex_lock(&ops_lock); /* Fill in type of service */ xprt->xp_type = XPRT_UDP; if (ops.xp_recv == NULL) { ops.xp_recv = svc_dg_recv; ops.xp_stat = svc_dg_stat; ops.xp_getargs = svc_dg_getargs; ops.xp_reply = svc_dg_reply; ops.xp_freeargs = svc_dg_freeargs; ops.xp_destroy = svc_dg_destroy; ops.xp_control = svc_dg_control; ops.xp_lock = svc_dg_lock; ops.xp_unlock = svc_dg_unlock; ops.xp_getreq = svc_getreq_default; ops.xp_dispatch = svc_dispatch_default; ops.xp_recv_user_data = NULL; /* no default */ ops.xp_free_user_data = NULL; /* no default */ } xprt->xp_ops = &ops; mutex_unlock(&ops_lock); } /* * Enable use of the cache. Returns 1 on success, 0 on failure. * Note: there is no disable. */ static const char cache_enable_str[] = "svc_enablecache: %s %s"; static const char enable_err[] = "cache already enabled"; int svc_dg_enablecache(SVCXPRT *transp, u_int size) { struct svc_dg_data *su = su_data(transp); struct cl_cache *uc; mutex_lock(&dupreq_lock); if (su->su_cache != NULL) { __warnx(TIRPC_DEBUG_FLAG_SVC_DG, cache_enable_str, enable_err, " "); mutex_unlock(&dupreq_lock); return (0); } uc = mem_alloc(sizeof(*uc)); uc->uc_size = size; uc->uc_nextvictim = 0; uc->uc_entries = mem_calloc(size * SPARSENESS, sizeof(cache_ptr)); uc->uc_fifo = mem_calloc(size, sizeof(cache_ptr)); su->su_cache = (char *)(void *)uc; mutex_unlock(&dupreq_lock); return (1); } /* * Set an entry in the cache. It assumes that the uc entry is set from * the earlier call to svc_dg_cache_get() for the same procedure. This will * always happen because svc_dg_cache_get() is calle by svc_dg_recv and * svc_dg_cache_set() is called by svc_dg_reply(). All this hoopla because * the right RPC parameters are not available at svc_dg_reply time. */ static const char cache_set_str[] = "cache_set: %s"; static const char cache_set_err1[] = "victim not found"; static void svc_dg_cache_set(SVCXPRT *xprt, size_t replylen) { cache_ptr victim; cache_ptr *vicp; struct svc_dg_data *su = su_data(xprt); struct cl_cache *uc = (struct cl_cache *)su->su_cache; u_int loc; char *newbuf; struct netconfig *nconf; char *uaddr; mutex_lock(&dupreq_lock); /* * Find space for the new entry, either by * reusing an old entry, or by mallocing a new one */ victim = uc->uc_fifo[uc->uc_nextvictim]; if (victim != NULL) { loc = CACHE_LOC(xprt, victim->cache_xid); for (vicp = &uc->uc_entries[loc]; *vicp != NULL && *vicp != victim; vicp = &(*vicp)->cache_next); if (*vicp == NULL) { __warnx(TIRPC_DEBUG_FLAG_SVC_DG, cache_set_str, cache_set_err1); mutex_unlock(&dupreq_lock); return; } *vicp = victim->cache_next; /* remove from cache */ newbuf = victim->cache_reply; } else { victim = mem_alloc(sizeof(struct cache_node)); newbuf = mem_alloc(su->su_iosz); } /* * Store it away */ if (__debug_flag(TIRPC_DEBUG_FLAG_RPC_CACHE)) { nconf = getnetconfigent(xprt->xp_netid); if (nconf) { uaddr = taddr2uaddr(nconf, &xprt->xp_remote.nb); freenetconfigent(nconf); __warnx(TIRPC_DEBUG_FLAG_SVC_DG, "cache set for xid= %x prog=%d vers=%d proc=%d " "for rmtaddr=%s\n", su->su_xid, uc->uc_prog, uc->uc_vers, uc->uc_proc, uaddr); mem_free(uaddr, 0); /* XXX */ } } /* DEBUG_RPC_CACHE */ victim->cache_replylen = replylen; victim->cache_reply = rpc_buffer(xprt); rpc_buffer(xprt) = newbuf; xdrmem_create(&(su->su_xdrs), rpc_buffer(xprt), su->su_iosz, XDR_ENCODE); victim->cache_xid = su->su_xid; victim->cache_proc = uc->uc_proc; victim->cache_vers = uc->uc_vers; victim->cache_prog = uc->uc_prog; victim->cache_addr = xprt->xp_remote.nb; victim->cache_addr.buf = mem_alloc(xprt->xp_remote.nb.len); (void)memcpy(victim->cache_addr.buf, xprt->xp_remote.nb.buf, (size_t) xprt->xp_remote.nb.len); loc = CACHE_LOC(xprt, victim->cache_xid); victim->cache_next = uc->uc_entries[loc]; uc->uc_entries[loc] = victim; uc->uc_fifo[uc->uc_nextvictim++] = victim; uc->uc_nextvictim %= uc->uc_size; mutex_unlock(&dupreq_lock); } /* * Try to get an entry from the cache * return 1 if found, 0 if not found and set the stage for svc_dg_cache_set() */ static int svc_dg_cache_get(SVCXPRT *xprt, struct rpc_msg *msg, char **replyp, size_t *replylenp) { u_int loc; cache_ptr ent; struct svc_dg_data *su = su_data(xprt); struct cl_cache *uc = (struct cl_cache *)su->su_cache; struct netconfig *nconf; char *uaddr; mutex_lock(&dupreq_lock); loc = CACHE_LOC(xprt, su->su_xid); for (ent = uc->uc_entries[loc]; ent != NULL; ent = ent->cache_next) { if (ent->cache_xid == su->su_xid && ent->cache_proc == msg->rm_call.cb_proc && ent->cache_vers == msg->rm_call.cb_vers && ent->cache_prog == msg->rm_call.cb_prog && ent->cache_addr.len == xprt->xp_remote.nb.len && (memcmp (ent->cache_addr.buf, xprt->xp_remote.nb.buf, xprt->xp_remote.nb.len) == 0)) { if (__debug_flag(TIRPC_DEBUG_FLAG_RPC_CACHE)) { nconf = getnetconfigent(xprt->xp_netid); if (nconf) { uaddr = taddr2uaddr(nconf, &xprt->xp_remote.nb); freenetconfigent(nconf); __warnx(TIRPC_DEBUG_FLAG_SVC_DG, "cache entry found for xid=%x prog=%d " "vers=%d proc=%d for rmtaddr=%s\n", su->su_xid, msg->rm_call.cb_prog, msg->rm_call.cb_vers, msg->rm_call.cb_proc, uaddr); mem_free(uaddr, 0); } } /* RPC_CACHE_DEBUG */ *replyp = ent->cache_reply; *replylenp = ent->cache_replylen; mutex_unlock(&dupreq_lock); return (1); } } /* * Failed to find entry * Remember a few things so we can do a set later */ uc->uc_proc = msg->rm_call.cb_proc; uc->uc_vers = msg->rm_call.cb_vers; uc->uc_prog = msg->rm_call.cb_prog; mutex_unlock(&dupreq_lock); return (0); } /* * Enable reception of PKTINFO control messages */ void svc_dg_enable_pktinfo(int fd, const struct __rpc_sockinfo *si) { int val = 1; switch (si->si_af) { case AF_INET: #ifdef SOL_IP (void)setsockopt(fd, SOL_IP, IP_PKTINFO, &val, sizeof(val)); #endif break; case AF_INET6: #ifdef SOL_IPV6 (void)setsockopt(fd, SOL_IP, IP_PKTINFO, &val, sizeof(val)); (void)setsockopt(fd, SOL_IPV6, IPV6_RECVPKTINFO, &val, sizeof(val)); #endif break; } } static int svc_dg_store_in_pktinfo(struct cmsghdr *cmsg, struct svc_req *req) { if (cmsg->cmsg_level == SOL_IP && cmsg->cmsg_type == IP_PKTINFO && cmsg->cmsg_len >= CMSG_LEN(sizeof(struct in_pktinfo))) { struct in_pktinfo *pkti; struct sockaddr_in *daddr; pkti = (struct in_pktinfo *)CMSG_DATA(cmsg); daddr = (struct sockaddr_in *)&req->rq_daddr; daddr->sin_family = AF_INET; #ifdef __FreeBSD__ daddr->sin_addr = pkti->ipi_addr; #else daddr->sin_addr.s_addr = pkti->ipi_spec_dst.s_addr; #endif req->rq_daddr_len = sizeof(struct sockaddr_in); return 1; } else { return 0; } } static int svc_dg_store_in6_pktinfo(struct cmsghdr *cmsg, struct svc_req *req) { if (cmsg->cmsg_level == SOL_IPV6 && cmsg->cmsg_type == IPV6_PKTINFO && cmsg->cmsg_len >= CMSG_LEN(sizeof(struct in6_pktinfo))) { struct in6_pktinfo *pkti; struct sockaddr_in6 *daddr; pkti = (struct in6_pktinfo *)CMSG_DATA(cmsg); daddr = (struct sockaddr_in6 *) &req->rq_daddr; daddr->sin6_family = AF_INET6; daddr->sin6_addr = pkti->ipi6_addr; daddr->sin6_scope_id = pkti->ipi6_ifindex; req->rq_daddr_len = sizeof(struct sockaddr_in6); return 1; } else { return 0; } } /* * When given a control message received from the socket * layer, check whether it contains valid PKTINFO data. * If so, store the data in the request. */ static int svc_dg_store_pktinfo(struct msghdr *msg, struct svc_req *req) { struct cmsghdr *cmsg; if (!msg->msg_name) return 0; if (msg->msg_flags & MSG_CTRUNC) return 0; cmsg = CMSG_FIRSTHDR(msg); if (cmsg == NULL || CMSG_NXTHDR(msg, cmsg) != NULL) return 0; switch (((struct sockaddr *)msg->msg_name)->sa_family) { case AF_INET: #ifdef SOL_IP if (svc_dg_store_in_pktinfo(cmsg, req)) return 1; #endif break; case AF_INET6: #ifdef SOL_IPV6 /* Handle IPv4 PKTINFO as well on IPV6 interface */ if (svc_dg_store_in_pktinfo(cmsg, req)) return 1; if (svc_dg_store_in6_pktinfo(cmsg, req)) return 1; #endif break; default: break; } return 0; } <file_sep> /* * Copyright (c) 1988 by Sun Microsystems, Inc. */ /* * Copyright (c) 2009, Sun Microsystems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - Neither the name of Sun Microsystems, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* * svcauth_des.c, server-side des authentication * * We insure for the service the following: * (1) The timestamp microseconds do not exceed 1 million. * (2) The timestamp plus the window is less than the current time. * (3) The timestamp is not less than the one previously * seen in the current session. * * It is up to the server to determine if the window size is * too small . * */ #include <pthread.h> #include <reentrant.h> #include <string.h> #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <rpc/des_crypt.h> #include <sys/param.h> #include <netinet/in.h> #include <rpc/types.h> #include <rpc/xdr.h> #include <rpc/auth.h> #include <rpc/auth_des.h> #include <rpc/svc.h> #include <rpc/rpc_msg.h> #include <rpc/svc_auth.h> #if defined(__FreeBSD__) || defined(__NetBSD__) #include <libc_private.h> #endif extern int key_decryptsession_pk(const char *, netobj *, des_block *); #define debug(msg) __warnx("svcauth_des: %s\n", (msg)) #define USEC_PER_SEC ((u_long) 1000000L) #define BEFORE(t1, t2) timercmp(t1, t2, <) /* * LRU cache of conversation keys and some other useful items. */ #define AUTHDES_CACHESZ 64 struct cache_entry { des_block key; /* conversation key */ char *rname; /* client's name */ u_int window; /* credential lifetime window */ struct timeval laststamp; /* detect replays of creds */ char *localcred; /* generic local credential */ }; static struct cache_entry *authdes_cache /* [AUTHDES_CACHESZ] */; static short *authdes_lru /* [AUTHDES_CACHESZ] */; static void cache_init(void); /* initialize the cache */ static short cache_spot(void); /* find an entry in the cache */ static void cache_ref(short sid); /* note that sid was ref'd */ static void invalidate(void); /* invalidate entry in cache */ /* * cache statistics */ static struct { u_long ncachehits; /* times cache hit, and is not replay */ u_long ncachereplays; /* times cache hit, and is replay */ u_long ncachemisses; /* times cache missed */ } svcauthdes_stats; /* * Service side authenticator for AUTH_DES */ enum auth_stat _svcauth_des(struct svc_req *req, struct rpc_msg *msg) { long *ixdr; des_block cryptbuf[2]; struct authdes_cred *cred; struct authdes_verf verf; int status; struct cache_entry *entry; short sid = 0; des_block *sessionkey; des_block ivec; u_int window; struct timeval timestamp; u_long namelen; struct area { struct authdes_cred area_cred; char area_netname[MAXNETNAMELEN + 1]; } *area; /* Initialize reply. */ req->rq_verf = _null_auth; if (!authdes_cache) cache_init(); area = (struct area *)req->rq_clntcred; cred = (struct authdes_cred *)&area->area_cred; /* * Get the credential */ ixdr = (long *)msg->rm_call.cb_cred.oa_base; cred->adc_namekind = IXDR_GET_ENUM(ixdr, enum authdes_namekind); switch (cred->adc_namekind) { case ADN_FULLNAME: namelen = IXDR_GET_U_LONG(ixdr); if (namelen > MAXNETNAMELEN) return (AUTH_BADCRED); cred->adc_fullname.name = area->area_netname; bcopy((char *)ixdr, cred->adc_fullname.name, (u_int) namelen); cred->adc_fullname.name[namelen] = 0; ixdr += (RNDUP(namelen) / BYTES_PER_XDR_UNIT); cred->adc_fullname.key.key.high = (u_long) *ixdr++; cred->adc_fullname.key.key.low = (u_long) *ixdr++; cred->adc_fullname.window = (u_long) *ixdr++; break; case ADN_NICKNAME: cred->adc_nickname = (u_long) *ixdr++; break; default: return (AUTH_BADCRED); } /* * Get the verifier */ ixdr = (long *)msg->rm_call.cb_verf.oa_base; verf.adv_xtimestamp.key.high = (u_long) *ixdr++; verf.adv_xtimestamp.key.low = (u_long) *ixdr++; verf.adv_int_u = (u_long) *ixdr++; /* * Get the conversation key */ if (cred->adc_namekind == ADN_FULLNAME) { netobj pkey; char pkey_data[1024]; sessionkey = &cred->adc_fullname.key; if (!getpublickey(cred->adc_fullname.name, pkey_data)) { debug("getpublickey"); return (AUTH_BADCRED); } pkey.n_bytes = pkey_data; pkey.n_len = strlen(pkey_data) + 1; if (key_decryptsession_pk (cred->adc_fullname.name, &pkey, sessionkey) < 0) { debug("decryptsessionkey"); return (AUTH_BADCRED); /* key not found */ } } else { /* ADN_NICKNAME */ sid = (short)cred->adc_nickname; if (sid < 0 || sid >= AUTHDES_CACHESZ) { debug("bad nickname"); return (AUTH_BADCRED); /* garbled credential */ } sessionkey = &authdes_cache[sid].key; } /* * Decrypt the timestamp */ cryptbuf[0] = verf.adv_xtimestamp; if (cred->adc_namekind == ADN_FULLNAME) { cryptbuf[1].key.high = cred->adc_fullname.window; cryptbuf[1].key.low = verf.adv_winverf; ivec.key.high = ivec.key.low = 0; status = cbc_crypt((char *)sessionkey, (char *)cryptbuf, 2 * sizeof(des_block), DES_DECRYPT | DES_HW, (char *)&ivec); } else { status = ecb_crypt((char *)sessionkey, (char *)cryptbuf, sizeof(des_block), DES_DECRYPT | DES_HW); } if (DES_FAILED(status)) { debug("decryption failure"); return (AUTH_FAILED); /* system error */ } /* * XDR the decrypted timestamp */ ixdr = (long *)cryptbuf; timestamp.tv_sec = IXDR_GET_LONG(ixdr); timestamp.tv_usec = IXDR_GET_LONG(ixdr); /* * Check for valid credentials and verifiers. * They could be invalid because the key was flushed * out of the cache, and so a new session should begin. * Be sure and send AUTH_REJECTED{CRED, VERF} if this is the case. */ { struct timeval current; int nick; int winverf; if (cred->adc_namekind == ADN_FULLNAME) { window = IXDR_GET_U_LONG(ixdr); winverf = IXDR_GET_U_LONG(ixdr); if (winverf != window - 1) { debug("window verifier mismatch"); return (AUTH_BADCRED); /* garbled credential */ } sid = cache_spot(sessionkey, cred->adc_fullname.name, &timestamp); if (sid < 0) { debug("replayed credential"); return (AUTH_REJECTEDCRED); /* replay */ } nick = 0; } else { /* ADN_NICKNAME */ window = authdes_cache[sid].window; nick = 1; } if ((u_long) timestamp.tv_usec >= USEC_PER_SEC) { debug("invalid usecs"); /* cached out (bad key), or garbled verifier */ return (nick ? AUTH_REJECTEDVERF : AUTH_BADVERF); } if (nick && BEFORE(&timestamp, &authdes_cache[sid].laststamp)) { debug("timestamp before last seen"); return (AUTH_REJECTEDVERF); /* replay */ } (void)gettimeofday(&current, (struct timezone *)NULL); current.tv_sec -= window; /* allow for expiration */ if (!BEFORE(&current, &timestamp)) { debug("timestamp expired"); /* replay, or garbled credential */ return (nick ? AUTH_REJECTEDVERF : AUTH_BADCRED); } } /* * Set up the reply verifier */ verf.adv_nickname = (u_long) sid; /* * xdr the timestamp before encrypting */ ixdr = (long *)cryptbuf; IXDR_PUT_LONG(ixdr, timestamp.tv_sec - 1); IXDR_PUT_LONG(ixdr, timestamp.tv_usec); /* * encrypt the timestamp */ status = ecb_crypt((char *)sessionkey, (char *)cryptbuf, sizeof(des_block), DES_ENCRYPT | DES_HW); if (DES_FAILED(status)) { debug("encryption failure"); return (AUTH_FAILED); /* system error */ } verf.adv_xtimestamp = cryptbuf[0]; /* * Serialize the reply verifier, and update req */ ixdr = (long *)msg->rm_call.cb_verf.oa_base; *ixdr++ = (long)verf.adv_xtimestamp.key.high; *ixdr++ = (long)verf.adv_xtimestamp.key.low; *ixdr++ = (long)verf.adv_int_u; req->rq_verf.oa_flavor = AUTH_DES; req->rq_verf.oa_base = msg->rm_call.cb_verf.oa_base; req->rq_verf.oa_length = (char *)ixdr - msg->rm_call.cb_verf.oa_base; /* * We succeeded, commit the data to the cache now and * finish cooking the credential. */ entry = &authdes_cache[sid]; entry->laststamp = timestamp; cache_ref(sid); if (cred->adc_namekind == ADN_FULLNAME) { cred->adc_fullname.window = window; cred->adc_nickname = (u_long) sid; /* save nickname */ if (entry->rname != NULL) mem_free(entry->rname, strlen(entry->rname) + 1); entry->rname = (char *)mem_strdup(cred->adc_fullname.name)); entry->key = *sessionkey; entry->window = window; invalidate(entry->localcred); /* mark any cached cred invalid */ } else { /* ADN_NICKNAME */ /* * nicknames are cooked into fullnames */ cred->adc_namekind = ADN_FULLNAME; cred->adc_fullname.name = entry->rname; cred->adc_fullname.key = entry->key; cred->adc_fullname.window = entry->window; } return (AUTH_OK); /* we made it! */ } /* * Initialize the cache */ static void cache_init(void) { int i; authdes_cache = (struct cache_entry *) mem_calloc(AUTHDES_CACHESZ, sizeof(struct cache_entry)); authdes_lru = (short *)mem_calloc(AUTHDES_CACHESZ, sizeof(short)); /* * Initialize the lru list */ for (i = 0; i < AUTHDES_CACHESZ; i++) { /* suppress block warning */ authdes_lru[i] = i; } } /* * Find the lru victim */ static short cache_victim(void) { return (authdes_lru[AUTHDES_CACHESZ - 1]); } /* * Note that sid was referenced */ static void cache_ref(short sid) { int i; short curr; short prev; prev = authdes_lru[0]; authdes_lru[0] = sid; for (i = 1; prev != sid; i++) { curr = authdes_lru[i]; authdes_lru[i] = prev; prev = curr; } } /* * Find a spot in the cache for a credential containing * the items given. Return -1 if a replay is detected, otherwise * return the spot in the cache. */ static short cache_spot(des_block *key, char *name, struct timeval *timestamp) { struct cache_entry *cp; int i; u_long hi; hi = key->key.high; for (cp = authdes_cache, i = 0; i < AUTHDES_CACHESZ; i++, cp++) { if (cp->key.key.high == hi && cp->key.key.low == key->key.low && cp->rname != NULL && bcmp(cp->rname, name, strlen(name) + 1) == 0) { if (BEFORE(timestamp, &cp->laststamp)) { svcauthdes_stats.ncachereplays++; return (-1); /* replay */ } svcauthdes_stats.ncachehits++; return (i); /* refresh */ } } svcauthdes_stats.ncachemisses++; return (cache_victim()); /* new credential */ } #if (defined(sun) || defined(vax) || defined(__FreeBSD__)) /* * Local credential handling stuff. * NOTE: bsd unix dependent. * Other operating systems should put something else here. */ #define UNKNOWN -2 /* grouplen, if cached cred is unknown user */ #define INVALID -1 /* grouplen, if cache entry is invalid */ struct bsdcred { short uid; /* cached uid */ short gid; /* cached gid */ short grouplen; /* length of cached groups */ short groups[NGROUPS]; /* cached groups */ }; /* * Map a des credential into a unix cred. * We cache the credential here so the application does * not have to make an rpc call every time to interpret * the credential. */ int authdes_getucred(struct authdes_cred *adc, uid_t *uid, gid_t *gid, int *grouplen, gid_t *groups) { unsigned sid; int i; uid_t i_uid; gid_t i_gid; int i_grouplen; struct bsdcred *cred; sid = adc->adc_nickname; if (sid >= AUTHDES_CACHESZ) { debug("invalid nickname"); return (0); } cred = (struct bsdcred *)authdes_cache[sid].localcred; if (cred == NULL) { cred = (struct bsdcred *)mem_alloc(sizeof(struct bsdcred)); authdes_cache[sid].localcred = (char *)cred; cred->grouplen = INVALID; } if (cred->grouplen == INVALID) { /* * not in cache: lookup */ if (!netname2user (adc->adc_fullname.name, &i_uid, &i_gid, &i_grouplen, groups)) { debug("unknown netname"); cred->grouplen = UNKNOWN; /* mark as lookup up, but * not found */ return (0); } debug("missed ucred cache"); *uid = cred->uid = i_uid; *gid = cred->gid = i_gid; *grouplen = cred->grouplen = i_grouplen; for (i = i_grouplen - 1; i >= 0; i--) { /* suppress block warning */ cred->groups[i] = groups[i]; /* int to short */ } return (1); } else if (cred->grouplen == UNKNOWN) { /* * Already lookup up, but no match found */ return (0); } /* * cached credentials */ *uid = cred->uid; *gid = cred->gid; *grouplen = cred->grouplen; for (i = cred->grouplen - 1; i >= 0; i--) { /* suppress block warning */ groups[i] = cred->groups[i]; /* short to int */ } return (1); } static void invalidate(char *cred) { if (cred == NULL) return; ((struct bsdcred *)cred)->grouplen = INVALID; } #endif <file_sep>/* * Copyright (c) 2012 Linux Box Corporation. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR `AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef RPC_DPLX_INTERNAL_H #define RPC_DPLX_INTERNAL_H #include <rpc/rpc_dplx.h> struct rpc_dplx_rec; /* in clnt_internal.h (avoids circular dependency) */ struct rpc_dplx_rec_set { mutex_t clnt_fd_lock; /* XXX check dplx correctness */ struct rbtree_x xt; }; /* XXX perhaps better off as a flag bit (until we can remove it) */ #define rpc_flag_clear 0 #define rpc_lock_value 1 enum rpc_duplex_callpath { RPC_DPLX_CLNT = 1, RPC_DPLX_SVC }; #define RPC_DPLX_FLAG_NONE 0x0000 #define RPC_DPLX_FLAG_LOCKED 0x0001 #define RPC_DPLX_FLAG_LOCK 0x0002 #define RPC_DPLX_FLAG_LOCKREC 0x0004 #define RPC_DPLX_FLAG_RECLOCKED 0x0008 #define RPC_DPLX_FLAG_UNLOCK 0x0010 #ifndef HAVE_STRLCAT extern size_t strlcat(char *, const char *, size_t); #endif #ifndef HAVE_STRLCPY extern size_t strlcpy(char *, const char *src, size_t); #endif #define RPC_DPLX_LKP_FLAG_NONE 0x0000 #define RPC_DPLX_LKP_IFLAG_LOCKREC 0x0001 #define RPC_DPLX_LKP_OFLAG_ALLOC 0x0002 struct rpc_dplx_rec *rpc_dplx_lookup_rec(int, uint32_t); static inline void rpc_dplx_lock_init(struct rpc_dplx_lock *lock) { lock->lock_flag_value = 0; mutex_init(&lock->we.mtx, NULL); cond_init(&lock->we.cv, 0, NULL); } static inline void rpc_dplx_lock_destroy(struct rpc_dplx_lock *lock) { mutex_destroy(&lock->we.mtx); cond_destroy(&lock->we.cv); } static inline int32_t rpc_dplx_ref(struct rpc_dplx_rec *rec, u_int flags) { int32_t refcnt; if (!(flags & RPC_DPLX_FLAG_LOCKED)) REC_LOCK(rec); refcnt = ++(rec->refcnt); /* release rec lock only if a) we took it and b) caller doesn't * want it returned locked */ if ((!(flags & RPC_DPLX_FLAG_LOCKED)) && (!(flags & RPC_DPLX_FLAG_LOCK))) REC_UNLOCK(rec); __warnx(TIRPC_DEBUG_FLAG_REFCNT, "%s: rec %p rec->refcnt %u", __func__, rec, refcnt); return (refcnt); } int32_t rpc_dplx_unref(struct rpc_dplx_rec *rec, u_int flags); /* swi: send wait impl */ static inline void rpc_dplx_swi(struct rpc_dplx_rec *rec, uint32_t wait_for) { rpc_dplx_lock_t *lk = &rec->send.lock; mutex_lock(&lk->we.mtx); while (lk->lock_flag_value != rpc_flag_clear) cond_wait(&lk->we.cv, &lk->we.mtx); mutex_unlock(&lk->we.mtx); } /* swc: send wait clnt */ static inline void rpc_dplx_swc(CLIENT *clnt, uint32_t wait_for) { struct rpc_dplx_rec *rec = (struct rpc_dplx_rec *)clnt->cl_p2; rpc_dplx_swi(rec, wait_for); } /* rwi: recv wait impl */ static inline void rpc_dplx_rwi(struct rpc_dplx_rec *rec, uint32_t wait_for) { rpc_dplx_lock_t *lk = &rec->recv.lock; mutex_lock(&lk->we.mtx); while (lk->lock_flag_value != rpc_flag_clear) cond_wait(&lk->we.cv, &lk->we.mtx); mutex_unlock(&lk->we.mtx); } /* rwc: recv wait clnt */ static inline void rpc_dplx_rwc(CLIENT *clnt, uint32_t wait_for) { struct rpc_dplx_rec *rec = (struct rpc_dplx_rec *)clnt->cl_p2; rpc_dplx_rwi(rec, wait_for); } /* ssi: send signal impl */ static inline void rpc_dplx_ssi(struct rpc_dplx_rec *rec, uint32_t flags) { rpc_dplx_lock_t *lk = &rec->send.lock; if (flags & RPC_DPLX_FLAG_LOCK) mutex_lock(&lk->we.mtx); cond_signal(&lk->we.cv); if (flags & RPC_DPLX_FLAG_LOCK) mutex_unlock(&lk->we.mtx); } /* ssc: send signal clnt */ static inline void rpc_dplx_ssc(CLIENT *clnt, uint32_t flags) { struct rpc_dplx_rec *rec = (struct rpc_dplx_rec *)clnt->cl_p2; rpc_dplx_ssi(rec, flags); } /* swf: send wait fd */ #define rpc_dplx_swf(fd, wait_for) \ do { \ struct vc_fd_rec *rec = rpc_dplx_lookup_rec(fd); \ rpc_dplx_swi(rec, wait_for); \ } while (0) /* rsi: recv signal impl */ static inline void rpc_dplx_rsi(struct rpc_dplx_rec *rec, uint32_t flags) { rpc_dplx_lock_t *lk = &rec->recv.lock; if (flags & RPC_DPLX_FLAG_LOCK) mutex_lock(&lk->we.mtx); cond_signal(&lk->we.cv); if (flags & RPC_DPLX_FLAG_LOCK) mutex_unlock(&lk->we.mtx); } /* rsc: recv signal clnt */ static inline void rpc_dplx_rsc(CLIENT *clnt, uint32_t flags) { struct rpc_dplx_rec *rec = (struct rpc_dplx_rec *)clnt->cl_p2; rpc_dplx_rsi(rec, flags); } /* rwf: recv wait fd */ #define rpc_dplx_rwf(fd, wait_for) \ do { \ struct vc_fd_rec *rec = rpc_dplx_lookup_rec(fd); \ rpc_dplx_rwi(rec, wait_for); \ } while (0) /* ssf: send signal fd */ #define rpc_dplx_ssf(fd, flags) \ do { \ struct vc_fd_rec *rec = rpc_dplx_lookup_rec(fd); \ rpc_dplx_ssi(rec, flags); \ } while (0) /* rsf: send signal fd */ #define rpc_dplx_rsf(fd, flags) \ do { \ struct vc_fd_rec *rec = rpc_dplx_lookup_rec(fd); \ rpc_dplx_rsi(rec, flags); \ } while (0) void rpc_dplx_shutdown(void); #endif /* RPC_DPLX_INTERNAL_H */ <file_sep>/* @(#)auth_des.h 2.2 88/07/29 4.0 RPCSRC; from 1.3 88/02/08 SMI */ /* $FreeBSD: src/include/rpc/auth_des.h,v 1.3 2002/03/23 17:24:55 imp Exp $ */ /* * Copyright (c) 2009, Sun Microsystems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - Neither the name of Sun Microsystems, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * from: @(#)auth_des.h 2.2 88/07/29 4.0 RPCSRC * from: @(#)auth_des.h 1.14 94/04/25 SMI */ /* * Copyright (c) 1986 - 1991 by Sun Microsystems, Inc. */ /* * auth_des.h, Protocol for DES style authentication for RPC */ #ifndef _TI_AUTH_DES_ #define _TI_AUTH_DES_ #include <rpc/auth.h> /* * There are two kinds of "names": fullnames and nicknames */ enum authdes_namekind { ADN_FULLNAME, ADN_NICKNAME }; /* * A fullname contains the network name of the client, * a conversation key and the window */ struct authdes_fullname { char *name; /* network name of client, up to MAXNETNAMELEN */ union des_block key; /* conversation key */ /* u_long window; */ u_int32_t window; /* associated window */ }; /* * A credential */ struct authdes_cred { enum authdes_namekind adc_namekind; struct authdes_fullname adc_fullname; /*u_long adc_nickname; */ u_int32_t adc_nickname; }; /* * A des authentication verifier */ struct authdes_verf { union { struct timeval adv_ctime; /* clear time */ des_block adv_xtime; /* crypt time */ } adv_time_u; /*u_long adv_int_u; */ u_int32_t adv_int_u; }; /* * des authentication verifier: client variety * * adv_timestamp is the current time. * adv_winverf is the credential window + 1. * Both are encrypted using the conversation key. */ #define adv_timestamp adv_time_u.adv_ctime #define adv_xtimestamp adv_time_u.adv_xtime #define adv_winverf adv_int_u /* * des authentication verifier: server variety * * adv_timeverf is the client's timestamp + client's window * adv_nickname is the server's nickname for the client. * adv_timeverf is encrypted using the conversation key. */ #define adv_timeverf adv_time_u.adv_ctime #define adv_xtimeverf adv_time_u.adv_xtime #define adv_nickname adv_int_u /* * Map a des credential into a unix cred. * */ __BEGIN_DECLS extern int authdes_getucred(struct authdes_cred *, uid_t *, gid_t *, int *, gid_t *); __END_DECLS __BEGIN_DECLS extern bool xdr_authdes_cred(XDR *, struct authdes_cred *); extern bool xdr_authdes_verf(XDR *, struct authdes_verf *); extern int rtime(dev_t, struct netbuf *, int, struct timeval *, struct timeval *); extern void kgetnetname(char *); extern enum auth_stat _svcauth_des(struct svc_req *, struct rpc_msg *); __END_DECLS #endif /* ndef _TI_AUTH_DES_ */ <file_sep>/* * Copyright (c) 2009,s Sun Microsystems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - Neither the name of Sun Microsystems, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <config.h> #include <sys/cdefs.h> #include <sys/cdefs.h> /* * xdr_rec.c, Implements TCP/IP based XDR streams with a "record marking" * layer above tcp (for rpc's use). * * Copyright (C) 1984, Sun Microsystems, Inc. * * These routines interface XDRSTREAMS to a tcp/ip connection. * There is a record marking layer between the xdr stream * and the tcp transport level. A record is composed on one or more * record fragments. A record fragment is a thirty-two bit header followed * by n bytes of data, where n is contained in the header. The header * is represented as a htonl(u_long). Thegh order bit encodes * whether or not the fragment is the last fragment of the record * (1 => fragment is last, 0 => more fragments to follow. * The other 31 bits encode the byte length of the fragment. */ #include <sys/types.h> #if !defined(_WIN32) #include <netinet/in.h> #include <err.h> #endif #include <stdio.h> #include <stdlib.h> #include <string.h> #include <rpc/types.h> #include <misc/portable.h> #include <rpc/xdr.h> #include <rpc/rpc.h> #include <rpc/auth.h> #include <rpc/svc_auth.h> #include <rpc/svc.h> #include <rpc/clnt.h> #include <stddef.h> #include "rpc_com.h" #include <misc/city.h> #include <rpc/rpc_cksum.h> #include <intrinsic.h> static bool xdr_inrec_getlong(XDR *, long *); static bool xdr_inrec_putlong(XDR *, const long *); static bool xdr_inrec_getbytes(XDR *, char *, u_int); static bool xdr_inrec_putbytes(XDR *, const char *, u_int); static u_int xdr_inrec_getpos(XDR *); static bool xdr_inrec_setpos(XDR *, u_int); static int32_t *xdr_inrec_inline(XDR *, u_int); static void xdr_inrec_destroy(XDR *); static bool xdr_inrec_noop(void); extern bool xdr_inrec_readahead(XDR *, u_int); typedef bool (*dummyfunc3) (XDR *, int, void *); typedef bool (*dummy_getbufs) (XDR *, xdr_uio *, u_int); typedef bool (*dummy_putbufs) (XDR *, xdr_uio *, u_int); static const struct xdr_ops xdr_inrec_ops = { xdr_inrec_getlong, xdr_inrec_putlong, xdr_inrec_getbytes, xdr_inrec_putbytes, xdr_inrec_getpos, xdr_inrec_setpos, xdr_inrec_inline, xdr_inrec_destroy, (dummyfunc3) xdr_inrec_noop, /* x_control */ (dummy_getbufs) xdr_inrec_noop, /* x_getbufs */ (dummy_putbufs) xdr_inrec_noop /* x_putbufs */ }; /* * A record is composed of one or more record fragments. * A record fragment is a four-byte header followed by zero to * 2**32-1 bytes. The header is treated as a long unsigned and is * encode/decoded to the network via htonl/ntohl. The low order 31 bits * are a byte count of the fragment. The highest order bit is a boolean: * 1 => this fragment is the last fragment of the record, * 0 => this fragment is followed by more fragment(s). * * The fragment/record machinery is not general; it is constructed to * meet the needs of xdr and rpc based on tcp. */ #define LAST_FRAG ((u_int32_t)(1 << 31)) typedef struct rec_strm { XDR *xdrs; char *tcp_handle; /* * in-coming bits */ int (*readit) (XDR *, void *, void *, int); u_int32_t in_size; /* fixed size of the input buffer */ char *in_base; char *in_finger; /* location of next byte to be had */ char *in_boundry; /* can read up to this location */ int32_t fbtbc; /* fragment bytes to be consumed */ int32_t offset; bool last_frag; u_int recvsize; uint64_t cksum; uint32_t cklen; bool in_haveheader; u_int32_t in_header; int in_maxrec; } RECSTREAM; static u_int fix_buf_size(u_int); static bool fill_input_buf(RECSTREAM *, int32_t); static bool get_input_bytes(RECSTREAM *, char *, int32_t, int32_t); static bool set_input_fragment(RECSTREAM *, int32_t); static bool skip_input_bytes(RECSTREAM *, long); static void compute_buffer_cksum(RECSTREAM *); /* * Create an xdr handle for xdrrec * xdr_inrec_create fills in xdrs. Sendsize and recvsize are * send and recv buffer sizes (0 => use default). * tcp_handle is an opaque handle that is passed as the first parameter to * the procedures readit and writeit. Readit and writeit are read and * write respectively. They are like the system * calls expect that they take an opaque handle rather than an fd. */ void xdr_inrec_create(XDR *xdrs, u_int recvsize, void *tcp_handle, /* like read, but pass it a tcp_handle, not sock */ int (*readit) (XDR *, void *, void *, int)) { RECSTREAM *rstrm = mem_alloc(sizeof(RECSTREAM)); rstrm->recvsize = recvsize = fix_buf_size(recvsize); rstrm->in_base = mem_alloc(recvsize); /* * now the rest ... */ xdrs->x_ops = &xdr_inrec_ops; xdrs->x_lib[0] = NULL; xdrs->x_lib[1] = NULL; xdrs->x_public = NULL; xdrs->x_private = rstrm; xdrs->x_data = NULL; xdrs->x_base = NULL; xdrs->x_flags = XDR_FLAG_CKSUM; rstrm->xdrs = xdrs; rstrm->tcp_handle = tcp_handle; rstrm->readit = readit; rstrm->in_size = recvsize; rstrm->in_boundry = rstrm->in_base; rstrm->in_finger = (rstrm->in_boundry += recvsize); rstrm->fbtbc = 0; rstrm->last_frag = true; rstrm->in_haveheader = false; rstrm->offset = 0; rstrm->cksum = 0; rstrm->cklen = 256; } /* Compute 64-bit checksum of the first cnt bytes (or offset, whichever is * less) in the receive buffer. Use only as directed. */ uint64_t xdr_inrec_cksum(XDR *xdrs) { RECSTREAM *rstrm = (RECSTREAM *) (xdrs->x_private); /* handle checksumming if requested (short request case) */ if (xdrs->x_flags & XDR_FLAG_CKSUM) { if (!(rstrm->cksum)) { if (rstrm->cklen) compute_buffer_cksum(rstrm); } } return (rstrm->cksum); } /* * The routines defined below are the xdr ops which will go into the * xdr handle filled in by xdr_inrec_create. */ static bool xdr_inrec_getlong(XDR *xdrs, long *lp) { RECSTREAM *rstrm = (RECSTREAM *) (xdrs->x_private); int32_t *buflp = (int32_t *) (void *)(rstrm->in_finger); int32_t mylong; /* first try the inline, fast case */ if ((rstrm->fbtbc >= sizeof(int32_t)) && ((PtrToUlong(rstrm->in_boundry) - PtrToUlong(buflp)) >= sizeof(int32_t))) { *lp = (long)ntohl((u_int32_t) (*buflp)); rstrm->fbtbc -= sizeof(int32_t); rstrm->in_finger += sizeof(int32_t); } else { if (!xdr_inrec_getbytes (xdrs, (char *)(void *)&mylong, sizeof(int32_t))) return (false); *lp = (long)ntohl((u_int32_t) mylong); } return (true); } static bool xdr_inrec_putlong(XDR *xdrs, const long *lp) { return (false); } static bool xdr_inrec_getbytes(XDR *xdrs, char *addr, u_int len) { RECSTREAM *rstrm = (RECSTREAM *) (xdrs->x_private); int current; while (len > 0) { current = (int)rstrm->fbtbc; if (current == 0) { if (rstrm->last_frag) return (false); if (!set_input_fragment(rstrm, INT_MAX)) return (false); continue; } current = (len < current) ? len : current; if (!get_input_bytes(rstrm, addr, current, INT_MAX)) return (false); addr += current; rstrm->fbtbc -= current; len -= current; /* handle checksumming if requested */ if (xdrs->x_flags & XDR_FLAG_CKSUM) { if (rstrm->cklen) { if (!(rstrm->cksum)) { if (rstrm->offset >= rstrm->cklen) compute_buffer_cksum(rstrm); } } } } return (true); } static bool xdr_inrec_putbytes(XDR *xdrs, const char *addr, u_int len) { return (false); } static u_int xdr_inrec_getpos(XDR *xdrs) { RECSTREAM *rstrm = (RECSTREAM *) xdrs->x_private; off_t pos; switch (xdrs->x_op) { case XDR_DECODE: pos = rstrm->in_boundry - rstrm->in_finger - BYTES_PER_XDR_UNIT; break; default: /* XXX annoys Coverity */ pos = (off_t) -1; break; } return ((u_int) pos); } static bool xdr_inrec_setpos(XDR *xdrs, u_int pos) { RECSTREAM *rstrm = (RECSTREAM *) xdrs->x_private; u_int currpos = xdr_inrec_getpos(xdrs); int delta = currpos - pos; char *newpos; if ((int)currpos != -1) switch (xdrs->x_op) { case XDR_DECODE: newpos = rstrm->in_finger - delta; if ((delta < (int)(rstrm->fbtbc)) && (newpos <= rstrm->in_boundry) && (newpos >= rstrm->in_base)) { rstrm->in_finger = newpos; rstrm->fbtbc -= delta; return (true); } break; case XDR_ENCODE: case XDR_FREE: break; } return (false); } bool xdr_inrec_readahead(XDR *xdrs, u_int maxfraglen) { RECSTREAM *rstrm; int current; rstrm = (RECSTREAM *) xdrs->x_private; current = (int)rstrm->fbtbc; if (current == 0) { if (rstrm->last_frag) return (false); if (!set_input_fragment(rstrm, maxfraglen)) return (false); } return (true); } static int32_t * xdr_inrec_inline(XDR *xdrs, u_int len) { RECSTREAM *rstrm = (RECSTREAM *) xdrs->x_private; int32_t *buf = NULL; switch (xdrs->x_op) { case XDR_DECODE: if ((len <= rstrm->fbtbc) && ((rstrm->in_finger + len) <= rstrm->in_boundry)) { buf = (int32_t *) (void *)rstrm->in_finger; rstrm->fbtbc -= len; rstrm->in_finger += len; } break; case XDR_ENCODE: case XDR_FREE: break; } return (buf); } static void xdr_inrec_destroy(XDR *xdrs) { RECSTREAM *rstrm = (RECSTREAM *) xdrs->x_private; mem_free(rstrm->in_base, rstrm->recvsize); mem_free(rstrm, sizeof(RECSTREAM)); } /* * Exported routines to manage xdr records */ /* * Before reading (deserializing from the stream), one should always call * this procedure to guarantee proper record alignment. */ bool xdr_inrec_skiprecord(XDR *xdrs) { RECSTREAM *rstrm = (RECSTREAM *) (xdrs->x_private); while (rstrm->fbtbc > 0 || (!rstrm->last_frag)) { if (!skip_input_bytes(rstrm, rstrm->fbtbc)) return (false); rstrm->fbtbc = 0; if ((!rstrm->last_frag) && (!set_input_fragment(rstrm, INT_MAX))) return (false); } rstrm->last_frag = false; rstrm->offset = 0; rstrm->cksum = 0; return (true); } /* * Look ahead function. * Returns true iff there is no more input in the buffer * after consuming the rest of the current record. */ bool xdr_inrec_eof(XDR *xdrs) { RECSTREAM *rstrm = (RECSTREAM *) (xdrs->x_private); while (rstrm->fbtbc > 0 || (!rstrm->last_frag)) { if (!skip_input_bytes(rstrm, rstrm->fbtbc)) return (true); rstrm->fbtbc = 0; if ((!rstrm->last_frag) && (!set_input_fragment(rstrm, INT_MAX))) return (true); } if (rstrm->in_finger == rstrm->in_boundry) return (true); return (false); } static bool fill_input_buf(RECSTREAM *rstrm, int32_t maxreadahead) { char *where; u_int32_t i; int len; where = rstrm->in_base; i = (u_int32_t) (PtrToUlong(rstrm->in_boundry) % BYTES_PER_XDR_UNIT); where += i; len = MIN(((u_int32_t) (rstrm->in_size - i)), maxreadahead); len = (*(rstrm->readit)) (rstrm->xdrs, rstrm->tcp_handle, where, len); if (len == -1) return (false); rstrm->in_finger = where; where += len; rstrm->in_boundry = where; /* cksum lookahead */ rstrm->offset += len; return (true); } static bool get_input_bytes(RECSTREAM *rstrm, char *addr, int32_t len, int32_t maxreadahead) { int32_t current; while (len > 0) { current = (PtrToUlong(rstrm->in_boundry) - PtrToUlong(rstrm->in_finger)); if (current == 0) { if (!fill_input_buf(rstrm, maxreadahead)) return (false); continue; } current = (len < current) ? len : current; memmove(addr, rstrm->in_finger, current); rstrm->in_finger += current; addr += current; len -= current; } return (true); } static bool set_input_fragment(RECSTREAM *rstrm, int32_t maxreadahead) { u_int32_t header; if (!get_input_bytes (rstrm, (char *)(void *)&header, sizeof(header), maxreadahead)) return (false); header = ntohl(header); rstrm->last_frag = ((header & LAST_FRAG) == 0) ? false : true; /* * Sanity check. Try not to accept wildly incorrect * record sizes. Unfortunately, the only record size * we can positively identify as being 'wildly incorrect' * is zero. Ridiculously large record sizes may look wrong, * but we don't have any way to be certain that they aren't * what the client actually intended to send us. */ if (header == 0) return (false); rstrm->fbtbc = header & (~LAST_FRAG); return (true); } static bool skip_input_bytes(RECSTREAM *rstrm, long cnt) { u_int32_t current; while (cnt > 0) { current = (size_t) (PtrToUlong(rstrm->in_boundry) - PtrToUlong(rstrm->in_finger)); if (current == 0) { if (!fill_input_buf(rstrm, INT_MAX)) return (false); continue; } current = (u_int32_t) ((cnt < current) ? cnt : current); rstrm->in_finger += current; cnt -= current; } return (true); } static u_int fix_buf_size(u_int s) { if (s < 100) s = 4000; return (RNDUP(s)); } static void compute_buffer_cksum(RECSTREAM *rstrm) { #if 1 /* CithHash64 is -substantially- faster than crc32c from FreeBSD * SCTP, so prefer it until fast crc32c bests it */ rstrm->cksum = CityHash64WithSeed(rstrm->in_base, MIN(rstrm->cklen, rstrm->offset), 103); #else rstrm->cksum = calculate_crc32c(0, rstrm->in_base, MIN(rstrm->cklen, rstrm->offset)); #endif } static bool xdr_inrec_noop(void) { return (false); }
fe2d1d4f5549898141aed615d4e1246666572ebe
[ "C", "Makefile", "CMake" ]
45
C
sswen/ntirpc
6f8802799a1f487c9fdda379ccf3ad9ef074b68e
50091056829af6761c094b769541e9d3975eb98f
refs/heads/master
<file_sep>import abc import ast import pep8 import re import sys import StringIO from optparse import OptionParser from pyflakes import checker as flakeschecker class ErrTypes(object): pass ERROR = ErrTypes() WARNING = ErrTypes() STYLE = ErrTypes() class Message(object): def __init__(self, err_type, err_code, line, message, col=0): self.err_type = err_type self.err_code = err_code self.line = line self.message = message class PyChecker(object): """Abstract base class for python code checkers.""" __metacls__ = abc.ABCMeta @abc.abstractmethod def check(self, name, content): """Performs the actual check. name: A buffer name content: the content to check. returns a list of messages instances """ pass class Pep8Checker(PyChecker): """A checker for the Pep8.""" def __init__(self): # TODO: make this configurable pep8.options = OptionParser() pep8.options.count = 1 pep8.options.select = [] pep8.options.ignore = [] pep8.options.show_source = False pep8.options.show_pep8 = False pep8.options.quiet = 0 pep8.options.repeat = True pep8.options.verbose = 0 pep8.options.counters = dict.fromkeys(pep8.BENCHMARK_KEYS, 0) pep8.options.physical_checks = pep8.find_checks('physical_line') pep8.options.logical_checks = pep8.find_checks('logical_line') pep8.options.messages = {} def check(self, name, content): lines = ['%s\n' % line for line in content.split('\n')] old_stderr, sys.stderr = sys.stderr, StringIO.StringIO() old_stdout, sys.stdout = sys.stdout, StringIO.StringIO() try: pep8.Checker(name, lines=lines).check_all() except: pass finally: sys.stderr, err_result = old_stderr, sys.stderr sys.stdout, result = old_stdout, sys.stdout result.seek(0) pep8regexpr = r'([^:]*):(\d*):(\d*): (\w\d*) (.*)' errors = sorted([re.match(pep8regexpr, line) for line in result.readlines() if line], key=lambda x: x.group(2)) for match in errors: lineno = int(match.group(2)) text = match.group(5) col = int(match.group(3) or -1) err_type = match.group(4) yield Message(STYLE, err_type, lineno, text, col=col) class PyFlakesChecker(PyChecker): """A pyflakes checker.""" def check(self, name, content): old_stderr, sys.stderr = sys.stderr, StringIO.StringIO() content = content + '\n' try: tree = ast.parse(content, name) except: try: value = sys.exc_info()[1] lineno, offset, line = value[1][1:] except IndexError: lineno, offset, line = 1, 0, '' yield Message(ERROR, 'E', lineno, str(value), offset) else: messages = flakeschecker.Checker(tree, name).messages for w in messages: yield Message(ERROR, 'E', w.lineno, '%s' % (w.message % w.message_args), getattr(w, 'col', 0)) finally: sys.stderr = old_stderr <file_sep>import os from gi.repository import GObject, Gedit, Gtk, GdkPixbuf from .checkers import Pep8Checker, PyFlakesChecker from . import checkers UI_XML = """<ui> <menubar name="MenuBar"> <menu name="ToolsMenu" action="Tools"> <placeholder name="ToolsOps_3"> <menuitem name="Pep8ConformanceCheckAction" action="Pep8ConformanceCheckAction"/> </placeholder> </menu> </menubar> </ui>""" class Pep8Plugin(GObject.Object, Gedit.WindowActivatable): __gtype_name = 'Pep8Plugin' window = GObject.property(type=Gedit.Window) def __init__(self): super(Pep8Plugin, self).__init__() self.handlers = [] def do_activate(self): # TODO: make this configurable self.checkers = [Pep8Checker(), PyFlakesChecker()] self.init_ui() handler = self.window.connect("tab-added", self.on_tab_added) handler = self.window.connect("active-tab-changed", self.on_tab_added) self.handlers.append((self.window, handler)) [self._watch_doc(doc) for doc in self.window.get_documents()] def on_tab_added(self, window, tab, data=None): self._watch_doc(tab.get_document()) def _watch_doc(self, doc): handler = doc.connect("save", self.on_document_save) handler = doc.connect("loaded", self.on_document_save) self.handlers.append((doc, handler)) def do_deactivate(self): self.remove_ui() for obj, handler in self.handlers: obj.disconnect(handler) def do_update_states(self): pass def remove_ui(self): manager = self.window.get_ui_manager() manager.remove_ui(self._ui_merge_id) manager.remove_action_group(self._actions) manager.ensure_update() def init_ui(self): self._init_menu() self._init_error_list() def _init_menu(self): manager = self.window.get_ui_manager() self._actions = Gtk.ActionGroup('Pep8Actions') self._actions.add_actions([ ('Pep8ConformanceCheckAction', Gtk.STOCK_INFO, 'Check pep8 conformance', None, 'Check pep8 conformance of the current document', self.check_all)]) manager.insert_action_group(self._actions) self._ui_merge_id = manager.add_ui_from_string(UI_XML) manager.ensure_update() def _init_error_list(self): self.error_list = ErrorListView() icon = Gtk.Image.new_from_stock(Gtk.STOCK_YES, Gtk.IconSize.MENU) panel = self.window.get_side_panel() sw = Gtk.ScrolledWindow() sw.add(self.error_list) self.error_list.connect("row-activated", self.on_row_click) panel.add_item(sw, "Pep 8 conformance", "Pep8 conformance", icon) panel.activate_item(sw) self.error_list.show_all() def on_document_save(self, document, *args, **kwargs): lang = document.get_language() if lang and lang.get_name() == 'Python': self.check_all(None) def check_all(self, action, data=None): self.error_list.clear() name, content = self._get_all_text() for checker in self.checkers: for message in checker.check(name, content): self.error_list.append_message(message) def _get_all_text(self): view = self.window.get_active_view() if view: doc = self.window.get_active_document() begin = doc.get_iter_at_line(0) end = doc.get_iter_at_line(doc.get_line_count()) content = view.get_buffer().get_text(begin, end, False) name = view.get_buffer().\ get_short_name_for_display() return name, content def on_row_click(self, tree_view, path, view=None): doc = self.window.get_active_document() lineno = self.error_list.props.model[path.get_indices()[0]] line_iter = doc.get_iter_at_line(lineno[2] - 1) self.window.get_active_view().get_buffer().place_cursor(line_iter) self.window.get_active_view().scroll_to_iter( line_iter, 0, False, 0, 0.3) class ErrorListView(Gtk.TreeView): def __init__(self): super(ErrorListView, self).__init__() self.set_model(Gtk.ListStore(GdkPixbuf.Pixbuf, # type GObject.TYPE_STRING, # code GObject.TYPE_INT, # line GObject.TYPE_STRING)) # message self.set_headers_visible(True) type_column = Gtk.TreeViewColumn('type') typecell = Gtk.CellRendererPixbuf() type_column.pack_start(typecell, False) self.append_column(type_column) type_column.add_attribute(typecell, "pixbuf", 0) code_column = Gtk.TreeViewColumn('code') codecell = Gtk.CellRendererText() code_column.pack_start(codecell, False) self.append_column(code_column) code_column.add_attribute(codecell, "text", 1) self.set_common_column_properties(code_column, 1) lineno_column = Gtk.TreeViewColumn('Line') lineno_cell = Gtk.CellRendererText() lineno_column.pack_start(lineno_cell, False) self.append_column(lineno_column) lineno_column.add_attribute(lineno_cell, "text", 2) self.set_common_column_properties(lineno_column, 2) message_column = Gtk.TreeViewColumn('Message') message_cell = Gtk.CellRendererText() message_column.pack_start(message_cell, False) self.append_column(message_column) message_column.add_attribute(message_cell, "text", 3) self.set_common_column_properties(message_column, 3) self._icons = { checkers.ERROR: self._get_icon_as_pixbuf('dialog-error'), checkers.WARNING: self._get_icon_as_pixbuf('dialog-warning'), checkers.STYLE: self._get_icon_as_pixbuf('dialog-information') } def _get_icon_as_pixbuf(self, icon): return Gtk.IconTheme.load_icon(Gtk.IconTheme.get_default(), icon, 16, 0) def set_common_column_properties(self, column, idx): column.set_resizable(True) column.set_reorderable(True) column.set_sort_column_id(idx) def append_message(self, message): self.props.model.append(( self._icons[message.err_type], message.err_code, message.line, message.message)) def clear(self): self.props.model.clear()
61b3363733cab93f9907fdff59327594423ad2eb
[ "Python" ]
2
Python
sfriesel/Gedit-checkpython
2feea693a8e4e9699ec1b1ee04678db59e8719e6
64b1a282c25c56000d26a2323e03639daae8b61c
refs/heads/master
<file_sep>//const rollbutton = document.querySelector("#roll-button"); //const dieRolls = [] //let roll = document.querySelector("#num-of-dice"); //rollbutton.addEventListener("click"), function () { let cube = document.querySelector("#cube") let text = document.querySelector("#num-of-dice") let rollbutton = document.querySelector("#roll-button") let totalofall = document.querySelector("#total") let showbutton = document.querySelector("#showalldice") let oderlist = document.querySelector("ol") let dieRoll = [] let show = document.querySelector("#olist") let resetbutton = document.querySelector("#reset-button") let red_imagebutton = document.querySelector("redimage") let numofsides = document.querySelector("#num-of-side") let enterside = document.querySelector("#side-button") // var img = document.getElementById("cube") //ctx.drawImage(img, 5, 5); //this.angle = 0 //}; function getRandom() { var randomdie = Math.floor((Math.random() * numofsides.value) + 1); return randomdie; } //function sum(dieRoll) { // return dieRoll[0] + dieRoll[1] + dieRoll[2] + // dieRoll[3] + dieRoll[4] + dieRoll[5] //} function total1() { let totals = 0; for (let i = 0; i < dieRoll.length; i++) totals += dieRoll[i]; } enterside.addEventListener("click", function () { let last = numofsides.value console.log(last) }) rollbutton.addEventListener("click", function () { console.log("roll the die") let x = text.value; console.log(x) let counter = 0 while (counter < x) { var rand = getRandom(); dieRoll.push(rand) counter += 1; } console.log(dieRoll); var sum = dieRoll.reduce(function (a, b) { return a + b; }, 0); console.log(sum); tot.innerHTML = Number(sum); }) //https://www.tutorialrepublic.com/faq/how-to-find-the-sum-of-an-array-of-numbers-in-javascript.php showbutton.addEventListener("click", function () { let numrolled = dieRoll counter = 0 i = 0 let newval = [] while (counter < dieRoll.length) { let p = dieRoll[i]; newval.push(p) i++; counter++ } console.log(newval); dieRoll = [] show.innerHTML = "<ol><li>" + newval.join('</li><li>') + "</li></ol>"; // let newDice = newval; // show.innerHTML = '<li class="ol">' + newDice. + '</li>' }) resetbutton.addEventListener("click", function () { tot.innerHTML = ""; show.innerHTML = ""; text.value = ""; numofsides.value = ""; }) rollbutton.addEventListener("click", function () { var cube = document.getElementById('cube'); var min = 1; var max = 24; rollbutton.onclick = function () { var xRand = getRandom(max, min); var yRand = getRandom(max, min); cube.style.webkitTransform = 'rotateX(' + xRand + 'deg) rotateY(' + yRand + 'deg)'; cube.style.transform = 'rotateX(' + xRand + 'deg) rotateY(' + yRand + 'deg)'; function getRandom(max, min) { return (Math.floor(Math.random() * (max - min)) + min) * 90; } } })
2d3ff59a393080bf474df058fd7fbe5f6bb9fa0b
[ "JavaScript" ]
1
JavaScript
Amisha82/ready_to_roll
a969d77a9d2f88dc00e55829884f6565e2fbdc2c
4e7e676befba1505dfd7c9bf636286cc968f0ec3
refs/heads/main
<repo_name>koushikruidas/RESTful-Spring-Application<file_sep>/src/main/java/com/koushik/MDM/controller/SystemController.java package com.koushik.MDM.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("/systems") public class SystemController { @GetMapping("/home") public String sys() { return "admin-page"; } } <file_sep>/src/main/java/com/koushik/MDM/controller/DisplayList.java package com.koushik.MDM.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import com.koushik.MDM.entity.Customer; import com.koushik.MDM.services.CustomerService; @Controller @RequestMapping("/display") public class DisplayList { @Autowired private CustomerService customerService; @RequestMapping("/showName") public String showName(Model model) { List<Customer> customers = customerService.getCustomers(); model.addAttribute("customerList", customers); return "show-customer-list"; } @RequestMapping("/addCustomer") public String addCustomer(Model model) { Customer cust = new Customer(); model.addAttribute("customer-details", cust); return "add-customer"; } @RequestMapping("/saveCustomer") public String saveCustomer(@ModelAttribute("customer-details") Customer customer, BindingResult theBindingResult) { customerService.saveCustomer(customer); return "redirect:/"; } }
15713c4e00df125b457065d61bea7f47de5e2c40
[ "Java" ]
2
Java
koushikruidas/RESTful-Spring-Application
e8e50e561856bbf98d028456821146b143d99478
dc4809c233fed6ce0ca7309364d33a3ecd517522
refs/heads/master
<repo_name>code-s-witch/Compilation-C-Java-MIPS-Python-<file_sep>/ASCII to 2sC in MIPS/README.txt ------------------------ Lab 4: ASCII Decimal to 2SC CMPE 012 Fall 2018 <NAME> sumorin ------------------------- Specification: 1.Read two program arguments: signed decimal numbers [-64, 63]. 2.Print the user inputs. 3.Convert the ASCII strings into two sign-extended integer values. a.Convert the first program argument to a 32-bit two’s complement number,stored in register $s1. b.Convert the second program argument to a 32-bit two’s complement number,stored in register $s2. 4.Add the two integer values, store the sum in $s0. 5.Print the sum as a decimal to the console. 6.Print the sumas 32-bit two’s complement binary number to the console. 7.(Extra credit) Print the sum as a decimal number expressed in Morse code. a.Use a period (ASCII code 0x2E) for “dots” and a hyphen (ASCII code 0x2D)for “dashes”. b.Insert a space (ASCII code 0x20) between characters. <file_sep>/Queue in Java/README.markdown *Brief description of submitted files:* **src/cs1c/MillionSongDataSubset.java** - One object of class MillionSongDataSubset parses a JSON data set and stores each entry in an array. **src/cs1c/SongEntry.java** - One object of class SongEntry stores a simplified version of the genre data set from the Million Song Dataset. **src/cs1c/TimeConverter.java** - Converts duration into a string representation. **src/queues/Jukebox.java** - The class Jukebox manages three objects of type Queue. An instance of the class may read a file which includes the user's requests for a the name of a song to be added to a specific playlist. It will then add songs to the three playlists "favorites", "lounge", and "road trip" accordingly. **src/queues/MyTunes.java** - Creates an object of type MyTunes which simulates a playlist queue. Enqueues and dequeues SongEntry objects from each playlist. Simulates playing each song and finally checks the state of each playlist. **src/queues/Queue.java** - Objects of type Queue manage items in a singly linked list where we can enqueue() items to the end and dequeue() items from the front of the queue. **RUN.txt** - console output of MyTunes.java Additional Cases: - Song_Not_Found.txt - tests for song not found - Playlist_Not_Found.txt - tests for playlist not found **README.markdown** - description of submitted files <file_sep>/JAVAFX GUI/README.txt project folder: team08-project09/ Brief description of submitted files: src/view/ChartGraph - Main application Instantiates an JavaFX application which creates a GraphPane(that extends BorderPane). - Sets up the scene with basic modification to the stage. - Includes main() for running the application. src/view/GraphPane -A class that represents the BorderPane with top and left menus and center to graph data. src/view/CountrySelector - A class that generates a linked list of country objects from the list of requested country names. src/view/BarGraphView - A class that creates a bar graph. src/view/LineGraphView - A class that creates a line graph. src/view/Icon.png - icon for the stage lib/controlsfx-8.40.12.jar - library used for combo check boxes lib/jfxrt.jar - javafx library src/DataModel - A class that provides access to CSV data and returns an array of objects that contain all data. src/cellularData/ICVReader.java - interface that provides methods for CSVReader classes. src/cellularData/CVReader.java - Reads the cellular data CSV file and parses it - stores year labels in the array of integers - stores country names in the linked list of strings - stores cellular data in the linked list of arrays of doubles src/cellularData/NewCVReader.java - Reads the human development CSV file and parses it - stores year labels in the array of integers - stores country names in the linked list of strings - stores cellular data in the linked list of arrays of doubles src/cellularData/LinkedList.java - Generic Linked List - Keeps track of generic Node objects src/cellularData/Node.java - Holds data for one generic node in a data structure. src/cellularData/Country.java - One object of class represents one country. - Stores country name and a Linked List with the YearData objects. - Calculates the number of subscriptions data for given range of years src/cellularData/YearData.java - One object of class represents one year of data - Stores the year of the data and the data for that year. resources/cellular.csv - A CSV (Comma Separated Value) file. - First row contains the title. - Second row contains number of countries. - Third row contains years for with subscription information is available in the format: Country Name,year,year,year - Lines 4 to EOF (end of file) contain name of the country and number of subscriptions in the format: country name,number of subscriptions,number of subscriptions,number of subscriptions resources/humandevelopment.csv - A CSV (Comma Separated Value) file. - First row contains the title. - Second row contains years for with data is available in the format: HDI Rank (2015),Country,year,year,year - Lines 3 to EOF (end of file) contain country rank, name of the country and data in the format: rank,country name,data,data,data resources/project_proposal.md - description of the project features resources/storyboard1.png resources/storyboard2.png - pictures of the proposed GUI features resources/style.css - styles for the graphs resources/task.md - description of the work to be done and who did it resources/RUN.png - screen of the output README.txt - description of submitted files<file_sep>/Stacks in Java/README.markdown *Brief description of submitted files:* **src/stacks/BrowserNavigation.java** * tester class simulates a browser's back and forward buttons by recording links that are visited and then keeping a stack of "back" links and a stack of "forward" links. **src/stacks/Navigator.java** * Navigator Object can Set the current link via setCurrentLink(linkName) method, replace the current link by going back one link via goBack() method and replace the current link by going forward one link via goForward() method. **src/stacks/StackList.java** * linked list keeps track of the current link, back link, and forward link by using stack operations like push(), pop() and peek() **RUN.txt** * console output of BrowserNavigation.java * includes the run of links2.txt (additional file than provided) **README.markdown** * description of submitted files <file_sep>/Graph Module in C/List.c //----------------------------------------------------------------------------- // List.c //ADT class that manages a doubly linked list with a cursor that is used to insert an element before/after to help in // indirectly sorting a list of strings by using the indices of the list. //----------------------------------------------------------------------------- //sumorin #include<stdio.h> #include<stdlib.h> #include "List.h" // // private types -------------------------------------------------------------- // NodeObj typedef struct NodeObj{ int data; struct NodeObj* prev; struct NodeObj* next; } NodeObj; // Node typedef NodeObj* Node; //ListObj typedef struct ListObj{ Node front; Node back; Node cursor; int length; int index; } ListObj; // constructor of the Node type Node newNode(int data_param) { Node N = malloc(sizeof(NodeObj)); // assert(N!=NULL); N->data = data_param; N->prev = NULL; N->next = NULL; return(N); } // freeNode() // destructor for the Node type void freeNode(Node* pN){ if( pN!=NULL && *pN!=NULL ){ free(*pN); *pN = NULL; } } // Constructors-Destructors --------------------------------------------------- //Constructor //Creates a new empty list. List newList(void){ List L; L = malloc(sizeof(ListObj)); L->front = L->back = NULL; L->length = 0; L->index = -1; return(L); } // frees all heap memory associated with its List* argument, // and sets *pL to NULL void freeList(List *pL){ //when you call this method from Lex use freeList(&L ) if(pL!=NULL && *pL!=NULL) { clear(*pL); free(*pL); *pL = NULL; } } // Access functions ----------------------------------------------------------- // Access functions // Returns the number of elements in this List int length(List L){ if( L == NULL ){ printf("List Error: calling length() on empty List reference\n"); // exit(1); } return(L->length); } // If cursor is defined, returns the index of the cursor element, // otherwise returns -1. int index(List L){ // if(L->cursor == NULL){ // L->index = -1; // } if (L == NULL){ printf("List Error: calling index() on empty List reference\n"); exit(1); } return (L->index); } void setIndex(List L, int index){ L->index = index; } // Returns front element. Pre: length()>0 int front(List L){ if (L->length <= 0){ printf("List Error: calling front() on empty List reference\n"); exit(1); } return (L->front->data); } // Returns back element. Pre: length()>0 int back(List L){ if (L->length <= 0){ printf("List Error: calling back() on empty List reference\n"); exit(1); } return (L->back->data); } // Returns cursor element. Pre: length()>0, index()>=0 int get(List L){ if (L->length<= 0 || L->index < 0){ printf("List Error: calling get() on empty List reference\n"); exit(1); } return L->cursor->data; } // Returns true if and only if this List and L are the same // integer sequence. The states of the cursors in the two Lists // are not used in determining equality. int equals(List A, List B){ int eq = 0; Node N = NULL; Node M = NULL; if( A==NULL || B==NULL ){ printf("List Error: calling equals() on NULL List reference\n"); exit(1); } eq = ( A->length == B->length ); N = A->front; M = B->front; while( eq && N!=NULL){ eq = (N->data==M->data); N = N->next; M = M->next; } return eq; } // Manipulation procedures ---------------------------------------------------- // Resets this List to its original empty state. void clear(List L){ while(length(L) > 0){ deleteFront(L); } L->index = -1; L->length = 0; L->front = NULL; L->back = NULL; L->cursor = NULL; } // If List is non-empty, places the cursor under the front element, // otherwise does nothing. void moveFront(List L){ if( L == NULL ){ printf("List Error: calling moveFront() on NULL List reference\n"); exit(1); } // if( length(L) == 0 ){ // printf("List Error: calling moveFront() on an empty List \n"); // } if (L->length > 0) { L->cursor = L->front; L->index = 0; } } // If List is non-empty, places the cursor under the back element, // otherwise does nothing. void moveBack(List L){ if (L->length > 0) { L->cursor = L->back; L->index = L->length -1; } } // If cursor is defined and not at front, moves cursor one step toward // front of this List, if cursor is defined and at front, cursor becomes // undefined, if cursor is undefined does nothing. void movePrev(List L){ //valid place to move the cursor if (L->index > 0) { L->cursor = L->cursor->prev; L->index--; }else if (L->index == 0) { //runs off the edge L->cursor = NULL; L->index = -1; } } // If cursor is defined and not at back, moves cursor one step toward // back of this List, if cursor is defined and at back, cursor becomes // undefined, if cursor is undefined does nothing. void moveNext(List L){ if (L->index < L->length - 1) { L->cursor = L->cursor->next; L->index++; } else if (L->index == L->length - 1) { //about to run off the edge L->cursor = NULL; L->index = -1; } } // Insert new element into this List. If List is non-empty, // insertion takes place before front element. void prepend(List L, int data){ Node N = newNode(data); if( L ==NULL ){ printf("List Error: calling prepend() on NULL List reference\n"); exit(1); } if( length(L)<= 0 ) { L->front = L->back = N; }else{ L->front->prev = N; N->next = L->front; L->front = N; if(L->index != -1){ L->index++; } } L->length++; } // Insert new element into this List. If List is non-empty, // insertion takes place after back element. void append(List L, int data){ Node N = newNode(data); if( L ==NULL ){ printf("List Error: calling append() on NULL List reference\n"); // exit(1); } if( length(L)<= 0 ) { L->front = L->back = N; }else{ L->back->next = N; N->prev = L->back; L->back = N; } L->length++; } // Insert new element before cursor. // Pre: length()>0, index()>=0 void insertBefore(List L, int data){ if(L->length <= 0 || L->index < 0){ printf("List Error: calling insertBefore() on empty List reference\n"); exit(1); } Node N = newNode(data); if (L->index == 0) { N->next = L->cursor; L->cursor->prev = N; L->front = N; } else { Node temp = L->cursor->prev; //store temp and we dont have to worry about order and losing info temp->next = N; N->next = L->cursor; L->cursor->prev = N; N->prev = temp; } L->length++; L->index++; } // Inserts new element after cursor. // Pre: length()>0, index()>=0 void insertAfter(List L, int data){ if(L->length <= 0 || L->index < 0){ printf("List Error: calling insertAfter() on empty List reference\n"); exit(1);; } Node N = newNode(data); if (L->index == L->length - 1) { L->cursor->next = N; N->prev = L->cursor; L->back = N; }else { Node temp = L->cursor->next; temp->prev = N; N->prev = L->cursor; L->cursor->next = N; N->next = temp; } L->length++; } // Deletes the front element. Pre: length()>0 void deleteFront(List L){ Node N = NULL; if( L==NULL ){ printf("List Error: calling deleteFront() on NULL List reference\n"); exit(1); } if( length(L) <= 0 ){ printf("List Error: calling deleteFront on an empty List\n"); exit(1); } N = L->front; if (length(L) == 1 ){ L->front = L->back = NULL; L->index--; }else{ L->front = L->front->next; L->front->prev = NULL; L->index--; } freeNode(&N); L->length--; } // Deletes the back element. Pre: length()>0 void deleteBack(List L){ Node N = NULL; if( L==NULL ){ printf("List Error: calling deleteBack() on NULL List reference\n"); exit(1); } if( length(L)<=0 ){ printf("List Error: calling deleteBack on an empty List\n"); exit(1); } N = L->back; //one node front = back if( length(L) == 1 ) { L->back = L->front = NULL; L->index=-1; }else{ L->back = L->back-> prev; L->back->next = NULL; if(index(L) == length(L) -1){ L->index=-1; } } freeNode(&N); L->length--; } // Deletes cursor element, making cursor undefined. // Pre: length()>0, index()>=0 void delete(List L){ Node N = NULL; N = L->cursor; if( L==NULL ){ printf("List Error: calling delete() on NULL List reference\n"); exit(1); } if( length(L)<= 0 && L->index < 0 ){ printf("List Error: calling delete() on an empty List\n"); exit(1); }else if (L->front == L->back) { //length == 1 L->front = L->back = NULL; L->length = 0; }else if (L->cursor == L->front) { //length <= 2 and in front L->front = L->cursor->next; L->front->prev =NULL; L->length--; }else if (L->cursor == L->back) { L->back = L->cursor->prev; L->back->next = NULL; L->length--; }else { //length >= 3 and in middle Node tempPrev = L->cursor->prev; Node tempNext = L->cursor->next; tempPrev->next = tempNext; tempNext->prev =tempPrev; L->length--; } freeNode(&N); L->cursor = NULL; //marks as undefined L->index = -1; //marks as undefined } // Other operations ----------------------------------------------------------- // prints the L to the file pointed to by out, formatted as a // space-separated string. void printList(FILE* out, List L){ Node N = NULL; if( L==NULL ){ printf("List Error: calling printList() on NULL List reference\n"); exit(1); } for(N = L->front; N != NULL; N = N->next){ fprintf(out, "%d ", N->data); } } //prints to stdout void printListStdOut(List L){ Node N = NULL; if( L==NULL ){ printf("List Error: calling printList() on NULL List reference\n"); exit(1); } for(N = L->front; N != NULL; N = N->next){ printf("%d ", N->data); } printf("\n"); } // Returns a new List representing the same integer sequence as this // List. The cursor in the new list is undefined, regardless of the // state of the cursor in this List. This List is unchanged. List copyList(List L){ List copy = newList(); if(L->length <= 0){ return(copy); }else{ for(moveFront(L); index(L)>=0; moveNext(L)){ append(copy, get(L)); } moveFront(L); return (copy); } } <file_sep>/JAVAFX GUI/cellularData/Country.java package cellularData; import java.util.Iterator; /** * Country class stores a name of the particular country and LinkedList of data. * @author <NAME>, <NAME>., Team 8 */ public class Country { private String name; // stores the name of the country private LinkedList<YearData> data; // holds all the data for that country private int minYear = 9999; private int maxYear = 0; /** * Parameter-taking constructor for creating Country object. * @param name name of the country */ public Country(String name){ this.name = name; data = new LinkedList<>(); } /** * Adds the year and the data for that year to the LinkedList * @param newYear particular year * @param newData data for particular year */ public void addYearData(int newYear, double newData) { data.add(new YearData(newYear, newData)); if(newYear < minYear){ minYear = newYear; } if(newYear > maxYear){ maxYear = newYear; } } /** * Calculates the total number of data for particular period. * @param startYear starting year of the requested period * @param endYear ending year of the requested period * @return totalNumOfSubscriptions total number of data * @throws IllegalArgumentException is thrown when years are out of range */ public double getNumSubscriptionsForPeriod(int startYear, int endYear) throws IllegalArgumentException { double totalNumOfSubscriptions = 0; int period = endYear - startYear; if(period < 0 || startYear < minYear || endYear > maxYear) { if (data.size() != 0) { totalNumOfSubscriptions = getNumSubscriptionsForPeriod(minYear, maxYear); } else { totalNumOfSubscriptions = 0; } String totalRes = String.format( "Total data between %d - %d = %.2f" , minYear, maxYear, totalNumOfSubscriptions); throw new IllegalArgumentException("Illegal Argument Request of year range " + startYear + "-" + endYear + "." + " Valid period for " + name + " is " + minYear + " to " + maxYear + ".\n" + totalRes + "\n"); } Iterator<YearData> iterator = data.iterator(); while (iterator.hasNext()) { YearData currentYear = iterator.next(); if (currentYear.getYear() >= startYear && currentYear.getYear() <= endYear) { totalNumOfSubscriptions += currentYear.getData(); } } return totalNumOfSubscriptions; } /** * The method is used to get a String object representing the value of the Country Object * @return name of country and its data */ public String toString(){ String result = ""; for(YearData currentYear: data) { result += String.format("\t%.2f", currentYear.getData()); } return this.name + ": " + result; } /** * Returns the name of the country . * @return name of country */ public String getName() { return name; } /** * Returns data of County object * @return data LinkedList of yearData */ public LinkedList<YearData> getData() { return data; } /** * Compares two Country objects. * @param o object, that we want to compare with * @return boolean */ @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Country country = (Country) o; return name != null ? name.equals(country.name) : country.name == null; } }<file_sep>/Subroutines in MIPS/README.txt ------------------------ Lab 5: Subroutines CMPE 012 Fall 2018 Specification: This program will display a string and prompt the user to type the same string in a given time limit. It will check if this string is identical to the given one and whether the user made the time limit. If the user types in the prompt incorrectly or does not finish the prompt in the given time limit, the game is over. <file_sep>/Hash Tables in Java/README.md Brief description of submitted files: **src/cs1c/MillionSongDataSubset.java** - One object of class MillionSongDataSubset parses a JSON data set and stores each entry in an array. **src/cs1c/SongEntry.java** - One object of class SongEntry stores a simplified version of the genre data set from the Million Song Dataset. **src/cs1c/TimeConverter.java** - Converts duration into a string representation. **src/hashTables/FHhasQP.java** - FHHashQP object creates a hash table and uses quadratic probing for collision resolution **src/hashTables/FHhashQPwFind.java** - Hash table that extends from FHhashQP. FhhashQPwFind object uses a find-on-key mechanism that takes in a KeyType (ie, String or Integer) and searches for the object matching that key. **src/hashTables/HashEntry.java** - HashEntry object lets the hash table know whether an element in array is occupied HashEntry acts as underlying data type for the array used in FHhashQP and derived class **src/hashTables/MyTunes.java** - Tests the functionality of FHhashQPwFind.java. Specifically checks for implementation of find() function to return an object associated with a given key input. **src/hashTables/SongCompInt.java** - SongCompInt object gives us the ability to compare a SongEntry object with an Integer ID **src/hashTables/SongCompGenre.java** - SongCompGenre gives us the ability to compare a SongEntry object with an genre name **src/hashTables/TableGenerator.java** - TableGenerator object will create and populate two hash tables of type FHhashQPwFind class, one for each wrapper class **RUN.txt** - console output of MyTunes.java **README.md** - description of submitted files <file_sep>/JAVAFX GUI/view/ChartGraph.java package view; import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.image.Image; import javafx.stage.Stage; /** * Instantiates an JavaFX application which creates a GraphPane(BorderPane). * Sets up the scene with basic modification to the stage. * @author <NAME>, <NAME>., <NAME>, <NAME>, <NAME> */ public class ChartGraph extends Application { /** * Called by launch method of Application * @param stage: Stage */ @Override public void start(Stage stage) { GraphPane bgp = new GraphPane(); Scene scene2 = new Scene(bgp, 700, 500); Image icon = new Image(getClass().getResourceAsStream("Icon.png")); stage.getIcons().add(icon); stage.setTitle("Team 8 Application"); stage.setScene(scene2); stage.show(); } /** * Launches a standalone JavaFx App */ public static void main(String[] args) { launch(); } } <file_sep>/Graph Module in C/FindComponents.c //sumorin #include<stdio.h> #include<stdlib.h> #include<string.h> #include "Graph.h" #define MAX_LEN 160 int main(int argc, char * argv[]) { FILE *in, *out; char line[MAX_LEN]; //where each line is read int u,v,n,sentinel = 0; Graph G = NULL; Graph T = NULL; List S; List L; // check command line for 2 command line arguments : // if two args: in and out are not specified program with - unsuccessfull termination if( argc != 3 ) { printf("Usage: %s <input file> <output file>\n", argv[0]); exit(1); } // open files for reading and writing in = fopen(argv[1], "r"); out = fopen(argv[2], "w"); //checks for invalid input file, if null exits program with - unsuccessfull termination if( in==NULL ) { printf("Unable to open file %s for reading\n", argv[1]); exit(1); } //checks for invalid output file, if null exits program with - unsuccessfull termination if( out==NULL ) { printf("Unable to open file %s for writing\n", argv[2]); exit(1); } int counter1 = 1; while(fgets(line, MAX_LEN, in) != NULL) { if(counter1 == 1) { //initialize a new graph of order n sscanf(line," %d", &n); G = newGraph(n); counter1++; } else { //scan line and parse it into two ints sscanf(line," %d %d", &u, &v); //check to see that we are still in pt 1 of input if(sentinel != v && sentinel != u) { //since we are still in pt 1 of input - add a directed edge from u to v addArc(G,u,v); } } } //done processing the file, so we print adjacency list printGraph(out, G); //create a list that will be in vector label sorted order {1,2,3...n} to feed into DFS S = newList(); for(int i = 1; i <= getOrder(G);i++ ){ append(S, i); } // printList(out, S); //start computing the strongly connected components of G DFS(G, S); //run DFS the first time on the adj list in vector label sorted order // fprintf(out, "here is the list after first run of DFS"); // printList(out, S); T = transpose(G); // printGraph(out, T); ///////test DFS(T, S); //run DFS the second time on the stack list from first run of DFS, the stack list from this run will be topological sorted order // fprintf(out, "here is the list after second run of DFS"); // printList(out, S); //now we start printing the connected components of G using the stack using List ADT int count =0; for(moveFront(S); index(S) != -1; moveNext(S)){ int check = get(S); if(getParent(T, check) == NIL){ count++; } } fprintf(out, "\nG contains %d strongly connected components: \n", count); int i = 0; L = newList(); //create a list to hold the strongly connected component(s) for (moveBack(S); index(S)>=0; movePrev(S)){ //start from the back of the list representing the bottom of stack //read vertices until one has a NIL as parent, then print int v = get(S); prepend(L, v); if(getParent(T, v) == NIL){ i++; //increment the number of SCC fprintf(out, "Component %d: ", i); printList(out, L); fprintf(out, "\n"); clear(L); //clear L so we can reuse it for next SCC } } //free memory freeGraph(&T); freeList(&L); freeList(&S); freeGraph(&G); //close the input/output files fclose(in); fclose(out); } <file_sep>/qickSort in Java/src/quickSort/TestQSwRecursionLimit.java //Author:sumorin package quickSort; import cs1c.TimeConverter; import cs1c.CSVFileWriter; /** * Class benchmarks quick sort algorithm on large arrays and recursion limits and generates data * that is used to make a graph and analyze optimal range of performance */ public class TestQSwRecursionLimit { static String fileName; /** * method that times QS 3 times for each array size and gives AVG elapsed time * @param arraySize takes in array size to benchmark * @return returns concatenated string to send to CSVFileWriter */ public static String benchmarkQS(int arraySize) { int limit = 2; int highBound = 300; int numberOfTests = 3; int k, randomInt; long startTime1, estimatedTime1; long startTime2, estimatedTime2; long startTime3, estimatedTime3; Integer[] originalArray = new Integer[arraySize]; Integer[] toSortArray1 = new Integer[arraySize]; Integer[] toSortArray2 = new Integer[arraySize]; Integer[] toSortArray3 = new Integer[arraySize]; FHsort fHsort = new FHsort(); // build array with randomly generated data for (k = 0; k < arraySize; k++) { randomInt = (int) (Math.random() * arraySize); originalArray[k] = randomInt; } CSVFileWriter fileWriter = null; String str = ""; setFileName("resources/" + arraySize + ".CSV"); while (limit <= highBound) { //copy original array with random values generated before sorting System.arraycopy(originalArray, 0, toSortArray1, 0, originalArray.length); System.arraycopy(originalArray, 0, toSortArray2, 0, originalArray.length); System.arraycopy(originalArray, 0, toSortArray3, 0, originalArray.length); //test1 startTime1 = System.nanoTime(); // ------------------ start fHsort.setRecursionLimit(limit); fHsort.quickSort(toSortArray1); //now we can sort the array because we saved the original copy to be used iteratively estimatedTime1 = System.nanoTime() - startTime1; // ---------------------- stop //test2 startTime2 = System.nanoTime(); // ------------------ start fHsort.setRecursionLimit(limit); fHsort.quickSort(toSortArray2); //now we can sort the array because we saved the original copy to be used iteratively estimatedTime2 = System.nanoTime() - startTime2; // ---------------------- stop //test3 startTime3 = System.nanoTime(); // ------------------ start fHsort.setRecursionLimit(limit); fHsort.quickSort(toSortArray3); //now we can sort the array because we saved the original copy to be used iteratively estimatedTime3 = System.nanoTime() - startTime3; // ---------------------- stop //take average of the 3 tests long averageEstimate = (estimatedTime1 + estimatedTime2 + estimatedTime3)/numberOfTests; System.out.println("Quick sort Elapsed Time: " + " size: " + arraySize + ", " + " recursion limit: " + limit + ", " + TimeConverter.convertTimeToString(averageEstimate) + " = " + averageEstimate + "ns"); str += limit + "," + averageEstimate + "\n"; limit +=2; } return str; } //mutator and accessor methods for global variable filename public static void setFileName(String str){ fileName = str; } public static String getFileName(){return fileName;} // ------- main -------------- /** * test file that creates arrays of variable sizes (and random generated data) with recursion limit ranging 2-300 then * calls on benchmarking feature to time performance * @param args * @throws Exception if there's an error within CSFFileWriter */ public static void main(String[] args) throws Exception { final int [] ARRAY_SIZES = new int [20]; //sets the 20 intervals with 500K width of interval (rounded up from 499K for better readability) //array of sizes for(int j = 20000, i = 0; j < 10000000; i++, j+=500000){ ARRAY_SIZES[i] = j; } //goes through the list of sizes for (int test = 0; test < ARRAY_SIZES.length; test++) { int currentSize = ARRAY_SIZES[test]; String str = null; str = benchmarkQS(currentSize); CSVFileWriter.writeCsvFile(str,getFileName()); } } } <file_sep>/Graph Module in C/Graph.c //sumorin #include<stdio.h> #include<stdlib.h> #include "Graph.h" //GraphObj typedef struct GraphObj { List *adjList; //whose ith element contains the neighbors of vertex i int *color; //whose ith element is the color (white, gray, black) of vertex i, white = 1, grey=2, black = 3 int *parent; // whose ith element is the parent of vertex i int *distance; //whose ith element is the distance from the (most recent) source to vertex i. int order; //number of vertices aka order of graph int size; //number of edges aka size of the graph int label; //label of vertex most recently used in BFS - undefined is NIL int *discover; //those ith element is the discovery time int *finish; //whose ith element is the finish time int Flag; int time; } GraphObj; /*** Constructors-Destructors *************************************************/ //returns a Graph pointing to a newly created GraphObj representing a graph having //n vertices and no edges. Graph newGraph(int n) { // allocate memory Graph G = malloc (sizeof(GraphObj)); G->adjList = malloc( (n + 1) * sizeof(List)); G->color = malloc( (n + 1) * sizeof(int)); G->parent = malloc( (n + 1) * sizeof(int)); G->distance = malloc( (n + 1) * sizeof(int)); G->discover = malloc( (n + 1) * sizeof(int)); G->finish = malloc( (n + 1) * sizeof(int)); //initialize new graph and adjList for each vector for(int i = 1; i < n + 1; i++) { G->adjList[i] = newList(); G->color[i] = WHITE; G->parent[i] = NIL; G->distance[i] = INF; G->discover[i] = UNDEF; G->finish[i] = UNDEF; } G->order = n; G->size = 0; G->label = NIL; G->Flag = 0; G->time = 0; return (G); } //frees all dynamic memory associated with the Graph //*pG, then sets the handle *pG to NULL void freeGraph(Graph* pG) { if (pG==NULL || *pG==NULL) { printf("Graph memory is already free\n"); return; } //free lists for (int i = 1; i <= getOrder(*pG); i++) { freeList(&(*pG)->adjList[i]); } //free pointers free((*pG)->adjList); free((*pG)->color); free((*pG)->parent); free((*pG)->distance); free((*pG)->discover); free((*pG)->finish); //free dynamic memory and set graph pojnter to null free(*pG); *pG = NULL; } /*** Access functions *************************************************************/ //returns order of graph - aka number of vertices int getOrder(Graph G) { return (G->order); } //returns size of graph - aka number of edges int getSize(Graph G) { return (G->size); } //returns the source vertex most recently used in function BFS() // or NIL if BFS() has not yet been called int getSource(Graph G) { return(G->label); } //precondition:1<= u <= getOrder(G) //return the parent of vertex u in the BreadthFirst //tree created by BFS(), or NIL if BFS() has not yet been called int getParent(Graph G, int u) { if (1>u || u > getOrder(G) ) { printf("Graph Error: calling getParent() with invalid parameters\n"); exit(1); } // if(G->parent[u] == NIL) // return (NIL); return G->parent[u]; } //precondition:1<= u <= getOrder(G) //returns the distance from the most recent BFS source to vertex u, //or INF if BFS() has not yet been called int getDist(Graph G, int u) { if (1>u || u > getOrder(G)) { printf("Graph Error: calling getDist() with invalid parameters\n"); exit(1); } //returns INF if u is not reachable by s //check if BFS() has been called else if(getSource(G) == NIL){ // printf("BFS has not been called"); return INF; } return G->distance[u]; //calculates distance from the source } //precondition:1<= u <= getOrder(G) //precondition: getSource(G)!=NIL //so BFS() must be called before getPath() //u is the destination - getPath appends vertices to a list void getPath(List L, Graph G, int u) { //check to see BFS() was called if (1 > u || u > getOrder(G) ) { printf("Graph Error: calling getPath() with invalid parameters\n"); exit(1); } if(getSource(G) == NIL) { printf("Graph Error: calling getPath() before BFS()\n"); exit(1); } //Case1: source = destination if (getSource(G) == u) { append(L,u); } //Case2: recur else if (G->parent[u] != NIL) //if parent has no predecessor we cannot recur to the source { getPath(L, G, G->parent[u]); append(L,u); } //Case3: source not reachable from destination vertex else if(G->distance[u] == INF){ append(L, NIL); } } // Pre: 1<=u<=getOrder(G) int getDiscover(Graph G, int u){ if(1 > u || u > getOrder(G)){ printf("Graph Error: calling getDiscover() with invalid parameters\n"); exit(1); } // else if(G->Flag == 0){ // return UNDEF; //DFS has not been called // } return G->discover[u]; //returns discover time for vertex u } // Pre: 1<=u<=getOrder(G) int getFinish(Graph G, int u){ if(1 > u || u > getOrder(G)){ printf("Graph Error: calling getFinish() with invalid parameters\n"); exit(1); } // else if(G->Flag == 0){ // return UNDEF; //DFS has not been called // } return G->finish[u]; //returns finish time for vertex u } /*** Manipulation procedures *************************************************/ //deletes all edges of G, restoring it to its original //(no edge) state - a null graph void makeNull(Graph G) { if(G == NULL) { printf("Error: calling makeNull() on NULL graph\n"); exit(1); } //iterate through and clear all lists for(int i = 0; i < G->order; i++) { clear(G->adjList[i]); } //clears number of edges G->size = 0; } //precondition: 1<= u <= getOrder(G) //precondition: 1<= v <= getOrder(G) //inserts a new edge joining u and v void addEdge(Graph G, int u, int v) { if (u < 1 || v < 1 || u > getOrder(G) || v > getOrder(G) ) { printf("Graph Error: calling addEdge() with invalid parameters\n"); exit(1); } addArc(G,v,u); //u is added to the adjacency List of v addArc(G,u,v); //v to the adjacency List of u G->size--; } //precondition: 1<= u <= getOrder(G) //precondition: 1<= v <= getOrder(G) // inserts a new directed edge from u to v, //i.e. v is added to the adjacency List of u (but not u to the adjacency List of v) void addArc(Graph G, int u, int v) { if (u < 1 || v < 1 || u > getOrder(G) || v > getOrder(G) ) { printf("Graph Error: calling addArc() with invalid parameters\n"); exit(1); } //make a reference to a list List L = G->adjList[u]; //Case1: list is empty if(length(L) == 0) { append(L,v); G->size++; return; } //check if v > than last element if(back(L) < v){ append(L,v); G->size++; return; } //cheks if v is < than starting from the front moveFront(L); while(index(L) >= 0){ if(v < get(L)){ insertBefore(L,v); G->size++; return; }else moveNext(L); } } // runs the BFS algorithm on the Graph G with source s, setting the color, distance, parent, //and source fields of G accordingly void BFS(Graph G, int s) { //initialize the source G->label = s; if(G == NULL) { printf("Error: calling makeNull() on NULL graph\n"); exit(1); } for(int i = 1; i <= G->order; i++) { G->color[i] = WHITE; G->parent[i] = NIL; G->distance[i] = INF; } //initialize the source vertex G->color[s] = GREY; G->parent[s]= NIL; G->distance[s] = 0; //initialize queue to be empty List Queue = newList(); //will use List as a queue with append as push and pop as delete() append(Queue, s); //when the 'queue' is non empty int x; while(length(Queue) != 0) { // printf("\n\nQUEUE before dequeue: \n"); // printListStdOut(Queue); moveFront(Queue); x = get(Queue); // will get the data at the front delete(Queue); // printf("we have deleted %d and now we are discovering its neighbors: \n", x); //test // printf("QUEUE after dequeue: \n"); // printListStdOut(Queue); if(length(G->adjList[x]) == 0){ //do nothing }else{ moveFront(G->adjList[x]); //go to the front of the list of vector x //iterate through adjList for each vector x // int y = get(G->adjList[x]); //test // printf("a neighbor for%d is: %d\n",x, y); //test // printListStdOut(G->adjList[x]); //test // printf("processing adj list for vertex %d...\n", x); for(int i = 1; i <= length(G->adjList[x]); i++) { int y = get(G->adjList[x]); //y will be the vector in adj list of vector x // printf("in for loop vertex: %d\n", y); if(G->color[y] == WHITE) //if we haven't discovered y { G->color[y] = GREY; //label vector as discovered - but neighbors yet to be discovered G->distance[y] = G->distance[x] +1; G->parent[y] = x; append(Queue,y); //enqueue next vertex to the queue } // printf("QUEUE while processing adj list: \n"); // printListStdOut(Queue); moveNext(G->adjList[x]); //move down the adjList of vector x } } } G->color[x] = BLACK; //all vectors in adj list have been discovered for vector x freeList(&Queue); } // Pre: length(S)==getOrder(G) void DFS(Graph G, List S){ G->time = 0; if (length(S)!= getOrder(G)){ printf("Graph Error: calling DFS() with incompatible list length \n"); exit(1); } // printListStdOut(S); // printf("we are in the DFS function"); G->Flag =1; //for each vertex u element of vertexSet(G) initialize the color to white and parent to NIL for(int x = 1; x <= G->order; x++) { G->color[x] = WHITE; G->parent[x] = NIL; } List L = copyList(S); //move the list that will determine the order of vertices DFS processes clear(S); // clear S so that we can append finish times in decreasing order //main loop for(moveFront(L); index(L) != -1; moveNext(L)) { // printf("INSIDE DFS: before deleting the vector being discovered \n"); // printListStdOut(L); int x = get(L); //get vertex at current cursor (starting from beg of list) // printf("INSIDE DFS: current vector being discovered is: %d\n", x); // printf("INSIDE DFS: after deleting the vector being discovered \n"); // printListStdOut(L); if(G->color[x] == WHITE){ Visit(G, x, S); } } freeList(&L); } //helper function for DFS void Visit(Graph G, int x, List S){ // printf("INSIDE Visit(): \n"); // printListStdOut(S); G->color[x] = GREY; G->discover[x] = (++G->time); // printf("time is now: %d \n", G->time); List L = G->adjList[x]; // printListStdOut(L); for(moveFront(L); index(L) != -1; moveNext(L)){ int y = get(L); // printf("printing y \n"); // printf( "y : %d ", y); // printf("INSIDE Visit(): after deleting the vector being discovered \n"); // printListStdOut(S); if(G->color[y] == WHITE){ G->parent[y] = x; Visit(G, y, S); } } G->color[x] = BLACK; G->finish[x] = (++G->time); //as vertices finish we push them onto the stack prepend(S, x); } /*** Other operations ******************************************************/ //prints the adjacency list representation of G to the file pointed to by out void printGraph(FILE* out, Graph G) { if (G == NULL ) { printf("Graph Error: calling printGraph() on empty Graph\n"); exit(1); } fprintf(out, "Adjacency list representation of G: \n"); for(int i = 1; i<= G->order; i++) { List L = G->adjList[i]; if(length(L) == 0){ fprintf(out, "%d: \n", i); }else{ fprintf(out, "%d: ", i); printList(out,L); fprintf(out, "\n"); } } } //prints to std out void printGraphStdOut(Graph G, List S) { if (G == NULL ) { printf("Graph Error: calling printGraph() on empty Graph\n"); exit(1); } printf("Adjacency list representation of G: \n"); for(moveFront(S); index(S) != -1; moveNext(S)) { int i = get(S); List L = G->adjList[i]; if(length(L) == 0){ printf("%d: \n", i); }else{ printf("%d: ", i); printListStdOut(L); // printf("\n"); } } } Graph transpose(Graph G){ Graph T = newGraph(getOrder(G)); //make new graph called transpose if (G == NULL) { printf("Error: transpose called on NULL Graph.\n"); exit(1); } for (int x = 1; x <= getOrder(T); x++) { List L= G->adjList[x]; //make a list reference that for each vector containing the vectors it points to for (moveFront(L); index(L) != -1; moveNext(L)) { int y = get(L); addArc(T,y,x); //reverse the edge direction and now the neighbors point to each vector } } return (T); } Graph copyGraph(Graph G){ if(G == NULL) { fprintf(stderr, "Error: cannot call copyGraph() on NULL Graph.\n"); exit(1); } Graph Copy = newGraph(getOrder(G)); for(int i = 1; i <= getOrder(G); i++) { List L = G->adjList[i]; for (moveFront(L); index(L) != -1; moveNext(L)) { addArc(Copy, i, get(L)); } } return Copy; } <file_sep>/qickSort in Java/README.md Brief description of submitted files: **src/cs1c/TimeConverter.java** - Converts duration into a string representation. **src/cs1c/CSVFileWriter.java** - CSVFileWriter object writes the data from each array size to a CSV file in resources folder **src/quickSort/FHsort.java** - A divide and conquer algorithm that uses a pivot to group the elements into two groups (higher/lower than pivot) to sort **src/quickSort/TestQSwRecursionLimit.java** - Class benchmarks quick sort algorithm on large arrays and recursion limits and generates data that is used to make a graph and analyze optimal range of performance **RUN.txt** - console output of TestQSwRecursionLimit.java **README.md** - description of submitted files <file_sep>/JAVAFX GUI/resources/project_proposal.md Project Proposal for Project 9 and Team [NUMBER] [AUTHOR NAMES] ================================================ [Give an overview of the features you propose to implement.] Feature 1 --------- - [DESCRIPTION of user interaction] choose from two files, check boxes to add countries that user wants to add to the line chart. - [OWNER] Susanna, Victoria, Julia - [PROJECTED COMPLETION DATE] 6/22 - [ACTUAL COMPLETION DATE TO github.com repo] etc. <br><br> Feature 2 --------- - [DESCRIPTION of user interaction] Sequential steps: choose from two files, select countries to be graphed from checkbox, select year , graph bar chart. - [OWNER] Susanna - [PROJECTED COMPLETION DATE] 6/22 - [ACTUAL COMPLETION DATE TO github.com repo] <br><br> Names of the classes ----------------------- [Proposed names of the classes used to implement the interactions.] [Note: As long as you remain true to the purpose of the feature, you may find it necessary to rename the classes and modify the funcanaltiy proposed here. If you make non-trivial changes, then update this.] BarGraphView - Reads in date from the model , creates a series from each country that is selected by user for bar chart graph BarGraphPane - organizes stage layout into HBox, VBox, StackPanes, and adds to scene2 of stage for bar chart feature LineGraphPane - organizes stage layout into HBox, VBox, StackPanes, and adds to scene of stage for line chart feature LineGraphView - Reads in date from the model , creates a series from each country that is selected by user for line chart graph <br><br> <file_sep>/JAVAFX GUI/cellularData/ICVReader.java package cellularData; /** * ICVReader interface provides methods for CSV classes * @author Foothill College, Bita M., Team 8 */ public interface ICVReader { /** * Array of CSVReader object which has a LinkedList of country names. * @return array of country names */ LinkedList<String> getCountryNames(); /** * Gets array of years of CSVReader object. * @return array of years */ int[] getYearLabels(); /** * Gets LinkedList of CSVReader object which has country names and number of subscriptions. * @return country names and number of subscriptions */ LinkedList<double[]> getParsedTable(); /** * Gets title of CSVReader object. * @return title of the parsed file */ String getTitle(); } <file_sep>/JAVAFX GUI/cellularData/CSVReader.java package cellularData; import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; /** * CSVReader class stores a data from a cellular.csv file. * @author <NAME>, <NAME>., Team 8 */ public class CSVReader implements ICVReader { // member data private LinkedList<String> countryNames; private int[] yearLabels; private LinkedList<double[]> cellularDataTable; private String title; /** * parameter-taking constructor for creating CSVReader object. * @param fileName takes a String value which contains the address of csv file */ public CSVReader(String fileName) { Scanner myScanner; String line; String[] tokens; File infile = new File (fileName); try { myScanner = new Scanner(infile); title = myScanner.nextLine(); //System.out.println(title); line = myScanner.nextLine(); tokens = line.split(","); countryNames = new LinkedList<>(); line = myScanner.nextLine(); tokens = line.split(","); yearLabels = new int[tokens.length-1]; for(int i = 1; i < tokens.length; i++) { yearLabels[i-1] = Integer.parseInt(tokens[i]); } cellularDataTable = new LinkedList<>(); while (myScanner.hasNextLine()) { line = myScanner.nextLine(); tokens = line.split(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)", -1); countryNames.add(tokens[0]); double[] data = new double[yearLabels.length]; for(int i = 1; i < tokens.length; i++) { data[i-1] = Double.parseDouble(tokens[i]); } cellularDataTable.add(data); } myScanner.close(); } catch(FileNotFoundException a) { System.out.println("File " + fileName + " not found!"); } } /** * Gets and returns the linked list with country names * @return countryNames, the linked list with country names */ @Override public LinkedList<String> getCountryNames() { return countryNames; } /** * Gets and returns an array of integers with year labels * @return yearLabels */ @Override public int[] getYearLabels() { return yearLabels; } /** * Gets and returns the data in the linked list of arrays of doubles. * @return cellularDataTable */ @Override public LinkedList<double[]> getParsedTable() { return cellularDataTable; } /** * Gets and returns the title for the chart. * @return title */ @Override public String getTitle(){ return title; } }<file_sep>/Queue in Java/src/queues/Jukebox.java //Author:sumorin package queues; import cs1c.SongEntry; import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; /** * The class Jukebox manages three objects of type Queue. * An instance of the class may read a file which includes the user's requests for a * the name of a song to be added to a specific playlist. It will then add songs * to the three playlists "favorites", "lounge", and "road trip" accordingly. */ public class Jukebox { //attributes String songNotFound = ""; Queue<SongEntry> favoritePL; Queue<SongEntry> roadTripPL; Queue<SongEntry> loungePL; /** * constructor */ public Jukebox() { this.favoritePL = new Queue<SongEntry>("favorites"); this.roadTripPL = new Queue<SongEntry>("road trip"); this.loungePL = new Queue<SongEntry>("lounge"); } /** * accessor method * @return */ public Queue<SongEntry> getFavoritePL() { return favoritePL; } /** * accessor method * @return */ public Queue<SongEntry> getLoungePL() { return loungePL; } /** * accessor method * @return */ public Queue<SongEntry> getRoadTripPL() { return roadTripPL; } /** * This method reads the test file and then adds songs to one of the three queues * Then the first song found that equals the title will be placed in the favorites playlist. * @param requestFile takes in a string onject with the title of the playlist to add to * @param allSongs takes in an array of songs */ public void fillPlaylists(String requestFile, SongEntry[] allSongs) { String songName, playlistName; String line = ""; File infile = new File(requestFile); String[] tokens = null; try { Scanner scanner = new Scanner((infile)); while (scanner.hasNextLine()) { line = scanner.nextLine(); tokens = line.split(","); playlistName = tokens[0]; songName = tokens[1]; SongEntry foundMatch = findFirstOccurrence(songName, allSongs); if(foundMatch != null){ switch(playlistName){ case "favorites": this.favoritePL.enqueue(foundMatch); break; case "road trip": this.roadTripPL.enqueue(foundMatch); break; case "lounge": this.loungePL.enqueue(foundMatch); break; } } else{ System.out.println("\n[PLAYLIST NOT FOUND]: " + playlistName.toUpperCase() + " - CANNOT ADD \"" + songName.toUpperCase() + "\"\n"); } } scanner.close(); //close the file } catch (FileNotFoundException e) { System.out.println("File " + requestFile + " not found!"); }catch (ArrayIndexOutOfBoundsException e){ System.out.println("\n[SONG(S) NOT FOUND]: \"" + songNotFound.toUpperCase() + "\" \n"); } } /** * helper method will find first occurrence of song title of interest * @param songToMatch holds the song that we want to search * @param masterList the master list that we will search in and compare each object title with the song of interest * @return SongEntry object that matched to the song of interest */ public SongEntry findFirstOccurrence(String songToMatch, SongEntry[] masterList){ SongEntry found = null; for(int i = 0; i < masterList.length; i++) { if(songToMatch.equals(masterList[i].getTitle())) { found = masterList[i]; break; //after found first occurrence break from the loop } } if(found == null){ songNotFound += songToMatch + ", "; } return found; } } <file_sep>/JAVAFX GUI/resources/tasks.md Tasks for Project 9 and Team [NUMBER] ===================================== Part A --------- - task 1: [DESCRIPTION, including classes and methods involved] creating bar chart, adding it to scene, handling input events, organizing stage into HBox, VBox,StackPanes, adding checkbox for country selection and adding to scene and stage, creating drop down for years available to each data files, handling input events, add icon to stage - [OWNER] Susanna - [PROJECTED COMPLETION DATE] 6/21 - [ACTUAL COMPLETION DATE TO github.com repo] TBD - task 2: [DESCRIPTION, including classes and methods involved] adding line chart to stage, organizing stage into HBox, VBox, StackPanes, creating tabs to toggle from Scene1(line) and Scene 2(bar), handling input events for scene 1 - [OWNER] Victoria - [PROJECTED COMPLETION DATE] 6/21 - [ACTUAL COMPLETION DATE TO github.com repo] TBD - task 3: [DESCRIPTION, including classes and methods involved] implementing checkbox for scene 1 for line chart - [OWNER] Julia - [PROJECTED COMPLETION DATE] 6/21 - [ACTUAL COMPLETION DATE TO github.com repo] TBD etc. <br><br> Part B - Tasks completed by each member Susanna: - created BarGraphView class - BarGraphView constructor, seriesFromYear() (*later used for seriesFromCountry*), update() - separated the GraphPane into two separate files to handle implementations of two scenes (merged back to GraphPane later*) - made ChartGraph only handle simple tasks instead of having GraphPane tasks nested inside - added the checkbox feature for countries to the BartChart - added icon to the application window - updated fileChoice() for dropdown year menu to handle clears for countries and year menus - setYears()creates the series based on the SubscriptionYear information of the current country. - YearComboBox to allow user to select year that will be graphed along with selected countries, only allows min,max year dependent on the file chosen - handled keyEvents to show on the console when the user selected from file, country, and year menu (removed later*) Victoria: - Created the layout using BorderPane, addHBox(), addVBox(), add CentralPane(), updateCentralPane() with initial switching between two scenes - Created fileChoice() to choose a data file to parse - Added short user manual to the default scene - updated fileChoice() to be shorter in accordance with program guidelines by moving code that belongs to the setYears() - removed unused variables, converted some variables to local. - Added/corrected comments, generated javadocs, wrote README file, created snapshots of the run. Julia: - added library for CheckComboBox - implemented CheckComboBox for the LineChart - addToolTip method for the hover effect label on the BarChart - style.css stylesheet for formatting bar graph - code refactoring into concise and efficient style with less classes and methods - moved country names from the axis labels to the legend for more spacious fit - returned user manual that was lost somewhere in the process - added clear button Branches used: master Since each team member had different schedules, we divided the work by what needed to be done first. Our work flow followed schedules and each person sequentially added and/or updated previous work and then integrated their work on top. --------- <br><br> Extra Credit (if applicable) ----------------------- Will be demoing project during class - sent email to Bita Friday 6/23. <br><br> Extra Credit Discussion (if applicable) ----------------------- A discussion that was useful when programming side by side was one that involved whether we wanted to use a BarChart in the second scene or if we wanted to instead use text output and make use of the getNumSubscriptionsForPeriod() in CountryClass. We opted to use the BarChart feature because it looks more visually appealing and modern. Also, we discussed whether it would be a better design to add a range of years (start year and end year) that can chosen by user to be graphed in the BarChart with different series plotted against each other. We ultimately, decided on having the user select one year so we can concentrate on the hover effect to satisfy InputEvent. <br><br> <file_sep>/Genomic Analysis in Python/sequenceAnalysis.py #!/usr/bin/env python # coding: utf-8 # In[ ]: #!/usr/bin/env python3 # Name: <NAME> (sumorin) # “None” '''A module containing 3 classes: NucParams: keeps track of amino acids, nucleotides, and codons (RNA/DNA) from complete genome ProteinParams: computes molecular weight, isoelectric point, net charge, molar extinction and mass extinction using protein composotion passed in from user input FastAreader: reads from a FastA file or from stdin ''' import sys from itertools import zip_longest import numpy as np from collections import OrderedDict class NucParams: '''A class that keeps track of amino acids, nucleotides, and codons (RNA/DNA) from complete genome''' rnaCodonTable = { # RNA codon table # U 'UUU': 'F', 'UCU': 'S', 'UAU': 'Y', 'UGU': 'C', # UxU 'UUC': 'F', 'UCC': 'S', 'UAC': 'Y', 'UGC': 'C', # UxC 'UUA': 'L', 'UCA': 'S', 'UAA': '-', 'UGA': '-', # UxA 'UUG': 'L', 'UCG': 'S', 'UAG': '-', 'UGG': 'W', # UxG # C 'CUU': 'L', 'CCU': 'P', 'CAU': 'H', 'CGU': 'R', # CxU 'CUC': 'L', 'CCC': 'P', 'CAC': 'H', 'CGC': 'R', # CxC 'CUA': 'L', 'CCA': 'P', 'CAA': 'Q', 'CGA': 'R', # CxA 'CUG': 'L', 'CCG': 'P', 'CAG': 'Q', 'CGG': 'R', # CxG # A 'AUU': 'I', 'ACU': 'T', 'AAU': 'N', 'AGU': 'S', # AxU 'AUC': 'I', 'ACC': 'T', 'AAC': 'N', 'AGC': 'S', # AxC 'AUA': 'I', 'ACA': 'T', 'AAA': 'K', 'AGA': 'R', # AxA 'AUG': 'M', 'ACG': 'T', 'AAG': 'K', 'AGG': 'R', # AxG # G 'GUU': 'V', 'GCU': 'A', 'GAU': 'D', 'GGU': 'G', # GxU 'GUC': 'V', 'GCC': 'A', 'GAC': 'D', 'GGC': 'G', # GxC 'GUA': 'V', 'GCA': 'A', 'GAA': 'E', 'GGA': 'G', # GxA 'GUG': 'V', 'GCG': 'A', 'GAG': 'E', 'GGG': 'G' # GxG } dnaCodonTable = {key.replace('U','T'):value for key, value in rnaCodonTable.items()} def __init__ (self, inString=''): self.seq = inString.upper() #takes in optional sequence parameter, empty string is default #creates a dictionary of amino acids, nucleotide bases, codons, all with initial values set to '0' self.aaComp = dict.fromkeys(NucParams.rnaCodonTable.values(),0) self.nucComp = dict.fromkeys('ACGTNU',0) self.codonComp = dict.fromkeys(NucParams.rnaCodonTable.keys(),0) #processes seq given as optional parameter only if non empty string if not self.seq: #self.seq will evaluate to false if string is empty self.addSequence(self.seq) def addSequence (self, inSeq): '''This method must accept new sequences, from the {ACGTUN} alphabet, and can be presumed to start in frame 1.''' self.nucComposition(inSeq) #counts nucleotides self.codonComposition(inSeq) #counts codons self.aaComposition(inSeq) #counts amino acids def aaComposition(self, inSeq): '''This method will return a dictionary of counts over the 20 amino acids and stop codons.The codon is decoded first.''' for codon in range(0,len(inSeq),3): actual = inSeq[codon:codon+3] if actual in NucParams.rnaCodonTable.keys() or NucParams.dnaCodonTable.keys(): #check for key in both codon dictionaries if all(char in "ACGUT" for char in actual) and len(actual) == 3: codon2AA = NucParams.rnaCodonTable.get(actual) or NucParams.dnaCodonTable.get(actual) #translates codon to aa #test: print('this is translation {0}: '.format(codon2AA)) self.aaComp[codon2AA] = self.aaComp.get(codon2AA) +1 #adds 1 to existing count #test: print('this is amino acid count {0}: '.format(self.aaComp.get(codon2AA))) return self.aaComp def nucComposition(self, inSeq): '''This method returns a dictionary of counts of valid nucleotides found in the analysis. (ACGTNU}. RNA nucleotides should be counted as RNA nucleotides.DNA nucleotides should be counted as DNA nucleotides. N bases found will be counted also. Invalid bases will be ignored in this dictionary.''' for nuc in inSeq: if nuc in 'ACGTNU': self.nucComp[nuc] = self.nucComp.get(nuc) +1 #increments the previous count if valid base in dict #test: print('nuc count: {0}'.format(self.nucComp.get(nuc))) #test: print('this is the nuc dict: {0}'.format(self.nucComp)) return self.nucComp def codonComposition(self, inSeq): '''This dictionary returns counts of codons. Presume that sequences start in frame 1, accept the alphabet {ACGTUN} and store codons in RNA format, along with their counts.Codons found with invalid bases and codons with N bases are discarded. All codon counts are stored as RNA codons, even if the input happens to be DNA. Discarded codons will not alter the frame of subsequent codons.''' for codon in range(0,len(inSeq),3): actual = inSeq[codon:codon+3] if 'T' in actual and len(actual) == 3: #only enters this suite if DNA codon, contains "T" tCount = actual.count('T') dna2RNA = actual.replace('T', 'U', tCount) self.codonComp[dna2RNA] = self.codonComp.get(dna2RNA) +1 #test: print(self.codonComp.get(dna2RNA)) elif all(char in "ACGU" for char in actual) and len(actual) == 3: #checks that all chars in codon are valid self.codonComp[actual] = self.codonComp.get(actual) +1 #if invalid chars in codon, it will discard the codon #test: print(self.codonComp.get(actual)) return self.codonComp def nucCount(self): '''This returns an integer value, summing every valid nucleotide {ACGTUN} found. This value will exactly equal the sum over the nucleotide composition dictionary.''' return sum(self.nucComp.values()) class FastAreader : ''' Define objects to read FastA files. instantiation: thisReader = FastAreader ('testTiny.fa') usage: for head, seq in thisReader.readFasta(): print (head,seq) ''' def __init__ (self, fname=''): '''contructor: saves attribute fname ''' self.fname = fname def doOpen (self): ''' Handle file opens, allowing STDIN.''' if self.fname is '': return sys.stdin else: return open(self.fname) def readFasta (self): ''' Read an entire FastA record and return the sequence header/sequence''' header = '' sequence = '' with self.doOpen() as fileH: header = '' sequence = '' # skip to first fasta header line = fileH.readline() while not line.startswith('>') : line = fileH.readline() header = line[1:].rstrip() for line in fileH: if line.startswith ('>'): yield header,sequence header = line[1:].rstrip() sequence = '' else : sequence += ''.join(line.rstrip().split()).upper() yield header,sequence class ProteinParam : '''Class computes molecular weight, isoelectric point, net charge, molar extinction and mass extinction using protein composotion passed in from user input. ''' # These tables are for calculating: # molecular weight (aa2mw), along with the mol. weight of H2O (mwH2O) # absorbance at 280 nm (aa2abs280) # pKa of positively charged Amino Acids (aa2chargePos) # pKa of negatively charged Amino acids (aa2chargeNeg) # and the constants aaNterm and aaCterm for pKa of the respective termini # As written, these are accessed as class attributes, for example: # ProteinParam.aa2mw['A'] or ProteinParam.mwH2O aa2mw = { 'A': 89.093, 'G': 75.067, 'M': 149.211, 'S': 105.093, 'C': 121.158, 'H': 155.155, 'N': 132.118, 'T': 119.119, 'D': 133.103, 'I': 131.173, 'P': 115.131, 'V': 117.146, 'E': 147.129, 'K': 146.188, 'Q': 146.145, 'W': 204.225, 'F': 165.189, 'L': 131.173, 'R': 174.201, 'Y': 181.189 } mwH2O = 18.015 aa2abs280= {'Y':1490, 'W': 5500, 'C': 125} aa2chargePos = {'K': 10.5, 'R':12.4, 'H':6} aa2chargeNeg = {'D': 3.86, 'E': 4.25, 'C': 8.33, 'Y': 10} aaNterm = 9.69 aaCterm = 2.34 def __init__ (self, protein): '''Computes and saves the aaComposition dictionary as an attribute.''' validAAs = ['A', 'C', 'D', 'E','F', 'G', 'H', 'I', 'L', 'K', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'Y', 'W'] upperAA = protein.upper() #convert string into uppercase pureAAs = ''.join(aa for aa in upperAA if aa in validAAs) #remove unwanted characters noDup = "".join(OrderedDict.fromkeys(pureAAs)) #remove duplicates self.aaComp = dict.fromkeys(validAAs, 0) #self. puts the dictionary into namespace of object j = 0 for values in self.aaComp: while j < len(noDup): self.aaComp[noDup[j]] = pureAAs.count(noDup[j]) j += 1 self.noDup = noDup #makes string of valid aa available to other methods def aaCount (self): '''This method will return a single integer count of valid amino acid characters found.''' return sum(self.aaComp.values()) #sum() returns the sum of all items in an iterable def pI (self): '''Estimates Isolelectric point by finding the particular pH that yields a neutral net Charge (close to 0), accurate to 2 decimal points.''' lowest = 10000000 for pH in np.arange(0.0,14.0,.01): #0-14 range current = self._charge_(pH) if current < lowest and current >= 0 : lowest = current lowestPH = pH return lowestPH def aaComposition (self) : '''This method is to return a dictionary keyed by single letter Amino acid code, and having associated values that are the counts of those amino acids in the sequence.''' return self.aaComp def _charge_ (self, pH): '''This method calculates the net charge on the protein at a specific pH (specified as a parameter of this method).''' posSum = 0 for aa, pCharge in ProteinParam.aa2chargePos.items(): posSum += self.aaComp.get(aa)*(10**pCharge/(10**pCharge + 10**pH)) negSum = 0 for aa, nCharge in ProteinParam.aa2chargeNeg.items(): negSum += self.aaComp.get(aa)*(10**pH/(10**nCharge + 10**pH)) nTerm = 10**ProteinParam.aaNterm / (10**ProteinParam.aaNterm + 10**pH) cTerm = 10**pH / (10**ProteinParam.aaCterm + 10**pH) return ((posSum + nTerm ) - (negSum + cTerm )) def molarExtinction (self): '''Estimates the molar extinction coefficient of a protein from knowledge of its amino acid composition (at 280 nm).''' y = self.aaComp.get('Y')*ProteinParam.aa2abs280.get('Y') #calculates the product of number of aa and extinction coefficient w = self.aaComp.get('W')*ProteinParam.aa2abs280.get('W') c = self.aaComp.get('C')*ProteinParam.aa2abs280.get('C') return y+w+c #sums up product for each Y,W,C present in protein def massExtinction (self): '''Calculates the Mass extinction coefficient from the Molar Extinction coefficient by dividing by the molecularWeight of the corresponding protein (at 280 nm).''' myMW = self.molecularWeight() return self.molarExtinction() / myMW if myMW else 0.0 def molecularWeight (self): '''Calculates the molecular weight (MW) of the protein sequence.''' r = 0 result = ProteinParam.mwH2O for aa in self.aaComp: while r < len(self.noDup): result += self.aaComp.get(self.noDup[r])*(ProteinParam.aa2mw.get(self.noDup[r])- ProteinParam.mwH2O) r += 1 return result <file_sep>/Graph Module in C/GraphTest.c //sumorin #include<stdio.h> #include<stdlib.h> #include<string.h> #include "Graph.h" int main(int argc, char * argv[]) { Graph G = NULL; // Graph T = NULL; List S; int n = 100; //create a graph G = newGraph(n); // addArc(G, 1, 2); // addArc(G, 2, 3); // addArc(G, 2, 5); // addArc(G, 2, 6); // addArc(G, 3, 4); // addArc(G, 3, 7); // addArc(G, 4, 3); // addArc(G, 4, 8); // addArc(G, 5, 1); // addArc(G, 5, 6); // addArc(G, 6, 7); // addArc(G, 7, 6); // addArc(G, 7, 8); // addArc(G, 8, 8); //create a list that will be in vector label sorted order {1,2,3...n} to feed into DFS // S = newList(); // for(int i = 1; i <= getOrder(G);i++ ){ // append(S, i); // } // //done processing the file, so we print adjacency list // printGraphStdOut(G, S); // DFS(G,S) // //print list of vectors in label sorted order // printf("Printing the list of vector labels in sorted order: "); // printListStdOut(S); // //first run of DFS on G // //S is the list that represents the order each vertex will be visited, initially it is vertex label sorted order // DFS(G, S); // printf("The list has been modified and now contains the order of vertices will follow on the second run: "); // // printListStdOut(S); // T = transpose(G); // // printGraphStdOut(T, S); // DFS(T,S); // printf("DFS has now been run a seconn time using G_Transpose and modified list of vectors finished in decreasing time order.\n "); // printf("List containing topological sorted order of strongly connected components .\n "); // printListStdOut(S); //-------------------------------------------------------------------------------- addArc(G, 64, 4); addArc(G, 64, 3); addArc(G, 42, 2); addArc(G, 2, 64); addArc(G, 4, 2); addArc(G, 3, 42); S = newList(); for(int i = 1; i <= 100 ;i++ ){ prepend(S, i); } printGraphStdOut(G, S); printListStdOut(S); DFS(G, S); int y = getFinish(G, 64); printf("get finish of G is: %d ", y); //second run of DFS DFS(G, S); int x = getFinish(G, 64); printf("get finish of G on second run is: %d ", x); //free the memory allocated freeList(&S); freeGraph(&G); } <file_sep>/README.md # A compilation of programs i've written in Computer Science, Computer Engineering, and Bioinformatics courses. Enjoy! # Note: Some of these files were provided by professors and I have also included a collaboration with collegues (JavaFX GUI). However, the majority of the listed projects, I have created on my own following required specifications. # Author names are provided at the beginning of each program (somewhere before first 10 lines). <file_sep>/Hash Tables in Java/src/hashTables/FHhashQPwFind.java //Author: sumorin package hashTables; import java.util.NoSuchElementException; /** * A generic hash class that allows for find-on-key mechanism * a FHHashQPwFind object will take in a key of type String or Integer and return the SongEntry object that matches * @param <KeyType> * @param <E> */ public class FHhashQPwFind<KeyType, E extends Comparable<KeyType> > extends FHhashQP<E> { static final int MATCH = 0; public FHhashQPwFind(int tableSize) { super(tableSize); // superclass constructor with matching parameter is called - FHhashQp(int tableSize) } /** * method takes in a key field (Integer or String) and finds an object matching that key field or throw a NoSuchElementException * * @param key key value to search for * @return returns entire object with the key value we searched for */ public E find(KeyType key) throws NoSuchElementException { //call on the findPosKey method to get index with key, if found int index = findPosKey(key); //throw exception because the index given does not hold anything and we cannot continue with QP if (mArray[index].state == EMPTY) { throw new NoSuchElementException(); } return mArray[index].data; } /** * A hash function that takes in a key into an array index * * @param key takes in a key of type int or String * @return a hash value assigned to that key that will guarantee to fit in the table */ protected int myHashKey(KeyType key) { int hashVal; hashVal = key.hashCode() % mTableSize;//makes sure it will fit in the table if (hashVal < 0) //because with mod operator it is possible to have neg number hashVal += mTableSize; return hashVal; } /** * Method that takes in a key and returns an index for the position in the table * * @param key takes in a String or Integer key * @return the index in the table array that holds the object that matches the key */ protected int findPosKey(KeyType key) { int kthOddNum = 1; int index = myHashKey(key); // keep probing until we get an empty position or match while (mArray[index].state != EMPTY && mArray[index].data.compareTo(key) != MATCH) { //now we can do the QP probing index += kthOddNum; // k squared = (k-1) squared + kth odd # kthOddNum += 2; // compute next odd # if (index >= mTableSize) //we have reached outside of the table index -= mTableSize; //lets go back to the beginning of the table and start QP from there } return index; } } <file_sep>/Graph Module in C/List.h //sumorin #ifndef LIST_H #define LIST_H // Exported Types -------------------------------------------------------------- typedef struct ListObj* List; // Constructors-Destructors --------------------------------------------------- List newList(void); //Constructor //Creates a new empty list. void freeList(List *pL); // frees all heap memory associated with its List* argument, // and sets *pL to NULL // Access functions ----------------------------------------------------------- int length(List L); // Access functions // Returns the number of elements in this List int index(List L); // If cursor is defined, returns the index of the cursor element, // otherwise returns -1. int front(List L); // Returns front element. Pre: length()>0 int back(List L); // Returns back element. Pre: length()>0 int get(List L); // Returns cursor element. Pre: length()>0, index()>=0 int equals(List A, List B); // Returns true if and only if this List and L are the same // integer sequence. The states of the cursors in the two Lists // are not used in determining equality. // Manipulation procedures ---------------------------------------------------- void clear(List L); // Resets this List to its original empty state. void moveFront(List L); // If List is non-empty, places the cursor under the front element, // otherwise does nothing. void moveBack(List L); // If List is non-empty, places the cursor under the back element, // otherwise does nothing. void movePrev(List L); // If cursor is defined and not at front, moves cursor one step toward // front of this List, if cursor is defined and at front, cursor becomes // undefined, if cursor is undefined does nothing. void moveNext(List L); // If cursor is defined and not at back, moves cursor one step toward // back of this List, if cursor is defined and at back, cursor becomes // undefined, if cursor is undefined does nothing. void prepend(List L, int data); // Insert new element into this List. If List is non-empty, // insertion takes place before front element. void append(List L, int data); // Insert new element into this List. If List is non-empty, // insertion takes place after back element. void insertBefore(List L, int data); // Insert new element before cursor. // Pre: length()>0, index()>=0 void insertAfter(List L, int data); // Inserts new element after cursor. // Pre: length()>0, index()>=0 void deleteFront(List L); // Deletes the front element. Pre: length()>0 void deleteBack(List L); // Deletes the back element. Pre: length()>0 void delete(List L); // Deletes cursor element, making cursor undefined. // Pre: length()>0, index()>=0 //delete current void setIndex(List L, int index); // Other operations ----------------------------------------------------------- void printList(FILE* out, List L); // prints the L to the file pointed to by out, formatted as a // space-separated string. void printListStdOut(List L); //prints a list to std out List copyList(List L); // Returns a new List representing the same integer sequence as this // List. The cursor in the new list is undefined, regardless of the // state of the cursor in this List. This List is unchanged. #endif <file_sep>/Genomic Analysis in Python/genomeAnalyzer.py #!/usr/bin/env python # coding: utf-8 # In[1]: #!/usr/bin/env python3 # Name: <NAME> (sumorin) # <NAME> (bdreyes) ''' This program imports sequenceAnalysis module. It is responsible for preparing the summaries and final display of the data. output: sequence length = 3.14 Mb GC content = 60.2% UAA : - 32.6 ( 1041) UAG : - 38.6 ( 1230) UGA : - 28.8 ( 918) GCA : A 14.1 ( 10605) GCC : A 40.5 ( 30524) GCG : A 30.5 ( 22991) GCU : A 14.9 ( 11238) UGC : C 67.2 ( 4653) UGU : C 32.8 ( 2270) ...''' from sequenceAnalysis import NucParams, FastAreader def main (): '''A program that outputs the summaries and final display of genome parsed in''' myReader = FastAreader() #make sure to change this to use stdin myNuc = NucParams() #instantiate new NucParams object for head, seq in myReader.readFasta() : #unpacks the header, sequence from the tuple myNuc.addSequence(seq) #adds only the sequence ot the myNuc object #calculate gc content and sequence length nucsMb = myNuc.nucCount()/1000000 c = myNuc.nucComp['C'] g = myNuc.nucComp['G'] gcTotal = c+g gcContent = (gcTotal/myNuc.nucCount())*100 print('sequence length = {0:.2f} Mb \n\n' 'GC content = {1:.1f} % \n'.format(nucsMb, gcContent)) #sort codons in alpha order, by Amino Acids (values in dict) # calculate relative codon usage for each codon and print for codon, aa in sorted(myNuc.rnaCodonTable.items(), key = lambda value: (value[1], value[0])): val = myNuc.codonComp.get(codon)/myNuc.aaComp.get(aa) print ('{:s} : {:s} {:5.1f} ({:6d})'.format(codon, aa, val*100, myNuc.codonComp.get(codon))) if __name__ == "__main__": main() # In[ ]: <file_sep>/Stacks in Java/src/stacks/StackList.java //Author:sumorin package stacks; import java.util.*; import java.util.NoSuchElementException; /** * Keeps track of the current link, links previous to the current link, and links seen after the current link * @param <AnyType> */ public class StackList<AnyType> implements Iterable { private String name; //the name of this instance (for testing and debugging) private Node top; //points to the top of the stack private int mSize; /** * constructor sets the member attributes * @param name holds the name of the stack (to be used by toString()) */ public StackList(String name) { this.name = name; clear(); } /** * accessor method * @return number of elements in the stack. */ public int size(){ return mSize; } /** * removes all the elements from the list */ public void clear(){ mSize = 0; this.top = null; } /** * prints the name of the stack passed in by the Navigator class in addition to the number of links in the stack */ @Override public String toString(){ Iterator<AnyType> iter = iterator(); String result = ""; while(iter.hasNext()){ result += iter.next() + ", "; } return this.name + " has " + this.mSize + " link(s): \n[" + result + "]"; } /** * Everytime a user wants to move to the beginning of the list, StackList return a new iterator pointing * to beginning of list * @return */ @Override public Iterator<AnyType> iterator() { return new StackIterator(); } // required stack operations --------------------------------------------------------------------- /** * Pushes an element onto the stack represented by this list. * @param x */ public void push(AnyType x) { Node newNode = new Node(x); newNode.next = this.top; this.top = newNode; mSize++; } /** * Pops an element from the stack represented by this list. * @return the generic item popped. */ public AnyType pop() { if (isEmpty()){ throw new EmptyStackException(); //in case pop() gets called in method besides goBack() and goForward() } AnyType retValue = this.top.data; this.top = top.next; mSize--; return retValue; } /** * Retrieves, but does not remove, the head (first element) of this list. * @return If the stack is empty, returns null. Otherwise, returns a generic type for the data seen at top of stack */ public AnyType peek() { if (isEmpty()){ return null; }else{ AnyType retValue = this.top.data; return retValue; } } /** * checks if the top of the stack is pointing to anything. * @return true if top has not been initialized (is empty), false otherwise. */ public boolean isEmpty(){ if(mSize == 0){ return true; }else{ return false; } } //inner class // This class is only used in LinkedList, so it is private. // This class does not need to access any instance members of LinkedList, so it is defined static. private class Node{ Node next; AnyType data; /** * Constructor * @param element takes in generic element as a parameter to be assigned as data */ Node( AnyType element ) { this.data = element; next = null; } } // required interface implementations ---------------------------------------------------------------- /** * traverses a list similar like a "cursor" that can be placed before one element of a data structure at given time */ private class StackIterator implements Iterator<AnyType>{ protected Node mCurrentNode; /** * Constructors (default access for package only) */ StackIterator() { mCurrentNode = top; //iterator is instantiated at start(far-left) of the list } /** * @return returns true if there is something in the list to the immediate right of the iterator. * If there is no item there, meaning it is at the end of the list, it returns false. */ public boolean hasNext() { if (mCurrentNode == null) { return false; } else { return true; } } /** * * @return returns the item to the immediate right of the iterator, and moves the iterator up one, i.e., * past the item just returned. */ public AnyType next() { if(!hasNext()){ throw new NoSuchElementException(); }else{ AnyType retVal = mCurrentNode.data; mCurrentNode = mCurrentNode.next; return retVal; } } } }
cd7b3549a9f1ba3339b2bad8558eb347e92aa637
[ "Markdown", "Java", "Python", "Text", "C" ]
25
Text
code-s-witch/Compilation-C-Java-MIPS-Python-
928accb47ff52355454fc895b662031b4bfa7dd2
6ae2e36b993aeb28d9841ae64f0cd2592693fad3
refs/heads/master
<file_sep>#!/usr/bin/env python # -*- coding:utf-8 -*- def merge_sort(alist): if len(alist) <= 1: return alist num = len(alist) // 2 l = merge_sort(alist[:num]) r = merge_sort(alist[num:]) return merge(l, r) def merge(left, right): l, r = 0, 0 result = [] while l<len(left) and r<len(right): if left[l] <= right[r]: result.append(left[l]) l += 1 else: result.append(right[r]) r += 1 result += left[l:] result += right[r:] return result li = [23, 54, 67, 12, 7, 26, 54, 21] print(merge_sort(li))<file_sep> def bubble_sort(alist): for j in range(len(alist)-1, 0, -1): for i in range(j): if alist[i] > alist[i+1]: alist[i], alist[i+1] = alist[i+1], alist[i] li = [23, 54, 67, 12, 7, 23, 54, 21] bubble_sort(li) print(li) <file_sep>#!/usr/bin/env python # -*- coding:utf-8 -*- def index_sort(alist): for i in range(1, len(alist)): for j in range(i, 0, -1): if alist[j] < alist[j-1]: alist[j], alist[j-1] = alist[j-1], alist[j] li = [23, 54, 67, 12, 7, 26, 54, 21] index_sort(li) print(li)<file_sep>#!/usr/bin/env python # -*- coding:utf-8 -*- """ 非递归方式实现 """ def binary_search(alist, item): first = 0 last = len(alist) - 1 while first <= last: midpoint = (first + last) // 2 if alist[midpoint] == item: return True elif item < alist[midpoint]: last = midpoint - 1 else: first = midpoint -1 return False def binary_sort_by_recursion(alist, item): if len(alist) == 0: return False else: midpoint = len(alist)//2 if alist[midpoint] == item: return True else: if item < alist[midpoint]: return binary_sort_by_recursion(alist[:midpoint], item) else: return binary_sort_by_recursion(alist[midpoint+1:], item) li = [23, 54, 67, 12, 7, 26, 54, 21] # print(binary_search(li, 3)) # print(binary_search(li, 5)) print(binary_sort_by_recursion(li,3)) print(binary_sort_by_recursion(li, 5))<file_sep>#!/usr/bin/env python # -*- coding:utf-8 -*- """ 单向循环链表 """ class Node(object): def __init__(self, item): self.item = item self.next = None class SingleLinkList(object): def __init__(self): self.__head = None def is_empty(self): return self.__head == None def length(self): if self.is_empty(): return 0 cur = self.__head count = 1 while cur.next != self.__head: count += 1 cur = cur.next return count def travel(self): if self.is_empty(): return cur = self.__head while cur.next != self.__head: print(cur.item) cur = cur.next print(' hhah ') def add(self, item): node = Node(item) if self.is_empty(): self.__head = node node.next = self.__head else: node.next = self.__head cur = self.__head while cur.next != self.__head: cur = cur.next cur.next = node self.__head = node def append(self, item): node = Node(item) if self.is_empty(): self.__head = node node.next = self.__head else: cur = self.__head while cur.next != self.__head: cur = cur.next cur.next = node node.next = self.__head def insert(self, pos, item): if pos <= 0: self.add(item) elif pos > (self.length() -1): self.append(item) else: node = Node(item) count = 0 cur = self.__head while count < (pos-1): count += 1 cur = cur.next node.next = cur.next cur.next = node def rm(self, item): if self.is_empty(): return cur = self.__head pre = None while cur.next != self.__head: if cur.item == item: if cur == self.__head: rear = self.__head while rear.next != self.__head: rear = rear.next self.__head = cur.next rear.next = self.__head else: pre.next = cur.next return else: pre = cur cur = cur.next if cur.item == item: if cur == self.__head: self.__head = None else: pre.next = self.__head def search(self, item): if self.is_empty(): return False cur = self.__head if cur.item == item: return True while cur.next != self.__head: cur = cur.next if cur.item == item: return True return False if __name__ == '__main__': my = SingleLinkList() my.add(1) # 头部 my.add(2) my.add(3) # 尾部 my.insert(0, 4) # 下标 print('length: ', my.length()) my.travel() # 遍历 print(my.search(2)) # 查找节点是否存在 print(my.search(5)) my.rm(2) # 删除节点 my.travel()<file_sep>#!/usr/bin/env python # -*- coding:utf-8 -*- """ 单项链表 """ class SingleNode(object): """ 节点类型 """ def __init__(self, item): self.item = item self.next = None class SingleLinkList(object): """单向链表""" def __init__(self): self.__head = None def is_empty(self): # 判断是否为空 return self.__head == None def length(self): # 静态鼠标移动的次数 cur = self.__head count = 0 while cur != None: count += 1 cur = cur.next return count def travel(self): # 遍历 可取多种值,,,, cur = self.__head while cur != None: print(cur.item) cur = cur.next print(' hhah ') def append_to_head(self, item): node = SingleNode(item) # 取节点 node.next = self.__head self.__head = node def append_to_tail(self, item): node = SingleNode(item) if self.is_empty(): self.__head = node else: cur = self.__head while cur.next != None: cur = cur.next cur.next = node def append_to_index(self, pos, item): if pos <= 0: self.append_to_head(item) elif pos > (self.length()-1): self.append_to_tail(item) else: node = SingleNode(item) count = 0 pre = self.__head while count < (pos-1): count += 1 pre = pre.next node.next = pre.next pre.next = node def rm(self, item): cur = self.__head prev = None while cur != None: if cur.item == item: if not prev: self.__head = cur.next else: prev.next = cur.next break else: prev = cur cur = cur.next def search(self, item): cur = self.__head while cur != None: if cur.item == item: return True cur = cur.next return False if __name__ == '__main__': my = SingleLinkList() my.append_to_head(1) # 头部 my.append_to_head(2) my.append_to_tail(3) # 尾部 my.append_to_index(0, 4) # 下标 print('length: ', my.length()) my.travel() # 遍历 print(my.search(2)) # 查找节点是否存在 print(my.search(5)) my.rm(2) # 删除节点 my.travel()<file_sep>#!/usr/bin/env python # -*- coding:utf-8 -*- from timeit import Timer def my_fn1(): l = [] for i in range(1000): l += [i] def my_fn2(): l = [] for i in range(1000): l.append(i) def my_fn3(): l =[i for i in range(1000)] def my_fn4(): l = list(range(1000)) timer1 = Timer('my_fn1()', 'from __main__ import my_fn1') print('concat', timer1.timeit(number=1000), 'seconds') timer2 = Timer('my_fn2()', 'from __main__ import my_fn2') print('append', timer2.timeit(number=1000), 'seconds') timer3 = Timer('my_fn3()', 'from __main__ import my_fn3') print('comprehension', timer3.timeit(number=1000), 'seconds') timer4 = Timer('my_fn4()', 'from __main__ import my_fn4') print('list range', timer4.timeit(number=1000), 'seconds') x =range(2000000000) pop_zero = Timer('x.pop(0)', 'from __main__ import x') print('pop_zero', pop_zero.timeit(number=1000), 'seconds') x1 =range(2000000000) pop_end = Timer('x1.pop()', 'from __main__ import x1') print('pop_end', pop_zero.timeit(number=1000), 'seconds') <file_sep>#!/usr/bin/env python # -*- coding:utf-8 -*- def quick_sort(alist, start, end): if start >= end: return mid = alist[start] low = start high = end while low < high: while low < high and alist[high] >= mid: high -= 1 alist[low] = alist[high] while low < high and alist[low] < mid: low += 1 alist[high] = alist[low] alist[low] = mid quick_sort(alist, start, low-1) quick_sort(alist, low+1, end) li = [23, 54, 67, 12, 7, 26, 54, 21] quick_sort(li, 0, len(li)-1) print(li) <file_sep>#!/usr/bin/env python # -*- coding:utf-8 -*- """ 双向链表 """ class Node(object): def __init__(self, item): self.item = item self.next = None self.prev = None class SingleLinkList(object): def __init__(self): self.__head = None def is_empty(self): return self.__head == None def length(self): cur = self.__head count = 0 while cur != None: count += 1 cur = cur.next return count def travel(self): cur = self.__head while cur != None: print(cur.item) cur = cur.next print(' hhah ') def append_to_head(self, item): node = Node(item) if self.is_empty(): self.__head = node else: node.next = self.__head self.__head.prev = node self.__head = node def append_to_tail(self, item): node = Node(item) if self.is_empty(): self.__head = node else: cur = self.__head while cur.next != None: cur = cur.next cur.next = node node.prev = node def append_to_index(self, pos, item): if pos <= 0: self.append_to_head(item) elif pos > (self.length() -1): self.append_to_tail(item) else: node = Node(item) count = 0 cur = self.__head while count < (pos-1): count += 1 cur = cur.next node.prev = cur node.next = cur.next cur.next.prev = node cur.next = node def rm(self, item): cur = self.__head while cur != None: if cur.item == item: if cur == self.__head: self.__head = cur.next if cur.next: cur.next.prev = None else: cur.prev.next = cur.next if cur.next: cur.next.prev = cur.prev break else: cur = cur.next def search(self, item): cur = self.__head while cur != None: if cur.item == item: return True cur = cur.next return False if __name__ == '__main__': my = SingleLinkList() my.append_to_head(1) # 头部 my.append_to_head(2) my.append_to_tail(3) # 尾部 my.append_to_index(0, 4) # 下标 print('length: ', my.length()) my.travel() # 遍历 print(my.search(2)) # 查找节点是否存在 print(my.search(5)) my.rm(2) # 删除节点 my.travel()<file_sep>#!/usr/bin/env python # -*- coding:utf-8 -*- def selection_sort(alist): n = len(alist) for i in range(n-1): min_index = i for j in range(i+1, n): if alist[j] < alist[min_index]: min_index = j if min_index != i: alist[i], alist[min_index] = alist[min_index], alist[i] li = [23, 54, 67, 12, 7, 23, 54, 21] selection_sort(li) print(li)
2a23c2f535bbe81d15e227c8e07d8239f20d60e3
[ "Python" ]
10
Python
gy0109/arithmetic
af65c49fbaa384e5c2af8de1fa660adca84ba392
ac0c72c22796036602ba8c55e065039a2a6629dd
refs/heads/master
<repo_name>Alvaro-78/basic-js-counter<file_sep>/js-basics/src/intro-JS/funciones-flecha.js const greeting = ( name ) => { return `Hola ${ name }` }; console.log(greeting( "pepe" )); const getUser = () => ({ uuid: 'ACF1234', userName: "pepe" }); const user = getUser(); console.log(user); const getUserActive = (name) => ({ uuid: "pepe9876", userName: "joan" }); const userActive = getUserActive("Pepito"); console.log(userActive);<file_sep>/js-basics/src/intro-JS/destructuring.js const person = { namePerson: 'John', age: 34, job: 'plumber' }; const { namePerson,age } = person; console.log( namePerson, age ); // Asignamos un valor dado en person a getPerson const getPerson = ({ namePerson, age, job }) => { return { nameSecret: job, age2: age } }; const { nameSecret, age2 } = getPerson( person ); console.log(nameSecret, age2)<file_sep>/js-basics/src/intro-JS/arays-destructuring.js const characters = ["Goku", "Vegeta", "Trunks"]; const [ p1, p2, p3 ] = characters; console.log(p3); const returnArr = () => { return ['ABC', 123]; } const [ words, numbers ] = returnArr(); console.log(words, numbers)<file_sep>/js-basics/src/intro-JS/promise.js import { getHeroeById } from './intro-JS/import-export' // const promise = new Promise( (res, rej) => { // setTimeout( () => { // const heroe = getHeroeById(2); // console.table(heroe); // // res(); // rej('No se pudo encontrar al héroe') // }, 2000 ) // } ); // promise.then( Heroe => { // console.table('Heroe', Heroe) // }) // .catch( err => console.warn( err )) const getHeroeByIdAsync = ( id ) => { return new Promise( (res, rej) => { setTimeout( () => { const heroe = getHeroeById( id ); if( heroe) { res( heroe ); } else { rej('No se pudo encontrar al héroe') } console.table(heroe); }, 2000 ) } ); } getHeroeByIdAsync(2) .then( heroe => console.table) .catch( err => console.warn( err ))<file_sep>/counter-app/src/FirstApp.js import React from 'react'; import PropTypes from 'prop-types'; const FirstApp = ({ greeting, subtitle }) => { return ( <> <h1> { greeting } </h1> {/* <pre>{ JSON.stringify( greeting, null, 3) }</pre> */} <h3> { subtitle } </h3> </> ) } FirstApp.propTypes = { greeting: PropTypes.string.isRequired } FirstApp.defaultProps = { subtitle: "Soy un Subtítulo" } export default FirstApp; <file_sep>/js-basics/src/intro-JS/import-export.js import{ Heroes } from '../data/Heroes'; console.table(Heroes); // Buscamos Heroes por ID con el método find export const getHeroeById = (id) => Heroes.find((Heroe) => Heroe.id === id); // console.log(getHeroeById(4)); // Buscamos la editorial de los Heroes con el método filter const getHeroesByOwner = ( owner ) => Heroes.filter((Heroe) => Heroe.owner === owner); // console.table(getHeroesByOwner('Marvel')) <file_sep>/js-basics/src/intro-JS/objetos-literales.js const persona = { nombre: "pepe", apellido: "grillo", edad: 40, direccion: { calle:" penó de la conquesta", zip: 46920, lat: 19.4567, lng: 34.5678 } } // Cuidado Mutación de las propiedades // const persona2 = persona; // persona2.nombre = "peter" console.table(persona); // console.table(persona2) // Clonado del objeto con el spred operator const persona2 = { ...persona }; persona2.nombre = "bastet" console.table(persona2) <file_sep>/counter-app/src/CounterApp.js import React, { useState } from 'react'; import PropTypes from 'prop-types'; const CounterApp = ({ value }) => { const [number, setNumber] = useState(value); const handleIncrement = () => setNumber( number + 1 ) const handleReset = () => setNumber( value ) const handleDecrement = () => { if( number === 0 ) { return '' } setNumber( number - 1 ) } return ( <> <h1>CounterApp</h1> <h2> { number } </h2> <button type="submit" onClick={ handleIncrement }>+ 1</button> <button type="submit" onClick={ handleReset }>Reset</button> <button type="submit" onClick={ handleDecrement }>- 1</button> </> ) } CounterApp.propTypes = { value: PropTypes.number.isRequired } export default CounterApp; <file_sep>/js-basics/src/intro-JS/async-await.js // const getImgPromis = () => new Promise((res) => res('https://google.com')) // getImgPromis().then(console.log) // Mismo resultado , dos formas de hacer una llamada a una API // Controlamos el error con un try-catch const getImg = async () => { try { const apiKey = 'RSnS98lIRy8kdgDH5qUR3kjiSYEtHUk5'; const response = await fetch(`https://api.giphy.com/v1/gifs/random?api_key=${ apiKey }`); const { data } = await response.json(); const { url } = data.images.original; const img = document.createElement('img'); img.src = url; document.body.append(img); } catch (error) { console.error(error) } } getImg()
df0affbe9a006fb4e30c03d38e299bde33f49416
[ "JavaScript" ]
9
JavaScript
Alvaro-78/basic-js-counter
77907e87f3119ec6c1ad706e6ffe872f524dda60
519c480678a25555cfd635d2a81e0c912e04f95d
refs/heads/main
<repo_name>amaxwellshaffer/WorkoutLog-Server<file_sep>/Readme.md Workout Log Endpoints: /user/register POST adds a new user to the database ![Create User Screenshot](Docs/createUser.png) /user/login POST revalidate an existing user ![Login User Screenshot](Docs/loginUser.png) /log/ POST adds a new log to the database, owned by posting user ![Post Log Screenshot](Docs/postNewLog.png) /log/ GET view all posts by current user ![See All Posts Screenshot](Docs/getUsersLogs.png) /log/:id GET view logs with stated Id ![Get Logs By Id Screenshot](Docs/getLogById.png) /log/:id PUT Updates stated log entry if owned by the user ![Update Log Screenshot](Docs/updateLog.png) /log/:id DELETE Deletes stated log entry, if owned by the user ![Delete Log Screenshot](Docs/deleteLog.png) <file_sep>/controllers/logController.js const router = require('express').Router(); const Log = require('../models/log'); const bcrypt = require('bcryptjs'); const jwt = require('jsonwebtoken'); const validateSession = require('../middleware/validateSession'); router.get('/test', (req, res) =>{ res.send('test whatever'); }); // CREATE NEW LOG router.post('/', validateSession, (req, res) => { Log.create({ description: req.body.description, definition: req.body.definition, result: req.body.result, owner_id: req.user.id }) .then(log => res.status(200).json({Message: 'log successfully posted', log})) .catch(err => res.status(500).json({message: 'log posting failed', error: err})) }); // SEE ALL LOGS FOR AN INDIVIDUAL USER router.get('/', validateSession, (req, res) => { Log.findAll({ where: { owner_id: req.user.id } }) .then(logs => res.status(200).json({logs})) .catch(err => res.status(500).json({message: 'no logs found', error: err})) }); // GET INDIVIDUAL LOGS FOR USER BY :ID router.get('/:id', validateSession, (req, res) => { Log.findAll({ where: { id: req.params.id, owner_id: req.user.id } }) .then(logs => res.status(200).json({logs})) .catch(err => res.status(500).json({message: 'no logs found', error: err})) }); // UPDATE ENTRIES BY ID, USER MUST OWN router.put('/:id', validateSession, (req, res) => { Log.update(req.body, {where: {id: req.params.id, owner_id: req.user.id}}) .then(update => res.status(200).json({message: 'log updated', update})) .catch(err => res.status(500).json({message: 'could not update log', error: err})) }); // DELETE A POST, USER MUST OWN router.delete('/:id', validateSession, (req,res) => { Log.destroy({where: {id: req.params.id, owner_id: req.user.id}}) .then(deleted => res.status(200).json({message: 'log successfully deleted', deleted})) .catch(err => res.status(500).json({message: 'log could not be deleted', error: err})) }); module.exports = router;
252668707d522d417f2e197262a3811f66856581
[ "Markdown", "JavaScript" ]
2
Markdown
amaxwellshaffer/WorkoutLog-Server
1902175027d92b6c5376f08c5aa5a2f82048be6c
dcc63c1ed79061b406b11bc248041d19d4f4ff30
refs/heads/master
<repo_name>ceineke/node-opengl<file_sep>/binding.gyp { "targets": [ { "target_name": "node-opengl", "sources": [ "src/opengl.cc" ], 'link_settings': { 'libraries': [ '-lGL', '-lGLU' ] } } ] } <file_sep>/README.md # node-opengl (OpenGL bindings for node.js) ## 0. Notes This package is a companion to the [node-sdl](https://github.com/creationix/node-sdl) package. It was built so the OpenGL bindings for SDL could remain separate from the SDL library. If you are looking for something else try the [node-webgl](https://github.com/pufuwozu/node-webgl) project. ## 1. Installation This package depends on node-sdl and OpenGL/SDL libraries being present on the target system. The following should get SDL installed on Ubunutu: <pre>sudo apt-get install libsdl-mixer1.2-dev libsdl-image1.2-dev libsdl-ttf2.0-dev</pre> <file_sep>/src/opengl.cc #include <node.h> #include <v8.h> #include <GL/gl.h> #include <GL/glu.h> using namespace v8; using namespace node; namespace gl { struct Constant { Constant(const char* name, const unsigned int value) : name(name), value(value) { } const char* name; const unsigned int value; }; static struct Constant constants[] = { /* Primitives */ Constant("POINTS", GL_POINTS), Constant("LINES", GL_LINES), Constant("LINE_LOOP", GL_LINE_LOOP), Constant("LINE_STRIP", GL_LINE_STRIP), Constant("TRIANGLES", GL_TRIANGLES), Constant("TRIANGLE_STRIP", GL_TRIANGLE_STRIP), Constant("TRIANGLE_FAN", GL_TRIANGLE_FAN), Constant("QUADS", GL_QUADS), Constant("QUAD_STRIP", GL_QUAD_STRIP), Constant("POLYGON", GL_POLYGON), /* Vertex Arrays */ Constant("VERTEX_ARRAY", GL_VERTEX_ARRAY), Constant("NORMAL_ARRAY", GL_NORMAL_ARRAY), Constant("COLOR_ARRAY", GL_COLOR_ARRAY), Constant("INDEX_ARRAY", GL_INDEX_ARRAY), Constant("TEXTURE_COORD_ARRAY", GL_TEXTURE_COORD_ARRAY), Constant("EDGE_FLAG_ARRAY", GL_EDGE_FLAG_ARRAY), Constant("VERTEX_ARRAY_SIZE", GL_VERTEX_ARRAY_SIZE), Constant("VERTEX_ARRAY_TYPE", GL_VERTEX_ARRAY_TYPE), Constant("VERTEX_ARRAY_STRIDE", GL_VERTEX_ARRAY_STRIDE), Constant("NORMAL_ARRAY_TYPE", GL_NORMAL_ARRAY_TYPE), Constant("NORMAL_ARRAY_STRIDE", GL_NORMAL_ARRAY_STRIDE), Constant("COLOR_ARRAY_SIZE", GL_COLOR_ARRAY_SIZE), Constant("COLOR_ARRAY_TYPE", GL_COLOR_ARRAY_TYPE), Constant("COLOR_ARRAY_STRIDE", GL_COLOR_ARRAY_STRIDE), Constant("INDEX_ARRAY_TYPE", GL_INDEX_ARRAY_TYPE), Constant("INDEX_ARRAY_STRIDE", GL_INDEX_ARRAY_STRIDE), Constant("TEXTURE_COORD_ARRAY_SIZE", GL_TEXTURE_COORD_ARRAY_SIZE), Constant("TEXTURE_COORD_ARRAY_TYPE", GL_TEXTURE_COORD_ARRAY_TYPE), Constant("TEXTURE_COORD_ARRAY_STRIDE", GL_TEXTURE_COORD_ARRAY_STRIDE), Constant("EDGE_FLAG_ARRAY_STRIDE", GL_EDGE_FLAG_ARRAY_STRIDE), Constant("VERTEX_ARRAY_POINTER", GL_VERTEX_ARRAY_POINTER), Constant("NORMAL_ARRAY_POINTER", GL_NORMAL_ARRAY_POINTER), Constant("COLOR_ARRAY_POINTER", GL_COLOR_ARRAY_POINTER), Constant("INDEX_ARRAY_POINTER", GL_INDEX_ARRAY_POINTER), Constant("TEXTURE_COORD_ARRAY_POINTER", GL_TEXTURE_COORD_ARRAY_POINTER), Constant("EDGE_FLAG_ARRAY_POINTER", GL_EDGE_FLAG_ARRAY_POINTER), Constant("V2F", GL_V2F), Constant("V3F", GL_V3F), Constant("C4UB_V2F", GL_C4UB_V2F), Constant("C4UB_V3F", GL_C4UB_V3F), Constant("C3F_V3F", GL_C3F_V3F), Constant("N3F_V3F", GL_N3F_V3F), Constant("C4F_N3F_V3F", GL_C4F_N3F_V3F), Constant("T2F_V3F", GL_T2F_V3F), Constant("T4F_V4F", GL_T4F_V4F), Constant("T2F_C4UB_V3F", GL_T2F_C4UB_V3F), Constant("T2F_C3F_V3F", GL_T2F_C3F_V3F), Constant("T2F_N3F_V3F", GL_T2F_N3F_V3F), Constant("T2F_C4F_N3F_V3F", GL_T2F_C4F_N3F_V3F), Constant("T4F_C4F_N3F_V4F", GL_T4F_C4F_N3F_V4F), /* Matrix Mode */ Constant("MATRIX_MODE", GL_MATRIX_MODE), Constant("MODELVIEW", GL_MODELVIEW), Constant("PROJECTION", GL_PROJECTION), Constant("TEXTURE", GL_TEXTURE), /* Points */ Constant("POINT_SMOOTH", GL_POINT_SMOOTH), Constant("POINT_SIZE", GL_POINT_SIZE), Constant("POINT_SIZE_GRANULARITY", GL_POINT_SIZE_GRANULARITY), Constant("POINT_SIZE_RANGE", GL_POINT_SIZE_RANGE), /* Lines */ Constant("LINE_SMOOTH", GL_LINE_SMOOTH), Constant("LINE_STIPPLE", GL_LINE_STIPPLE), Constant("LINE_STIPPLE_PATTERN", GL_LINE_STIPPLE_PATTERN), Constant("LINE_STIPPLE_REPEAT", GL_LINE_STIPPLE_REPEAT), Constant("LINE_WIDTH", GL_LINE_WIDTH), Constant("LINE_WIDTH_GRANULARITY", GL_LINE_WIDTH_GRANULARITY), Constant("LINE_WIDTH_RANGE", GL_LINE_WIDTH_RANGE), /* Polygons */ Constant("POINT", GL_POINT), Constant("LINE", GL_LINE), Constant("FILL", GL_FILL), Constant("CW", GL_CW), Constant("CCW", GL_CCW), Constant("FRONT", GL_FRONT), Constant("BACK", GL_BACK), Constant("POLYGON_MODE", GL_POLYGON_MODE), Constant("POLYGON_SMOOTH", GL_POLYGON_SMOOTH), Constant("POLYGON_STIPPLE", GL_POLYGON_STIPPLE), Constant("EDGE_FLAG", GL_EDGE_FLAG), Constant("CULL_FACE", GL_CULL_FACE), Constant("CULL_FACE_MODE", GL_CULL_FACE_MODE), Constant("FRONT_FACE", GL_FRONT_FACE), Constant("POLYGON_OFFSET_FACTOR", GL_POLYGON_OFFSET_FACTOR), Constant("POLYGON_OFFSET_UNITS", GL_POLYGON_OFFSET_UNITS), Constant("POLYGON_OFFSET_POINT", GL_POLYGON_OFFSET_POINT), Constant("POLYGON_OFFSET_LINE", GL_POLYGON_OFFSET_LINE), Constant("POLYGON_OFFSET_FILL", GL_POLYGON_OFFSET_FILL), /* Display Lists */ Constant("COMPILE", GL_COMPILE), Constant("COMPILE_AND_EXECUTE", GL_COMPILE_AND_EXECUTE), Constant("LIST_BASE", GL_LIST_BASE), Constant("LIST_INDEX", GL_LIST_INDEX), Constant("LIST_MODE", GL_LIST_MODE), /* Depth buffer */ Constant("NEVER", GL_NEVER), Constant("LESS", GL_LESS), Constant("EQUAL", GL_EQUAL), Constant("LEQUAL", GL_LEQUAL), Constant("GREATER", GL_GREATER), Constant("NOTEQUAL", GL_NOTEQUAL), Constant("GEQUAL", GL_GEQUAL), Constant("ALWAYS", GL_ALWAYS), Constant("DEPTH_TEST", GL_DEPTH_TEST), Constant("DEPTH_BITS", GL_DEPTH_BITS), Constant("DEPTH_CLEAR_VALUE", GL_DEPTH_CLEAR_VALUE), Constant("DEPTH_FUNC", GL_DEPTH_FUNC), Constant("DEPTH_RANGE", GL_DEPTH_RANGE), Constant("DEPTH_WRITEMASK", GL_DEPTH_WRITEMASK), Constant("DEPTH_COMPONENT", GL_DEPTH_COMPONENT), /* Lighting */ Constant("LIGHTING", GL_LIGHTING), Constant("LIGHT0", GL_LIGHT0), Constant("LIGHT1", GL_LIGHT1), Constant("LIGHT2", GL_LIGHT2), Constant("LIGHT3", GL_LIGHT3), Constant("LIGHT4", GL_LIGHT4), Constant("LIGHT5", GL_LIGHT5), Constant("LIGHT6", GL_LIGHT6), Constant("LIGHT7", GL_LIGHT7), Constant("SPOT_EXPONENT", GL_SPOT_EXPONENT), Constant("SPOT_CUTOFF", GL_SPOT_CUTOFF), Constant("CONSTANT_ATTENUATION", GL_CONSTANT_ATTENUATION), Constant("LINEAR_ATTENUATION", GL_LINEAR_ATTENUATION), Constant("QUADRATIC_ATTENUATION", GL_QUADRATIC_ATTENUATION), Constant("AMBIENT", GL_AMBIENT), Constant("DIFFUSE", GL_DIFFUSE), Constant("SPECULAR", GL_SPECULAR), Constant("SHININESS", GL_SHININESS), Constant("EMISSION", GL_EMISSION), Constant("POSITION", GL_POSITION), Constant("SPOT_DIRECTION", GL_SPOT_DIRECTION), Constant("AMBIENT_AND_DIFFUSE", GL_AMBIENT_AND_DIFFUSE), Constant("COLOR_INDEXES", GL_COLOR_INDEXES), Constant("LIGHT_MODEL_TWO_SIDE", GL_LIGHT_MODEL_TWO_SIDE), Constant("LIGHT_MODEL_LOCAL_VIEWER", GL_LIGHT_MODEL_LOCAL_VIEWER), Constant("LIGHT_MODEL_AMBIENT", GL_LIGHT_MODEL_AMBIENT), Constant("FRONT_AND_BACK", GL_FRONT_AND_BACK), Constant("SHADE_MODEL", GL_SHADE_MODEL), Constant("FLAT", GL_FLAT), Constant("SMOOTH", GL_SMOOTH), Constant("COLOR_MATERIAL", GL_COLOR_MATERIAL), Constant("COLOR_MATERIAL_FACE", GL_COLOR_MATERIAL_FACE), Constant("COLOR_MATERIAL_PARAMETER", GL_COLOR_MATERIAL_PARAMETER), Constant("NORMALIZE", GL_NORMALIZE), /* User clipping planes */ Constant("CLIP_PLANE0", GL_CLIP_PLANE0), Constant("CLIP_PLANE1", GL_CLIP_PLANE1), Constant("CLIP_PLANE2", GL_CLIP_PLANE2), Constant("CLIP_PLANE3", GL_CLIP_PLANE3), Constant("CLIP_PLANE4", GL_CLIP_PLANE4), Constant("CLIP_PLANE5", GL_CLIP_PLANE5), /* Accumulation buffer */ Constant("ACCUM_RED_BITS", GL_ACCUM_RED_BITS), Constant("ACCUM_GREEN_BITS", GL_ACCUM_GREEN_BITS), Constant("ACCUM_BLUE_BITS", GL_ACCUM_BLUE_BITS), Constant("ACCUM_ALPHA_BITS", GL_ACCUM_ALPHA_BITS), Constant("ACCUM_CLEAR_VALUE", GL_ACCUM_CLEAR_VALUE), Constant("ACCUM", GL_ACCUM), Constant("ADD", GL_ADD), Constant("LOAD", GL_LOAD), Constant("MULT", GL_MULT), Constant("RETURN", GL_RETURN), /* Alpha testing */ Constant("ALPHA_TEST", GL_ALPHA_TEST), Constant("ALPHA_TEST_REF", GL_ALPHA_TEST_REF), Constant("ALPHA_TEST_FUNC", GL_ALPHA_TEST_FUNC), /* Blending */ Constant("BLEND", GL_BLEND), Constant("BLEND_SRC", GL_BLEND_SRC), Constant("BLEND_DST", GL_BLEND_DST), Constant("ZERO", GL_ZERO), Constant("ONE", GL_ONE), Constant("SRC_COLOR", GL_SRC_COLOR), Constant("ONE_MINUS_SRC_COLOR", GL_ONE_MINUS_SRC_COLOR), Constant("SRC_ALPHA", GL_SRC_ALPHA), Constant("ONE_MINUS_SRC_ALPHA", GL_ONE_MINUS_SRC_ALPHA), Constant("DST_ALPHA", GL_DST_ALPHA), Constant("ONE_MINUS_DST_ALPHA", GL_ONE_MINUS_DST_ALPHA), Constant("DST_COLOR", GL_DST_COLOR), Constant("ONE_MINUS_DST_COLOR", GL_ONE_MINUS_DST_COLOR), Constant("SRC_ALPHA_SATURATE", GL_SRC_ALPHA_SATURATE), /* Render Mode */ Constant("FEEDBACK", GL_FEEDBACK), Constant("RENDER", GL_RENDER), Constant("SELECT", GL_SELECT), /* Feedback */ Constant("2D", GL_2D), Constant("3D", GL_3D), Constant("3D_COLOR", GL_3D_COLOR), Constant("3D_COLOR_TEXTURE", GL_3D_COLOR_TEXTURE), Constant("4D_COLOR_TEXTURE", GL_4D_COLOR_TEXTURE), Constant("POINT_TOKEN", GL_POINT_TOKEN), Constant("LINE_TOKEN", GL_LINE_TOKEN), Constant("LINE_RESET_TOKEN", GL_LINE_RESET_TOKEN), Constant("POLYGON_TOKEN", GL_POLYGON_TOKEN), Constant("BITMAP_TOKEN", GL_BITMAP_TOKEN), Constant("DRAW_PIXEL_TOKEN", GL_DRAW_PIXEL_TOKEN), Constant("COPY_PIXEL_TOKEN", GL_COPY_PIXEL_TOKEN), Constant("PASS_THROUGH_TOKEN", GL_PASS_THROUGH_TOKEN), Constant("FEEDBACK_BUFFER_POINTER", GL_FEEDBACK_BUFFER_POINTER), Constant("FEEDBACK_BUFFER_SIZE", GL_FEEDBACK_BUFFER_SIZE), Constant("FEEDBACK_BUFFER_TYPE", GL_FEEDBACK_BUFFER_TYPE), /* Selection */ Constant("SELECTION_BUFFER_POINTER", GL_SELECTION_BUFFER_POINTER), Constant("SELECTION_BUFFER_SIZE", GL_SELECTION_BUFFER_SIZE), /* Fog */ Constant("FOG", GL_FOG), Constant("FOG_MODE", GL_FOG_MODE), Constant("FOG_DENSITY", GL_FOG_DENSITY), Constant("FOG_COLOR", GL_FOG_COLOR), Constant("FOG_INDEX", GL_FOG_INDEX), Constant("FOG_START", GL_FOG_START), Constant("FOG_END", GL_FOG_END), Constant("LINEAR", GL_LINEAR), Constant("EXP", GL_EXP), Constant("EXP2", GL_EXP2), /* Logic Ops */ Constant("LOGIC_OP", GL_LOGIC_OP), Constant("INDEX_LOGIC_OP", GL_INDEX_LOGIC_OP), Constant("COLOR_LOGIC_OP", GL_COLOR_LOGIC_OP), Constant("LOGIC_OP_MODE", GL_LOGIC_OP_MODE), Constant("CLEAR", GL_CLEAR), Constant("SET", GL_SET), Constant("COPY", GL_COPY), Constant("COPY_INVERTED", GL_COPY_INVERTED), Constant("NOOP", GL_NOOP), Constant("INVERT", GL_INVERT), Constant("AND", GL_AND), Constant("NAND", GL_NAND), Constant("OR", GL_OR), Constant("NOR", GL_NOR), Constant("XOR", GL_XOR), Constant("EQUIV", GL_EQUIV), Constant("AND_REVERSE", GL_AND_REVERSE), Constant("AND_INVERTED", GL_AND_INVERTED), Constant("OR_REVERSE", GL_OR_REVERSE), Constant("OR_INVERTED", GL_OR_INVERTED), /* Stencil */ Constant("STENCIL_BITS", GL_STENCIL_BITS), Constant("STENCIL_TEST", GL_STENCIL_TEST), Constant("STENCIL_CLEAR_VALUE", GL_STENCIL_CLEAR_VALUE), Constant("STENCIL_FUNC", GL_STENCIL_FUNC), Constant("STENCIL_VALUE_MASK", GL_STENCIL_VALUE_MASK), Constant("STENCIL_FAIL", GL_STENCIL_FAIL), Constant("STENCIL_PASS_DEPTH_FAIL", GL_STENCIL_PASS_DEPTH_FAIL), Constant("STENCIL_PASS_DEPTH_PASS", GL_STENCIL_PASS_DEPTH_PASS), Constant("STENCIL_REF", GL_STENCIL_REF), Constant("STENCIL_WRITEMASK", GL_STENCIL_WRITEMASK), Constant("STENCIL_INDEX", GL_STENCIL_INDEX), Constant("KEEP", GL_KEEP), Constant("REPLACE", GL_REPLACE), Constant("INCR", GL_INCR), Constant("DECR", GL_DECR), /* Buffers, Pixel Drawing/Reading */ Constant("NONE", GL_NONE), Constant("LEFT", GL_LEFT), Constant("RIGHT", GL_RIGHT), Constant("FRONT", GL_FRONT), Constant("BACK", GL_BACK), Constant("FRONT_AND_BACK", GL_FRONT_AND_BACK), Constant("FRONT_LEFT", GL_FRONT_LEFT), Constant("FRONT_RIGHT", GL_FRONT_RIGHT), Constant("BACK_LEFT", GL_BACK_LEFT), Constant("BACK_RIGHT", GL_BACK_RIGHT), Constant("AUX0", GL_AUX0), Constant("AUX1", GL_AUX1), Constant("AUX2", GL_AUX2), Constant("AUX3", GL_AUX3), Constant("COLOR_INDEX", GL_COLOR_INDEX), Constant("RED", GL_RED), Constant("GREEN", GL_GREEN), Constant("BLUE", GL_BLUE), Constant("ALPHA", GL_ALPHA), Constant("LUMINANCE", GL_LUMINANCE), Constant("LUMINANCE_ALPHA", GL_LUMINANCE_ALPHA), Constant("ALPHA_BITS", GL_ALPHA_BITS), Constant("RED_BITS", GL_RED_BITS), Constant("GREEN_BITS", GL_GREEN_BITS), Constant("BLUE_BITS", GL_BLUE_BITS), Constant("INDEX_BITS", GL_INDEX_BITS), Constant("SUBPIXEL_BITS", GL_SUBPIXEL_BITS), Constant("AUX_BUFFERS", GL_AUX_BUFFERS), Constant("READ_BUFFER", GL_READ_BUFFER), Constant("DRAW_BUFFER", GL_DRAW_BUFFER), Constant("DOUBLEBUFFER", GL_DOUBLEBUFFER), Constant("STEREO", GL_STEREO), Constant("BITMAP", GL_BITMAP), Constant("COLOR", GL_COLOR), Constant("DEPTH", GL_DEPTH), Constant("STENCIL", GL_STENCIL), Constant("DITHER", GL_DITHER), Constant("RGB", GL_RGB), Constant("RGBA", GL_RGBA), /* Implementation limits */ Constant("MAX_LIST_NESTING", GL_MAX_LIST_NESTING), Constant("MAX_EVAL_ORDER", GL_MAX_EVAL_ORDER), Constant("MAX_LIGHTS", GL_MAX_LIGHTS), Constant("MAX_CLIP_PLANES", GL_MAX_CLIP_PLANES), Constant("MAX_TEXTURE_SIZE", GL_MAX_TEXTURE_SIZE), Constant("MAX_PIXEL_MAP_TABLE", GL_MAX_PIXEL_MAP_TABLE), Constant("MAX_ATTRIB_STACK_DEPTH", GL_MAX_ATTRIB_STACK_DEPTH), Constant("MAX_MODELVIEW_STACK_DEPTH", GL_MAX_MODELVIEW_STACK_DEPTH), Constant("MAX_NAME_STACK_DEPTH", GL_MAX_NAME_STACK_DEPTH), Constant("MAX_PROJECTION_STACK_DEPTH", GL_MAX_PROJECTION_STACK_DEPTH), Constant("MAX_TEXTURE_STACK_DEPTH", GL_MAX_TEXTURE_STACK_DEPTH), Constant("MAX_VIEWPORT_DIMS", GL_MAX_VIEWPORT_DIMS), Constant("MAX_CLIENT_ATTRIB_STACK_DEPTH", GL_MAX_CLIENT_ATTRIB_STACK_DEPTH), /* Gets */ Constant("ATTRIB_STACK_DEPTH", GL_ATTRIB_STACK_DEPTH), Constant("CLIENT_ATTRIB_STACK_DEPTH", GL_CLIENT_ATTRIB_STACK_DEPTH), Constant("COLOR_CLEAR_VALUE", GL_COLOR_CLEAR_VALUE), Constant("COLOR_WRITEMASK", GL_COLOR_WRITEMASK), Constant("CURRENT_INDEX", GL_CURRENT_INDEX), Constant("CURRENT_COLOR", GL_CURRENT_COLOR), Constant("CURRENT_NORMAL", GL_CURRENT_NORMAL), Constant("CURRENT_RASTER_COLOR", GL_CURRENT_RASTER_COLOR), Constant("CURRENT_RASTER_DISTANCE", GL_CURRENT_RASTER_DISTANCE), Constant("CURRENT_RASTER_INDEX", GL_CURRENT_RASTER_INDEX), Constant("CURRENT_RASTER_POSITION", GL_CURRENT_RASTER_POSITION), Constant("CURRENT_RASTER_TEXTURE_COORDS", GL_CURRENT_RASTER_TEXTURE_COORDS), Constant("CURRENT_RASTER_POSITION_VALID", GL_CURRENT_RASTER_POSITION_VALID), Constant("CURRENT_TEXTURE_COORDS", GL_CURRENT_TEXTURE_COORDS), Constant("INDEX_CLEAR_VALUE", GL_INDEX_CLEAR_VALUE), Constant("INDEX_MODE", GL_INDEX_MODE), Constant("INDEX_WRITEMASK", GL_INDEX_WRITEMASK), Constant("MODELVIEW_MATRIX", GL_MODELVIEW_MATRIX), Constant("MODELVIEW_STACK_DEPTH", GL_MODELVIEW_STACK_DEPTH), Constant("NAME_STACK_DEPTH", GL_NAME_STACK_DEPTH), Constant("PROJECTION_MATRIX", GL_PROJECTION_MATRIX), Constant("PROJECTION_STACK_DEPTH", GL_PROJECTION_STACK_DEPTH), Constant("RENDER_MODE", GL_RENDER_MODE), Constant("RGBA_MODE", GL_RGBA_MODE), Constant("TEXTURE_MATRIX", GL_TEXTURE_MATRIX), Constant("TEXTURE_STACK_DEPTH", GL_TEXTURE_STACK_DEPTH), Constant("VIEWPORT", GL_VIEWPORT), /* Evaluators */ Constant("AUTO_NORMAL", GL_AUTO_NORMAL), Constant("MAP1_COLOR_4", GL_MAP1_COLOR_4), Constant("MAP1_INDEX", GL_MAP1_INDEX), Constant("MAP1_NORMAL", GL_MAP1_NORMAL), Constant("MAP1_TEXTURE_COORD_1", GL_MAP1_TEXTURE_COORD_1), Constant("MAP1_TEXTURE_COORD_2", GL_MAP1_TEXTURE_COORD_2), Constant("MAP1_TEXTURE_COORD_3", GL_MAP1_TEXTURE_COORD_3), Constant("MAP1_TEXTURE_COORD_4", GL_MAP1_TEXTURE_COORD_4), Constant("MAP1_VERTEX_3", GL_MAP1_VERTEX_3), Constant("MAP1_VERTEX_4", GL_MAP1_VERTEX_4), Constant("MAP2_COLOR_4", GL_MAP2_COLOR_4), Constant("MAP2_INDEX", GL_MAP2_INDEX), Constant("MAP2_NORMAL", GL_MAP2_NORMAL), Constant("MAP2_TEXTURE_COORD_1", GL_MAP2_TEXTURE_COORD_1), Constant("MAP2_TEXTURE_COORD_2", GL_MAP2_TEXTURE_COORD_2), Constant("MAP2_TEXTURE_COORD_3", GL_MAP2_TEXTURE_COORD_3), Constant("MAP2_TEXTURE_COORD_4", GL_MAP2_TEXTURE_COORD_4), Constant("MAP2_VERTEX_3", GL_MAP2_VERTEX_3), Constant("MAP2_VERTEX_4", GL_MAP2_VERTEX_4), Constant("MAP1_GRID_DOMAIN", GL_MAP1_GRID_DOMAIN), Constant("MAP1_GRID_SEGMENTS", GL_MAP1_GRID_SEGMENTS), Constant("MAP2_GRID_DOMAIN", GL_MAP2_GRID_DOMAIN), Constant("MAP2_GRID_SEGMENTS", GL_MAP2_GRID_SEGMENTS), Constant("COEFF", GL_COEFF), Constant("ORDER", GL_ORDER), Constant("DOMAIN", GL_DOMAIN), /* Hints */ Constant("PERSPECTIVE_CORRECTION_HINT", GL_PERSPECTIVE_CORRECTION_HINT), Constant("POINT_SMOOTH_HINT", GL_POINT_SMOOTH_HINT), Constant("LINE_SMOOTH_HINT", GL_LINE_SMOOTH_HINT), Constant("POLYGON_SMOOTH_HINT", GL_POLYGON_SMOOTH_HINT), Constant("FOG_HINT", GL_FOG_HINT), Constant("DONT_CARE", GL_DONT_CARE), Constant("FASTEST", GL_FASTEST), Constant("NICEST", GL_NICEST), /* Scissor box */ Constant("SCISSOR_BOX", GL_SCISSOR_BOX), Constant("SCISSOR_TEST", GL_SCISSOR_TEST), /* Pixel Mode / Transfer */ Constant("MAP_COLOR", GL_MAP_COLOR), Constant("MAP_STENCIL", GL_MAP_STENCIL), Constant("INDEX_SHIFT", GL_INDEX_SHIFT), Constant("INDEX_OFFSET", GL_INDEX_OFFSET), Constant("RED_SCALE", GL_RED_SCALE), Constant("RED_BIAS", GL_RED_BIAS), Constant("GREEN_SCALE", GL_GREEN_SCALE), Constant("GREEN_BIAS", GL_GREEN_BIAS), Constant("BLUE_SCALE", GL_BLUE_SCALE), Constant("BLUE_BIAS", GL_BLUE_BIAS), Constant("ALPHA_SCALE", GL_ALPHA_SCALE), Constant("ALPHA_BIAS", GL_ALPHA_BIAS), Constant("DEPTH_SCALE", GL_DEPTH_SCALE), Constant("DEPTH_BIAS", GL_DEPTH_BIAS), Constant("PIXEL_MAP_S_TO_S_SIZE", GL_PIXEL_MAP_S_TO_S_SIZE), Constant("PIXEL_MAP_I_TO_I_SIZE", GL_PIXEL_MAP_I_TO_I_SIZE), Constant("PIXEL_MAP_I_TO_R_SIZE", GL_PIXEL_MAP_I_TO_R_SIZE), Constant("PIXEL_MAP_I_TO_G_SIZE", GL_PIXEL_MAP_I_TO_G_SIZE), Constant("PIXEL_MAP_I_TO_B_SIZE", GL_PIXEL_MAP_I_TO_B_SIZE), Constant("PIXEL_MAP_I_TO_A_SIZE", GL_PIXEL_MAP_I_TO_A_SIZE), Constant("PIXEL_MAP_R_TO_R_SIZE", GL_PIXEL_MAP_R_TO_R_SIZE), Constant("PIXEL_MAP_G_TO_G_SIZE", GL_PIXEL_MAP_G_TO_G_SIZE), Constant("PIXEL_MAP_B_TO_B_SIZE", GL_PIXEL_MAP_B_TO_B_SIZE), Constant("PIXEL_MAP_A_TO_A_SIZE", GL_PIXEL_MAP_A_TO_A_SIZE), Constant("PIXEL_MAP_S_TO_S", GL_PIXEL_MAP_S_TO_S), Constant("PIXEL_MAP_I_TO_I", GL_PIXEL_MAP_I_TO_I), Constant("PIXEL_MAP_I_TO_R", GL_PIXEL_MAP_I_TO_R), Constant("PIXEL_MAP_I_TO_G", GL_PIXEL_MAP_I_TO_G), Constant("PIXEL_MAP_I_TO_B", GL_PIXEL_MAP_I_TO_B), Constant("PIXEL_MAP_I_TO_A", GL_PIXEL_MAP_I_TO_A), Constant("PIXEL_MAP_R_TO_R", GL_PIXEL_MAP_R_TO_R), Constant("PIXEL_MAP_G_TO_G", GL_PIXEL_MAP_G_TO_G), Constant("PIXEL_MAP_B_TO_B", GL_PIXEL_MAP_B_TO_B), Constant("PIXEL_MAP_A_TO_A", GL_PIXEL_MAP_A_TO_A), Constant("PACK_ALIGNMENT", GL_PACK_ALIGNMENT), Constant("PACK_LSB_FIRST", GL_PACK_LSB_FIRST), Constant("PACK_ROW_LENGTH", GL_PACK_ROW_LENGTH), Constant("PACK_SKIP_PIXELS", GL_PACK_SKIP_PIXELS), Constant("PACK_SKIP_ROWS", GL_PACK_SKIP_ROWS), Constant("PACK_SWAP_BYTES", GL_PACK_SWAP_BYTES), Constant("UNPACK_ALIGNMENT", GL_UNPACK_ALIGNMENT), Constant("UNPACK_LSB_FIRST", GL_UNPACK_LSB_FIRST), Constant("UNPACK_ROW_LENGTH", GL_UNPACK_ROW_LENGTH), Constant("UNPACK_SKIP_PIXELS", GL_UNPACK_SKIP_PIXELS), Constant("UNPACK_SKIP_ROWS", GL_UNPACK_SKIP_ROWS), Constant("UNPACK_SWAP_BYTES", GL_UNPACK_SWAP_BYTES), Constant("ZOOM_X", GL_ZOOM_X), Constant("ZOOM_Y", GL_ZOOM_Y), /* Texture mapping */ Constant("TEXTURE_ENV", GL_TEXTURE_ENV), Constant("TEXTURE_ENV_MODE", GL_TEXTURE_ENV_MODE), Constant("TEXTURE_1D", GL_TEXTURE_1D), Constant("TEXTURE_2D", GL_TEXTURE_2D), Constant("TEXTURE_WRAP_S", GL_TEXTURE_WRAP_S), Constant("TEXTURE_WRAP_T", GL_TEXTURE_WRAP_T), Constant("TEXTURE_MAG_FILTER", GL_TEXTURE_MAG_FILTER), Constant("TEXTURE_MIN_FILTER", GL_TEXTURE_MIN_FILTER), Constant("TEXTURE_ENV_COLOR", GL_TEXTURE_ENV_COLOR), Constant("TEXTURE_GEN_S", GL_TEXTURE_GEN_S), Constant("TEXTURE_GEN_T", GL_TEXTURE_GEN_T), Constant("TEXTURE_GEN_R", GL_TEXTURE_GEN_R), Constant("TEXTURE_GEN_Q", GL_TEXTURE_GEN_Q), Constant("TEXTURE_GEN_MODE", GL_TEXTURE_GEN_MODE), Constant("TEXTURE_BORDER_COLOR", GL_TEXTURE_BORDER_COLOR), Constant("TEXTURE_WIDTH", GL_TEXTURE_WIDTH), Constant("TEXTURE_HEIGHT", GL_TEXTURE_HEIGHT), Constant("TEXTURE_BORDER", GL_TEXTURE_BORDER), Constant("TEXTURE_COMPONENTS", GL_TEXTURE_COMPONENTS), Constant("TEXTURE_RED_SIZE", GL_TEXTURE_RED_SIZE), Constant("TEXTURE_GREEN_SIZE", GL_TEXTURE_GREEN_SIZE), Constant("TEXTURE_BLUE_SIZE", GL_TEXTURE_BLUE_SIZE), Constant("TEXTURE_ALPHA_SIZE", GL_TEXTURE_ALPHA_SIZE), Constant("TEXTURE_LUMINANCE_SIZE", GL_TEXTURE_LUMINANCE_SIZE), Constant("TEXTURE_INTENSITY_SIZE", GL_TEXTURE_INTENSITY_SIZE), Constant("NEAREST_MIPMAP_NEAREST", GL_NEAREST_MIPMAP_NEAREST), Constant("NEAREST_MIPMAP_LINEAR", GL_NEAREST_MIPMAP_LINEAR), Constant("LINEAR_MIPMAP_NEAREST", GL_LINEAR_MIPMAP_NEAREST), Constant("LINEAR_MIPMAP_LINEAR", GL_LINEAR_MIPMAP_LINEAR), Constant("OBJECT_LINEAR", GL_OBJECT_LINEAR), Constant("OBJECT_PLANE", GL_OBJECT_PLANE), Constant("EYE_LINEAR", GL_EYE_LINEAR), Constant("EYE_PLANE", GL_EYE_PLANE), Constant("SPHERE_MAP", GL_SPHERE_MAP), Constant("DECAL", GL_DECAL), Constant("MODULATE", GL_MODULATE), Constant("NEAREST", GL_NEAREST), Constant("REPEAT", GL_REPEAT), Constant("CLAMP", GL_CLAMP), Constant("S", GL_S), Constant("T", GL_T), Constant("R", GL_R), Constant("Q", GL_Q), /* Utility */ Constant("VENDOR", GL_VENDOR), Constant("RENDERER", GL_RENDERER), Constant("VERSION", GL_VERSION), Constant("EXTENSIONS", GL_EXTENSIONS), /* Errors */ Constant("NO_ERROR", GL_NO_ERROR), Constant("INVALID_ENUM", GL_INVALID_ENUM), Constant("INVALID_VALUE", GL_INVALID_VALUE), Constant("INVALID_OPERATION", GL_INVALID_OPERATION), Constant("STACK_OVERFLOW", GL_STACK_OVERFLOW), Constant("STACK_UNDERFLOW", GL_STACK_UNDERFLOW), Constant("OUT_OF_MEMORY", GL_OUT_OF_MEMORY), /* glPush/PopAttrib bits */ Constant("CURRENT_BIT", GL_CURRENT_BIT), Constant("POINT_BIT", GL_POINT_BIT), Constant("LINE_BIT", GL_LINE_BIT), Constant("POLYGON_BIT", GL_POLYGON_BIT), Constant("POLYGON_STIPPLE_BIT", GL_POLYGON_STIPPLE_BIT), Constant("PIXEL_MODE_BIT", GL_PIXEL_MODE_BIT), Constant("LIGHTING_BIT", GL_LIGHTING_BIT), Constant("FOG_BIT", GL_FOG_BIT), Constant("DEPTH_BUFFER_BIT", GL_DEPTH_BUFFER_BIT), Constant("ACCUM_BUFFER_BIT", GL_ACCUM_BUFFER_BIT), Constant("STENCIL_BUFFER_BIT", GL_STENCIL_BUFFER_BIT), Constant("VIEWPORT_BIT", GL_VIEWPORT_BIT), Constant("TRANSFORM_BIT", GL_TRANSFORM_BIT), Constant("ENABLE_BIT", GL_ENABLE_BIT), Constant("COLOR_BUFFER_BIT", GL_COLOR_BUFFER_BIT), Constant("HINT_BIT", GL_HINT_BIT), Constant("EVAL_BIT", GL_EVAL_BIT), Constant("LIST_BIT", GL_LIST_BIT), Constant("TEXTURE_BIT", GL_TEXTURE_BIT), Constant("SCISSOR_BIT", GL_SCISSOR_BIT), Constant("ALL_ATTRIB_BITS", GL_ALL_ATTRIB_BITS), /* * OpenGL 1.1 */ Constant("PROXY_TEXTURE_1D", GL_PROXY_TEXTURE_1D), Constant("PROXY_TEXTURE_2D", GL_PROXY_TEXTURE_2D), Constant("TEXTURE_PRIORITY", GL_TEXTURE_PRIORITY), Constant("TEXTURE_RESIDENT", GL_TEXTURE_RESIDENT), Constant("TEXTURE_BINDING_1D", GL_TEXTURE_BINDING_1D), Constant("TEXTURE_BINDING_2D", GL_TEXTURE_BINDING_2D), Constant("TEXTURE_INTERNAL_FORMAT", GL_TEXTURE_INTERNAL_FORMAT), Constant("ALPHA4", GL_ALPHA4), Constant("ALPHA8", GL_ALPHA8), Constant("ALPHA12", GL_ALPHA12), Constant("ALPHA16", GL_ALPHA16), Constant("LUMINANCE4", GL_LUMINANCE4), Constant("LUMINANCE8", GL_LUMINANCE8), Constant("LUMINANCE12", GL_LUMINANCE12), Constant("LUMINANCE16", GL_LUMINANCE16), Constant("LUMINANCE4_ALPHA4", GL_LUMINANCE4_ALPHA4), Constant("LUMINANCE6_ALPHA2", GL_LUMINANCE6_ALPHA2), Constant("LUMINANCE8_ALPHA8", GL_LUMINANCE8_ALPHA8), Constant("LUMINANCE12_ALPHA4", GL_LUMINANCE12_ALPHA4), Constant("LUMINANCE12_ALPHA12", GL_LUMINANCE12_ALPHA12), Constant("LUMINANCE16_ALPHA16", GL_LUMINANCE16_ALPHA16), Constant("INTENSITY", GL_INTENSITY), Constant("INTENSITY4", GL_INTENSITY4), Constant("INTENSITY8", GL_INTENSITY8), Constant("INTENSITY12", GL_INTENSITY12), Constant("INTENSITY16", GL_INTENSITY16), Constant("R3_G3_B2", GL_R3_G3_B2), Constant("RGB4", GL_RGB4), Constant("RGB5", GL_RGB5), Constant("RGB8", GL_RGB8), Constant("RGB10", GL_RGB10), Constant("RGB12", GL_RGB12), Constant("RGB16", GL_RGB16), Constant("RGBA2", GL_RGBA2), Constant("RGBA4", GL_RGBA4), Constant("RGB5_A1", GL_RGB5_A1), Constant("RGBA8", GL_RGBA8), Constant("RGB10_A2", GL_RGB10_A2), Constant("RGBA12", GL_RGBA12), Constant("RGBA16", GL_RGBA16), Constant("CLIENT_PIXEL_STORE_BIT", GL_CLIENT_PIXEL_STORE_BIT), Constant("CLIENT_VERTEX_ARRAY_BIT", GL_CLIENT_VERTEX_ARRAY_BIT), Constant("ALL_CLIENT_ATTRIB_BITS", GL_ALL_CLIENT_ATTRIB_BITS), Constant("CLIENT_ALL_ATTRIB_BITS", GL_CLIENT_ALL_ATTRIB_BITS), /* * OpenGL 1.2 */ Constant("RESCALE_NORMAL", GL_RESCALE_NORMAL), Constant("CLAMP_TO_EDGE", GL_CLAMP_TO_EDGE), Constant("MAX_ELEMENTS_VERTICES", GL_MAX_ELEMENTS_VERTICES), Constant("MAX_ELEMENTS_INDICES", GL_MAX_ELEMENTS_INDICES), Constant("BGR", GL_BGR), Constant("BGRA", GL_BGRA), Constant("UNSIGNED_BYTE_3_3_2", GL_UNSIGNED_BYTE_3_3_2), Constant("UNSIGNED_BYTE_2_3_3_REV", GL_UNSIGNED_BYTE_2_3_3_REV), Constant("UNSIGNED_SHORT_5_6_5", GL_UNSIGNED_SHORT_5_6_5), Constant("UNSIGNED_SHORT_5_6_5_REV", GL_UNSIGNED_SHORT_5_6_5_REV), Constant("UNSIGNED_SHORT_4_4_4_4", GL_UNSIGNED_SHORT_4_4_4_4), Constant("UNSIGNED_SHORT_4_4_4_4_REV", GL_UNSIGNED_SHORT_4_4_4_4_REV), Constant("UNSIGNED_SHORT_5_5_5_1", GL_UNSIGNED_SHORT_5_5_5_1), Constant("UNSIGNED_SHORT_1_5_5_5_REV", GL_UNSIGNED_SHORT_1_5_5_5_REV), Constant("UNSIGNED_INT_8_8_8_8", GL_UNSIGNED_INT_8_8_8_8), Constant("UNSIGNED_INT_8_8_8_8_REV", GL_UNSIGNED_INT_8_8_8_8_REV), Constant("UNSIGNED_INT_10_10_10_2", GL_UNSIGNED_INT_10_10_10_2), Constant("UNSIGNED_INT_2_10_10_10_REV", GL_UNSIGNED_INT_2_10_10_10_REV), Constant("LIGHT_MODEL_COLOR_CONTROL", GL_LIGHT_MODEL_COLOR_CONTROL), Constant("SINGLE_COLOR", GL_SINGLE_COLOR), Constant("SEPARATE_SPECULAR_COLOR", GL_SEPARATE_SPECULAR_COLOR), Constant("TEXTURE_MIN_LOD", GL_TEXTURE_MIN_LOD), Constant("TEXTURE_MAX_LOD", GL_TEXTURE_MAX_LOD), Constant("TEXTURE_BASE_LEVEL", GL_TEXTURE_BASE_LEVEL), Constant("TEXTURE_MAX_LEVEL", GL_TEXTURE_MAX_LEVEL), Constant("SMOOTH_POINT_SIZE_RANGE", GL_SMOOTH_POINT_SIZE_RANGE), Constant("SMOOTH_POINT_SIZE_GRANULARITY", GL_SMOOTH_POINT_SIZE_GRANULARITY), Constant("SMOOTH_LINE_WIDTH_RANGE", GL_SMOOTH_LINE_WIDTH_RANGE), Constant("SMOOTH_LINE_WIDTH_GRANULARITY", GL_SMOOTH_LINE_WIDTH_GRANULARITY), Constant("ALIASED_POINT_SIZE_RANGE", GL_ALIASED_POINT_SIZE_RANGE), Constant("ALIASED_LINE_WIDTH_RANGE", GL_ALIASED_LINE_WIDTH_RANGE), Constant("PACK_SKIP_IMAGES", GL_PACK_SKIP_IMAGES), Constant("PACK_IMAGE_HEIGHT", GL_PACK_IMAGE_HEIGHT), Constant("UNPACK_SKIP_IMAGES", GL_UNPACK_SKIP_IMAGES), Constant("UNPACK_IMAGE_HEIGHT", GL_UNPACK_IMAGE_HEIGHT), Constant("TEXTURE_3D", GL_TEXTURE_3D), Constant("PROXY_TEXTURE_3D", GL_PROXY_TEXTURE_3D), Constant("TEXTURE_DEPTH", GL_TEXTURE_DEPTH), Constant("TEXTURE_WRAP_R", GL_TEXTURE_WRAP_R), Constant("MAX_3D_TEXTURE_SIZE", GL_MAX_3D_TEXTURE_SIZE), Constant("TEXTURE_BINDING_3D", GL_TEXTURE_BINDING_3D), /* * GL_ARB_imaging */ Constant("CONSTANT_COLOR", GL_CONSTANT_COLOR), Constant("ONE_MINUS_CONSTANT_COLOR", GL_ONE_MINUS_CONSTANT_COLOR), Constant("CONSTANT_ALPHA", GL_CONSTANT_ALPHA), Constant("ONE_MINUS_CONSTANT_ALPHA", GL_ONE_MINUS_CONSTANT_ALPHA), Constant("COLOR_TABLE", GL_COLOR_TABLE), Constant("POST_CONVOLUTION_COLOR_TABLE", GL_POST_CONVOLUTION_COLOR_TABLE), Constant("POST_COLOR_MATRIX_COLOR_TABLE", GL_POST_COLOR_MATRIX_COLOR_TABLE), Constant("PROXY_COLOR_TABLE", GL_PROXY_COLOR_TABLE), Constant("PROXY_POST_CONVOLUTION_COLOR_TABLE", GL_PROXY_POST_CONVOLUTION_COLOR_TABLE), Constant("PROXY_POST_COLOR_MATRIX_COLOR_TABLE", GL_PROXY_POST_COLOR_MATRIX_COLOR_TABLE), Constant("COLOR_TABLE_SCALE", GL_COLOR_TABLE_SCALE), Constant("COLOR_TABLE_BIAS", GL_COLOR_TABLE_BIAS), Constant("COLOR_TABLE_FORMAT", GL_COLOR_TABLE_FORMAT), Constant("COLOR_TABLE_WIDTH", GL_COLOR_TABLE_WIDTH), Constant("COLOR_TABLE_RED_SIZE", GL_COLOR_TABLE_RED_SIZE), Constant("COLOR_TABLE_GREEN_SIZE", GL_COLOR_TABLE_GREEN_SIZE), Constant("COLOR_TABLE_BLUE_SIZE", GL_COLOR_TABLE_BLUE_SIZE), Constant("COLOR_TABLE_ALPHA_SIZE", GL_COLOR_TABLE_ALPHA_SIZE), Constant("COLOR_TABLE_LUMINANCE_SIZE", GL_COLOR_TABLE_LUMINANCE_SIZE), Constant("COLOR_TABLE_INTENSITY_SIZE", GL_COLOR_TABLE_INTENSITY_SIZE), Constant("CONVOLUTION_1D", GL_CONVOLUTION_1D), Constant("CONVOLUTION_2D", GL_CONVOLUTION_2D), Constant("SEPARABLE_2D", GL_SEPARABLE_2D), Constant("CONVOLUTION_BORDER_MODE", GL_CONVOLUTION_BORDER_MODE), Constant("CONVOLUTION_FILTER_SCALE", GL_CONVOLUTION_FILTER_SCALE), Constant("CONVOLUTION_FILTER_BIAS", GL_CONVOLUTION_FILTER_BIAS), Constant("REDUCE", GL_REDUCE), Constant("CONVOLUTION_FORMAT", GL_CONVOLUTION_FORMAT), Constant("CONVOLUTION_WIDTH", GL_CONVOLUTION_WIDTH), Constant("CONVOLUTION_HEIGHT", GL_CONVOLUTION_HEIGHT), Constant("MAX_CONVOLUTION_WIDTH", GL_MAX_CONVOLUTION_WIDTH), Constant("MAX_CONVOLUTION_HEIGHT", GL_MAX_CONVOLUTION_HEIGHT), Constant("POST_CONVOLUTION_RED_SCALE", GL_POST_CONVOLUTION_RED_SCALE), Constant("POST_CONVOLUTION_GREEN_SCALE", GL_POST_CONVOLUTION_GREEN_SCALE), Constant("POST_CONVOLUTION_BLUE_SCALE", GL_POST_CONVOLUTION_BLUE_SCALE), Constant("POST_CONVOLUTION_ALPHA_SCALE", GL_POST_CONVOLUTION_ALPHA_SCALE), Constant("POST_CONVOLUTION_RED_BIAS", GL_POST_CONVOLUTION_RED_BIAS), Constant("POST_CONVOLUTION_GREEN_BIAS", GL_POST_CONVOLUTION_GREEN_BIAS), Constant("POST_CONVOLUTION_BLUE_BIAS", GL_POST_CONVOLUTION_BLUE_BIAS), Constant("POST_CONVOLUTION_ALPHA_BIAS", GL_POST_CONVOLUTION_ALPHA_BIAS), Constant("CONSTANT_BORDER", GL_CONSTANT_BORDER), Constant("REPLICATE_BORDER", GL_REPLICATE_BORDER), Constant("CONVOLUTION_BORDER_COLOR", GL_CONVOLUTION_BORDER_COLOR), Constant("COLOR_MATRIX", GL_COLOR_MATRIX), Constant("COLOR_MATRIX_STACK_DEPTH", GL_COLOR_MATRIX_STACK_DEPTH), Constant("MAX_COLOR_MATRIX_STACK_DEPTH", GL_MAX_COLOR_MATRIX_STACK_DEPTH), Constant("POST_COLOR_MATRIX_RED_SCALE", GL_POST_COLOR_MATRIX_RED_SCALE), Constant("POST_COLOR_MATRIX_GREEN_SCALE", GL_POST_COLOR_MATRIX_GREEN_SCALE), Constant("POST_COLOR_MATRIX_BLUE_SCALE", GL_POST_COLOR_MATRIX_BLUE_SCALE), Constant("POST_COLOR_MATRIX_ALPHA_SCALE", GL_POST_COLOR_MATRIX_ALPHA_SCALE), Constant("POST_COLOR_MATRIX_RED_BIAS", GL_POST_COLOR_MATRIX_RED_BIAS), Constant("POST_COLOR_MATRIX_GREEN_BIAS", GL_POST_COLOR_MATRIX_GREEN_BIAS), Constant("POST_COLOR_MATRIX_BLUE_BIAS", GL_POST_COLOR_MATRIX_BLUE_BIAS), Constant("POST_COLOR_MATRIX_ALPHA_BIAS", GL_POST_COLOR_MATRIX_ALPHA_BIAS), Constant("HISTOGRAM", GL_HISTOGRAM), Constant("PROXY_HISTOGRAM", GL_PROXY_HISTOGRAM), Constant("HISTOGRAM_WIDTH", GL_HISTOGRAM_WIDTH), Constant("HISTOGRAM_FORMAT", GL_HISTOGRAM_FORMAT), Constant("HISTOGRAM_RED_SIZE", GL_HISTOGRAM_RED_SIZE), Constant("HISTOGRAM_GREEN_SIZE", GL_HISTOGRAM_GREEN_SIZE), Constant("HISTOGRAM_BLUE_SIZE", GL_HISTOGRAM_BLUE_SIZE), Constant("HISTOGRAM_ALPHA_SIZE", GL_HISTOGRAM_ALPHA_SIZE), Constant("HISTOGRAM_LUMINANCE_SIZE", GL_HISTOGRAM_LUMINANCE_SIZE), Constant("HISTOGRAM_SINK", GL_HISTOGRAM_SINK), Constant("MINMAX", GL_MINMAX), Constant("MINMAX_FORMAT", GL_MINMAX_FORMAT), Constant("MINMAX_SINK", GL_MINMAX_SINK), Constant("TABLE_TOO_LARGE", GL_TABLE_TOO_LARGE), Constant("BLEND_EQUATION", GL_BLEND_EQUATION), Constant("MIN", GL_MIN), Constant("MAX", GL_MAX), Constant("FUNC_ADD", GL_FUNC_ADD), Constant("FUNC_SUBTRACT", GL_FUNC_SUBTRACT), Constant("FUNC_REVERSE_SUBTRACT", GL_FUNC_REVERSE_SUBTRACT), Constant("BLEND_COLOR", GL_BLEND_COLOR), /* * OpenGL 1.3 */ /* multitexture */ Constant("TEXTURE0", GL_TEXTURE0), Constant("TEXTURE1", GL_TEXTURE1), Constant("TEXTURE2", GL_TEXTURE2), Constant("TEXTURE3", GL_TEXTURE3), Constant("TEXTURE4", GL_TEXTURE4), Constant("TEXTURE5", GL_TEXTURE5), Constant("TEXTURE6", GL_TEXTURE6), Constant("TEXTURE7", GL_TEXTURE7), Constant("TEXTURE8", GL_TEXTURE8), Constant("TEXTURE9", GL_TEXTURE9), Constant("TEXTURE10", GL_TEXTURE10), Constant("TEXTURE11", GL_TEXTURE11), Constant("TEXTURE12", GL_TEXTURE12), Constant("TEXTURE13", GL_TEXTURE13), Constant("TEXTURE14", GL_TEXTURE14), Constant("TEXTURE15", GL_TEXTURE15), Constant("TEXTURE16", GL_TEXTURE16), Constant("TEXTURE17", GL_TEXTURE17), Constant("TEXTURE18", GL_TEXTURE18), Constant("TEXTURE19", GL_TEXTURE19), Constant("TEXTURE20", GL_TEXTURE20), Constant("TEXTURE21", GL_TEXTURE21), Constant("TEXTURE22", GL_TEXTURE22), Constant("TEXTURE23", GL_TEXTURE23), Constant("TEXTURE24", GL_TEXTURE24), Constant("TEXTURE25", GL_TEXTURE25), Constant("TEXTURE26", GL_TEXTURE26), Constant("TEXTURE27", GL_TEXTURE27), Constant("TEXTURE28", GL_TEXTURE28), Constant("TEXTURE29", GL_TEXTURE29), Constant("TEXTURE30", GL_TEXTURE30), Constant("TEXTURE31", GL_TEXTURE31), Constant("ACTIVE_TEXTURE", GL_ACTIVE_TEXTURE), Constant("CLIENT_ACTIVE_TEXTURE", GL_CLIENT_ACTIVE_TEXTURE), Constant("MAX_TEXTURE_UNITS", GL_MAX_TEXTURE_UNITS), /* texture_cube_map */ Constant("NORMAL_MAP", GL_NORMAL_MAP), Constant("REFLECTION_MAP", GL_REFLECTION_MAP), Constant("TEXTURE_CUBE_MAP", GL_TEXTURE_CUBE_MAP), Constant("TEXTURE_BINDING_CUBE_MAP", GL_TEXTURE_BINDING_CUBE_MAP), Constant("TEXTURE_CUBE_MAP_POSITIVE_X", GL_TEXTURE_CUBE_MAP_POSITIVE_X), Constant("TEXTURE_CUBE_MAP_NEGATIVE_X", GL_TEXTURE_CUBE_MAP_NEGATIVE_X), Constant("TEXTURE_CUBE_MAP_POSITIVE_Y", GL_TEXTURE_CUBE_MAP_POSITIVE_Y), Constant("TEXTURE_CUBE_MAP_NEGATIVE_Y", GL_TEXTURE_CUBE_MAP_NEGATIVE_Y), Constant("TEXTURE_CUBE_MAP_POSITIVE_Z", GL_TEXTURE_CUBE_MAP_POSITIVE_Z), Constant("TEXTURE_CUBE_MAP_NEGATIVE_Z", GL_TEXTURE_CUBE_MAP_NEGATIVE_Z), Constant("PROXY_TEXTURE_CUBE_MAP", GL_PROXY_TEXTURE_CUBE_MAP), Constant("MAX_CUBE_MAP_TEXTURE_SIZE", GL_MAX_CUBE_MAP_TEXTURE_SIZE), /* texture_compression */ Constant("COMPRESSED_ALPHA", GL_COMPRESSED_ALPHA), Constant("COMPRESSED_LUMINANCE", GL_COMPRESSED_LUMINANCE), Constant("COMPRESSED_LUMINANCE_ALPHA", GL_COMPRESSED_LUMINANCE_ALPHA), Constant("COMPRESSED_INTENSITY", GL_COMPRESSED_INTENSITY), Constant("COMPRESSED_RGB", GL_COMPRESSED_RGB), Constant("COMPRESSED_RGBA", GL_COMPRESSED_RGBA), Constant("TEXTURE_COMPRESSION_HINT", GL_TEXTURE_COMPRESSION_HINT), Constant("TEXTURE_COMPRESSED_IMAGE_SIZE", GL_TEXTURE_COMPRESSED_IMAGE_SIZE), Constant("TEXTURE_COMPRESSED", GL_TEXTURE_COMPRESSED), Constant("NUM_COMPRESSED_TEXTURE_FORMATS", GL_NUM_COMPRESSED_TEXTURE_FORMATS), Constant("COMPRESSED_TEXTURE_FORMATS", GL_COMPRESSED_TEXTURE_FORMATS), /* multisample */ Constant("MULTISAMPLE", GL_MULTISAMPLE), Constant("SAMPLE_ALPHA_TO_COVERAGE", GL_SAMPLE_ALPHA_TO_COVERAGE), Constant("SAMPLE_ALPHA_TO_ONE", GL_SAMPLE_ALPHA_TO_ONE), Constant("SAMPLE_COVERAGE", GL_SAMPLE_COVERAGE), Constant("SAMPLE_BUFFERS", GL_SAMPLE_BUFFERS), Constant("SAMPLES", GL_SAMPLES), Constant("SAMPLE_COVERAGE_VALUE", GL_SAMPLE_COVERAGE_VALUE), Constant("SAMPLE_COVERAGE_INVERT", GL_SAMPLE_COVERAGE_INVERT), Constant("MULTISAMPLE_BIT", GL_MULTISAMPLE_BIT), /* transpose_matrix */ Constant("TRANSPOSE_MODELVIEW_MATRIX", GL_TRANSPOSE_MODELVIEW_MATRIX), Constant("TRANSPOSE_PROJECTION_MATRIX", GL_TRANSPOSE_PROJECTION_MATRIX), Constant("TRANSPOSE_TEXTURE_MATRIX", GL_TRANSPOSE_TEXTURE_MATRIX), Constant("TRANSPOSE_COLOR_MATRIX", GL_TRANSPOSE_COLOR_MATRIX), /* texture_env_combine */ Constant("COMBINE", GL_COMBINE), Constant("COMBINE_RGB", GL_COMBINE_RGB), Constant("COMBINE_ALPHA", GL_COMBINE_ALPHA), Constant("SOURCE0_RGB", GL_SOURCE0_RGB), Constant("SOURCE1_RGB", GL_SOURCE1_RGB), Constant("SOURCE2_RGB", GL_SOURCE2_RGB), Constant("SOURCE0_ALPHA", GL_SOURCE0_ALPHA), Constant("SOURCE1_ALPHA", GL_SOURCE1_ALPHA), Constant("SOURCE2_ALPHA", GL_SOURCE2_ALPHA), Constant("OPERAND0_RGB", GL_OPERAND0_RGB), Constant("OPERAND1_RGB", GL_OPERAND1_RGB), Constant("OPERAND2_RGB", GL_OPERAND2_RGB), Constant("OPERAND0_ALPHA", GL_OPERAND0_ALPHA), Constant("OPERAND1_ALPHA", GL_OPERAND1_ALPHA), Constant("OPERAND2_ALPHA", GL_OPERAND2_ALPHA), Constant("RGB_SCALE", GL_RGB_SCALE), Constant("ADD_SIGNED", GL_ADD_SIGNED), Constant("INTERPOLATE", GL_INTERPOLATE), Constant("SUBTRACT", GL_SUBTRACT), Constant("CONSTANT", GL_CONSTANT), Constant("PRIMARY_COLOR", GL_PRIMARY_COLOR), Constant("PREVIOUS", GL_PREVIOUS), /* texture_env_dot3 */ Constant("DOT3_RGB", GL_DOT3_RGB), Constant("DOT3_RGBA", GL_DOT3_RGBA), /* texture_border_clamp */ Constant("CLAMP_TO_BORDER", GL_CLAMP_TO_BORDER), /* * GL_ARB_multitexture (ARB extension 1 and OpenGL 1.2.1) */ Constant("TEXTURE0_ARB", GL_TEXTURE0_ARB), Constant("TEXTURE1_ARB", GL_TEXTURE1_ARB), Constant("TEXTURE2_ARB", GL_TEXTURE2_ARB), Constant("TEXTURE3_ARB", GL_TEXTURE3_ARB), Constant("TEXTURE4_ARB", GL_TEXTURE4_ARB), Constant("TEXTURE5_ARB", GL_TEXTURE5_ARB), Constant("TEXTURE6_ARB", GL_TEXTURE6_ARB), Constant("TEXTURE7_ARB", GL_TEXTURE7_ARB), Constant("TEXTURE8_ARB", GL_TEXTURE8_ARB), Constant("TEXTURE9_ARB", GL_TEXTURE9_ARB), Constant("TEXTURE10_ARB", GL_TEXTURE10_ARB), Constant("TEXTURE11_ARB", GL_TEXTURE11_ARB), Constant("TEXTURE12_ARB", GL_TEXTURE12_ARB), Constant("TEXTURE13_ARB", GL_TEXTURE13_ARB), Constant("TEXTURE14_ARB", GL_TEXTURE14_ARB), Constant("TEXTURE15_ARB", GL_TEXTURE15_ARB), Constant("TEXTURE16_ARB", GL_TEXTURE16_ARB), Constant("TEXTURE17_ARB", GL_TEXTURE17_ARB), Constant("TEXTURE18_ARB", GL_TEXTURE18_ARB), Constant("TEXTURE19_ARB", GL_TEXTURE19_ARB), Constant("TEXTURE20_ARB", GL_TEXTURE20_ARB), Constant("TEXTURE21_ARB", GL_TEXTURE21_ARB), Constant("TEXTURE22_ARB", GL_TEXTURE22_ARB), Constant("TEXTURE23_ARB", GL_TEXTURE23_ARB), Constant("TEXTURE24_ARB", GL_TEXTURE24_ARB), Constant("TEXTURE25_ARB", GL_TEXTURE25_ARB), Constant("TEXTURE26_ARB", GL_TEXTURE26_ARB), Constant("TEXTURE27_ARB", GL_TEXTURE27_ARB), Constant("TEXTURE28_ARB", GL_TEXTURE28_ARB), Constant("TEXTURE29_ARB", GL_TEXTURE29_ARB), Constant("TEXTURE30_ARB", GL_TEXTURE30_ARB), Constant("TEXTURE31_ARB", GL_TEXTURE31_ARB), Constant("ACTIVE_TEXTURE_ARB", GL_ACTIVE_TEXTURE_ARB), Constant("CLIENT_ACTIVE_TEXTURE_ARB", GL_CLIENT_ACTIVE_TEXTURE_ARB), Constant("MAX_TEXTURE_UNITS_ARB", GL_MAX_TEXTURE_UNITS_ARB), }; #define ARGS_IS_LENGTH(len) \ if (args.Length() != len) { \ return ThrowException(Exception::TypeError(String::New("Invalid number arguments: __FUNCTION__ expects len arguments"))); \ } #define ARG_AS_NUMBER(num) \ if (!(args[num]->IsNumber())) { \ return ThrowException(Exception::TypeError(String::New("Invalid number arguments: __FUNCTION__ expects argument num as a Number"))); \ } \ float arg_ ## num = args[num]->NumberValue(); #define ARG_AS_INT32(num) \ if (!(args[num]->IsNumber())) { \ return ThrowException(Exception::TypeError(String::New("Invalid number arguments: __FUNCTION__ expects argument num as a Number"))); \ } \ int32_t arg_ ## num = args[num]->Int32Value(); #define ARG_AS_ARRAY(num) \ if (!(args[num]->IsNumber())) { \ return ThrowException(Exception::TypeError(String::New("Invalid number arguments: __FUNCTION__ expects argument num as a Number"))); \ } \ Handle<Object> arg_ ## num = args[num]->ToObject(); #define ARG(num) \ arg_ ## num #define ARG0 ARG(0) #define ARG1 ARG(1) #define ARG2 ARG(2) #define ARG3 ARG(3) #define ARG4 ARG(4) #define ARG5 ARG(5) #define ARG6 ARG(6) #define ARG7 ARG(7) #define ARG8 ARG(8) #define ARG9 ARG(9) static Handle<Value> ClearIndex(const Arguments& args) { HandleScope scope; ARGS_IS_LENGTH(1); ARG_AS_NUMBER(0); glClearIndex((GLfloat) ARG0); return Undefined(); } static Handle<Value> ClearColor(const Arguments& args) { HandleScope scope; ARGS_IS_LENGTH(4); ARG_AS_NUMBER(0); ARG_AS_NUMBER(1); ARG_AS_NUMBER(2); ARG_AS_NUMBER(3); glClearColor((GLclampf) ARG0, (GLclampf) ARG1, (GLclampf) ARG2, (GLclampf) ARG3); return Undefined(); } static Handle<Value> IndexMask(const Arguments& args) { HandleScope scope; ARGS_IS_LENGTH(1); ARG_AS_NUMBER(0); glIndexMask((GLclampf) ARG0); return Undefined(); } static Handle<Value> ColorMask(const Arguments& args) { HandleScope scope; ARGS_IS_LENGTH(4); ARG_AS_NUMBER(0); ARG_AS_NUMBER(1); ARG_AS_NUMBER(2); ARG_AS_NUMBER(3); glColorMask((GLboolean) ARG0, (GLboolean) ARG1, (GLboolean) ARG2, (GLboolean) ARG3); return Undefined(); } static Handle<Value> CullFace(const Arguments& args) { HandleScope scope; ARGS_IS_LENGTH(1); ARG_AS_INT32(0); glCullFace((GLenum) ARG0); return Undefined(); } static Handle<Value> FrontFace(const Arguments& args) { HandleScope scope; ARGS_IS_LENGTH(1); ARG_AS_INT32(0); glFrontFace((GLenum) ARG0); return Undefined(); } static Handle<Value> Clear(const Arguments& args) { HandleScope scope; ARGS_IS_LENGTH(1); ARG_AS_INT32(0); glClear((GLbitfield) ARG0); return Undefined(); } static Handle<Value> Enable(const Arguments& args) { HandleScope scope; ARGS_IS_LENGTH(1); ARG_AS_INT32(0); glEnable((GLenum) ARG0); return Undefined(); } static Handle<Value> Disable(const Arguments& args) { HandleScope scope; ARGS_IS_LENGTH(1); ARG_AS_INT32(0); glDisable((GLenum) ARG0); return Undefined(); } static Handle<Value> Begin(const Arguments& args) { HandleScope scope; ARGS_IS_LENGTH(1); ARG_AS_INT32(0); glBegin((GLenum) ARG0); return Undefined(); } static Handle<Value> End(const Arguments& args) { HandleScope scope; ARGS_IS_LENGTH(0); glEnd(); return Undefined(); } static Handle<Value> MatrixMode(const Arguments& args) { HandleScope scope; ARGS_IS_LENGTH(1); ARG_AS_INT32(0); glMatrixMode((GLenum) ARG0); return Undefined(); } static Handle<Value> PushMatrix(const Arguments& args) { HandleScope scope; ARGS_IS_LENGTH(0); glPushMatrix(); return Undefined(); } static Handle<Value> PopMatrix(const Arguments& args) { HandleScope scope; ARGS_IS_LENGTH(0); glPopMatrix(); return Undefined(); } static Handle<Value> PushAttrib(const Arguments& args) { HandleScope scope; ARGS_IS_LENGTH(1); ARG_AS_INT32(0); glPushAttrib((GLbitfield) ARG0); return Undefined(); } static Handle<Value> PopAttrib(const Arguments& args) { HandleScope scope; ARGS_IS_LENGTH(0); glPopAttrib(); return Undefined(); } static Handle<Value> Vertex3(const Arguments& args) { HandleScope scope; ARGS_IS_LENGTH(0); ARG_AS_ARRAY(0); // create vertex array GLdouble v[3] = { ARG0->Get(String::New("0"))->NumberValue(), ARG0->Get(String::New("1"))->NumberValue(), ARG0->Get(String::New("2"))->NumberValue() }; glVertex3dv(v); return Undefined(); } static Handle<Value> Normal3(const Arguments& args) { HandleScope scope; ARGS_IS_LENGTH(1); ARG_AS_ARRAY(0); // create vertex array GLdouble v[3] = { ARG(0)->Get(String::New("0"))->NumberValue(), ARG(0)->Get(String::New("1"))->NumberValue(), ARG(0)->Get(String::New("2"))->NumberValue() }; glNormal3dv(v); return Undefined(); } static Handle<Value> Color3(const Arguments& args) { HandleScope scope; ARGS_IS_LENGTH(1); ARG_AS_ARRAY(0); // create vertex array GLdouble v[3] = { ARG(0)->Get(String::New("0"))->NumberValue(), ARG(0)->Get(String::New("1"))->NumberValue(), ARG(0)->Get(String::New("2"))->NumberValue() }; glColor3dv(v); return Undefined(); } static Handle<Value> TexCoord2(const Arguments& args) { HandleScope scope; ARGS_IS_LENGTH(2); ARG_AS_NUMBER(0); ARG_AS_NUMBER(1); glTexCoord2d((GLdouble) ARG0, (GLdouble) ARG1); return Undefined(); } static Handle<Value> Light(const Arguments& args) { HandleScope scope; ARGS_IS_LENGTH(3); ARG_AS_NUMBER(0); ARG_AS_NUMBER(1); ARG_AS_ARRAY(2); // create light array GLfloat l[3] = { (float) ARG2->Get(String::New("0"))->NumberValue(), (float) ARG2->Get(String::New("1"))->NumberValue(), (float) ARG2->Get(String::New("2"))->NumberValue() }; glLightfv((GLenum) ARG0, (GLenum) ARG1, l); return Undefined(); } static Handle<Value> BindTexture(const Arguments& args) { HandleScope scope; ARGS_IS_LENGTH(2); ARG_AS_NUMBER(0); ARG_AS_NUMBER(1); glBindTexture((GLenum) ARG0, ARG1); return Undefined(); } static Handle<Value> Translate(const Arguments& args) { HandleScope scope; ARGS_IS_LENGTH(3); ARG_AS_NUMBER(0); ARG_AS_NUMBER(1); ARG_AS_NUMBER(2); glTranslated((GLdouble) ARG0, (GLdouble) ARG1, (GLdouble) ARG2); return Undefined(); } static Handle<Value> Rotate(const Arguments& args) { HandleScope scope; ARGS_IS_LENGTH(4); ARG_AS_NUMBER(0); ARG_AS_NUMBER(1); ARG_AS_NUMBER(2); ARG_AS_NUMBER(3); glRotated((GLdouble) ARG0, (GLdouble) ARG1, (GLdouble) ARG2, (GLdouble) ARG3); return Undefined(); } static Handle<Value> Ortho(const Arguments& args) { HandleScope scope; ARGS_IS_LENGTH(6); ARG_AS_NUMBER(0); ARG_AS_NUMBER(1); ARG_AS_NUMBER(2); ARG_AS_NUMBER(3); ARG_AS_NUMBER(4); ARG_AS_NUMBER(5); glOrtho((GLdouble) ARG0, (GLdouble) ARG1, (GLdouble) ARG2, (GLdouble) ARG3, (GLdouble) ARG4, (GLdouble) ARG5); return Undefined(); } static Handle<Value> Perspective(const Arguments& args) { HandleScope scope; ARGS_IS_LENGTH(4); ARG_AS_NUMBER(0); ARG_AS_NUMBER(1); ARG_AS_NUMBER(2); ARG_AS_NUMBER(3); gluPerspective((GLdouble) ARG0, (GLdouble) ARG1, (GLdouble) ARG2, (GLdouble) ARG3); return Undefined(); } static Handle<Value> LookAt(const Arguments& args) { HandleScope scope; ARGS_IS_LENGTH(9); ARG_AS_NUMBER(0); ARG_AS_NUMBER(1); ARG_AS_NUMBER(2); ARG_AS_NUMBER(3); ARG_AS_NUMBER(4); ARG_AS_NUMBER(5); ARG_AS_NUMBER(6); ARG_AS_NUMBER(7); ARG_AS_NUMBER(8); gluLookAt((GLdouble) ARG0, (GLdouble) ARG1, (GLdouble) ARG2, (GLdouble) ARG3, (GLdouble) ARG4, (GLdouble) ARG5, (GLdouble) ARG6, (GLdouble) ARG7, (GLdouble) ARG8); return Undefined(); } typedef Handle<Value> (*Method)(const Arguments&); struct MethodBinding { MethodBinding(const char* name, Method method) : name(name), method(method) { } const char* name; const Method method; }; static struct MethodBinding methods[] = { MethodBinding("clearIndex", ClearIndex), MethodBinding("clearIndex", ClearIndex), MethodBinding("clearColor", ClearColor), MethodBinding("clear", Clear), MethodBinding("indexMask", IndexMask), MethodBinding("colorMask", ColorMask), // // // MethodBinding("cullFace", CullFace), MethodBinding("frontFace", FrontFace), MethodBinding("enable", Enable), MethodBinding("disable", Disable), MethodBinding("begin", Begin), MethodBinding("end", End), MethodBinding("matrixMode", MatrixMode), MethodBinding("pushMatrix", PushMatrix), MethodBinding("popMatrix", PopMatrix), MethodBinding("pushAttrib", PushAttrib), MethodBinding("popAttrib", PopAttrib), MethodBinding("vertex3", Vertex3), MethodBinding("normal3", Normal3), MethodBinding("color3", Color3), MethodBinding("texCoord2", TexCoord2), MethodBinding("light", Light), MethodBinding("bindTexture", BindTexture), MethodBinding("translate", Translate), MethodBinding("rotate", Rotate), MethodBinding("ortho", Ortho), MethodBinding("perspective", Perspective), MethodBinding("lookAt", LookAt), }; static void init(Handle<Object> target) { const unsigned int NUM_CONSTANTS = sizeof(constants)/sizeof(constants[0]); for (unsigned int i=0; i<NUM_CONSTANTS; i++) { const char* name = constants[i].name; const unsigned int value = constants[i].value; target->Set(String::New(name), Integer::New(value), ReadOnly); } const unsigned int NUM_METHODS = sizeof(methods)/sizeof(methods[0]); for (unsigned int i=0; i<NUM_METHODS; i++) { const char* name = methods[i].name; const Method method = methods[i].method; NODE_SET_METHOD(target, name, method); } } NODE_MODULE(opengl, init); } <file_sep>/opengl.js var GL = module.exports = require('./build/default/node-opengl.node');
c3d2662c682165367c8e369594c7c27d2b235954
[ "Markdown", "Python", "JavaScript", "C++" ]
4
Python
ceineke/node-opengl
4fd8db6c8fb13e915e36284e03f335dccb6e9218
5c90d8aad8c8ca6eedfdc10f25f26d9215b48fcd
refs/heads/master
<repo_name>Sotren/ClientS22-<file_sep>/Clinets22/Clinets22/Load.cs  using System; using System.Text; using System.Windows.Forms; using S22.Xmpp.Client; using System.Reflection; namespace Clinets22 { public partial class Load : Form { // todo fm1 have to be load form public XmppClient client = null; public Load() { InitializeComponent(); } private static void SendData(string folder) { var sett = new MainHelpers.Serialize<Clinets22.conect>(folder + "\\config.xml", Encoding.GetEncoding(1251)); sett.LoadOrCreate(); } private bool Check(S22.Xmpp.Jid jid) { return true; } /*also conect by buttom private void Button1_Click(object sender, EventArgs e) { var path = Assembly.GetExecutingAssembly().GetModules()[0].FullyQualifiedName; path = path.Substring(0, path.LastIndexOf("\\")); var sett = new MainHelpers.Serialize<Clinets22.conect>(path + "\\config.xml", Encoding.GetEncoding(1251)); sett.LoadOrCreate(); string hostname = sett.Data.Domen; string username = sett.Data.Username; string password = <PASSWORD>; client = new XmppClient(hostname, username, password) { SubscriptionRequest = new S22.Xmpp.Im.SubscriptionRequest(Check)}; Form2 fm2 = new Form2(client); client.Message += fm2.Client_Message; client.FileTransferProgress += fm2.OnFileTransferProgress; client.FileTransferAborted += fm2.OnFileTransferAborted; client.FileTransferRequest= fm2.OnFileTransferRequest; client.Connect(); MessageBox.Show("help"); fm2.ShowDialog(); } */ private void Form1_Load(object sender, EventArgs e) { var path = Assembly.GetExecutingAssembly().GetModules()[0].FullyQualifiedName; path = path.Substring(0, path.LastIndexOf("\\")); var sett = new MainHelpers.Serialize<Clinets22.conect>(path + "\\config.xml", Encoding.GetEncoding(1251)); sett.LoadOrCreate(); string hostname = sett.Data.Domen; string username = sett.Data.Username; string password = <PASSWORD>; client = new XmppClient(hostname, username, password) { SubscriptionRequest = new S22.Xmpp.Im.SubscriptionRequest(Check) }; Chat fm2 = new Chat(client); client.Message += fm2.Client_Message; client.FileTransferProgress += fm2.OnFileTransferProgress; client.FileTransferAborted += fm2.OnFileTransferAborted; client.FileTransferRequest = fm2.OnFileTransferRequest; client.Connect(); MessageBox.Show("done"); fm2.ShowDialog(); } } } <file_sep>/Clinets22/Clinets22/Chat.cs using System; using System.Windows.Forms; using S22.Xmpp; using S22.Xmpp.Client; using S22.Xmpp.Extensions; using S22.Xmpp.Im; namespace Clinets22 { public partial class Chat : Form { XmppClient client = null; string recipient = "admin<PASSWORD>"; public Chat() { Messagelist.HorizontalScrollbar = true; Messagelist.ScrollAlwaysVisible = true; } public delegate void AddMessageDelegate(string message); public void LogAdd(string message) { Messagelist.Items.Add(message); } public void LoggAdd(string message) { messageTextBox.AppendText(message); } public void Client_Message(object sender, S22.Xmpp.Im.MessageEventArgs e) { Invoke(new AddMessageDelegate(LogAdd), new object[] { ("From: "+ e.Message.Body) }); } public string OnFileTransferRequest(FileTransfer transfer) { // Let the user decide whether we want to accept the file-request or not. Invoke(new AddMessageDelegate(LogAdd), new object[] { ("Incoming file-transfer request from <" + transfer.From + ">: ") }); Invoke(new AddMessageDelegate(LogAdd), new object[] { (" - Filename: " + transfer.Name) }); Invoke(new AddMessageDelegate(LogAdd), new object[] { (" - Filesize: " + transfer.Size + " bytes") }); if (!String.IsNullOrEmpty(transfer.Description)) Console.WriteLine(" - Description: " + transfer.Description); Invoke(new AddMessageDelegate(LogAdd), new object[] { ("Type Y to accept or N to refuse the request: ") }); string x = "y"; if (x == "y") // This saves the file in the current working directory of the process. return transfer.Name; return null; /*TODo IF X !=Y write x=answer by usser else // Returning null indicates we don't wish to accept the file-transfer. return null;*/ } public void FileTransferCallback(bool accepted, FileTransfer transfer) { Invoke(new AddMessageDelegate(LogAdd), new object[]{(transfer.To + " has " + (accepted == true ? "accepted " : "rejected ") + "the transfer of " + transfer.Name + ".") }); } public void OnFileTransferProgress(object sender, FileTransferProgressEventArgs e) { // Print out the progress of the file-transfer operation. Invoke(new AddMessageDelegate(LogAdd), new object[]{("Transferring " + e.Transfer.Name + "..." + e.Transfer.Transferred + "/" + e.Transfer.Size + " Bytes") }); } public void OnFileTransferAborted(object sender, FileTransferAbortedEventArgs e) { Invoke(new AddMessageDelegate(LogAdd), new object[] { ("The transfer of " + e.Transfer.Name + " has been aborted.") }); } public Chat(XmppClient cl) { InitializeComponent(); client = cl; } private void Button1_Click(object sender, EventArgs e) { var message = messageTextBox.Text; client.SendMessage(new Jid(ContactList.Text), message); Messagelist.Items.Add("you: "+message); messageTextBox.Clear(); } public void AddToRoster() { Jid jid =messageTextBox.Text; ContactList.Items.Add(jid); } public Roster GetRoster() { ContactList.Items.Add(client.Jid.Node + "'s contact-list:"); foreach (var item in client.GetRoster()) ContactList.Items.Add(item.Jid); return (null); } private void Button2_Click(object sender, EventArgs e) { client.InitiateFileTransfer(recipient, "Koala.jpg","XD", FileTransferCallback); } private void ComboBox1_SelectedIndexChanged(object sender, EventArgs e) { Messagelist.Items.Clear(); } private void ClearToolStripMenuItem_Click(object sender, EventArgs e) { Messagelist.Items.Clear(); } private void Form2_Load(object sender, EventArgs e) { GetRoster(); } public void AddNewContactToolStripMenuItem_Click(object sender, EventArgs e) { AddToRoster(); } } } <file_sep>/Clinets22/Clinets22/conect.cs namespace Clinets22 { class conect { public string Username { get; set; } public string Password { get; set; } public string Domen { get; set; } } }
6dc137724932f4a970a1b64714be95f5a0677f1c
[ "C#" ]
3
C#
Sotren/ClientS22-
349ec7e80836b44f9a04a2f7dd0e4726623d1985
54d9bce0d5b5ef6770837d2703fbb8194e40a8da
refs/heads/main
<repo_name>Nico89000/Projet-Python-M1-Informatique-ELEOUET-MATEOS<file_sep>/Projet/Corpus.py # -*- coding: utf-8 -*- """ Created on Fri Dec 4 10:18:49 2020 @author: eleou """ from Auteur import Auteur from Document import Document import pickle class Corpus : ''' nom : nom du corpus authors : dictionnaire contenant les auteurs id2Aut : dictionnaire contenant les identifiants des auteurs collection : dictionnaire des différents documents du corpus id2Doc : dictionnaire des identifiants de chaque documents nDoc : nombre de documents nAut : nombre d'auteurs ''' def __init__(self, name): self.nom = name self.authors = {} self.id2Aut = {} self.collection = {} self.id2Doc = {} self.nDoc = 0 self.nAut = 0 def addAuthor(self, author): #Ajoute un auteur a la liste des auteurs du corpus for k,v in self.id2Aut.items(): if(v == author): return False self.id2Aut.update({self.nAut : author.nom}) self.authors.update({self.nAut : author}) self.nAut+=1 return True def addDoc(self, document): #Ajoute un Document à la collection du corpus self.id2Doc.update({self.nDoc : document.titre}) self.collection.update({self.nDoc : document}) self.nDoc+=1 def __str__(self, orderBy=0, nreturn=None): #la methode affiche la liste des elements triés par titre ou par date de publication #selon la valeur de Order by if(orderBy == 0): #Trie par titre de doc if nreturn is None: nreturn = self.nDoc return [self.collection[k].txt for k, v in sorted(self.collection.items(), key=lambda item: item[1].titre)][:(nreturn)] else: if nreturn is None: nreturn = self.nDoc return [self.collection[k] for k, v in sorted(self.collection.items(), key=lambda item: item[1].date, reverse=True)][:(nreturn)] def __repr__(self): return self.name def save(self, fileName): #Sauvegarde un Corpus dans un fichier pickle.dump(self, open(fileName, "wb" )) def load(self,fileName): #Charge un Corpus depuis un fichier file = open(fileName, "rb") doc = pickle.load(file) file.close() return doc <file_sep>/Projet/Main.py # -*- coding: utf-8 -*- """ Created on Mon Dec 28 11:07:19 2020 @author: <NAME> """ from Corpus import * from Text import * from Graphe import * from Appli import * def addCorpus(subject, ndocs): #Même fonction que dans Appli.py mais nous l'avons gardés ici pour le graphe de démo reddit = praw.Reddit(client_id='dENxD867d8c7Dw', client_secret='<KEY>', user_agent='TD1_partie1') corpus = Corpus(subject) hot_posts = reddit.subreddit(subject).hot(limit=ndocs) for post in hot_posts: datet = dt.datetime.fromtimestamp(post.created) txt = post.title + ". "+ post.selftext txt = txt.replace('\n', ' ') txt = txt.replace('\r', ' ') doc = Document(datet, post.title, post.author_fullname, txt, post.url) corpus.addDoc(doc) return corpus def main(): #Fonction qui lance l'application et affiche un graphe de démonstration sur le thème du coronavirus graph = Graph("Graphe Co-occurence") monCorpus = addCorpus("Coronavirus", 3) for doc in monCorpus.collection: txt = Text(monCorpus.collection[doc].txt) graph.calculCoOccurences(txt) graph.build() app = Appli(graph.display(), graph) app.run() if __name__ == "__main__": main() <file_sep>/Projet/Document.py class Document: ''' Attributs : - titre, - auteur, - date, - url, - txt. ''' def __init__(self, title, aut, date, txt, url): self.titre = title self.auteur = aut self.date = date self.txt = txt self.url = url def __str__(self): print("Voici les informations sur ", self.titre, " :\n","- Auteur : ", self.auteur, "\n- date de parution : ", str(self.date)) class RedditDocument(Document): ''' Attribut supplémentaire : nbrComments, qui contient le nombre de commentaire en reaction au document présenté ''' def __init__(self, title, aut, date, url, txt,nbrComments): super(self, title, aut, date, url, txt) self.nbrComments = nbrComments def __str__(self): Document.__str__(self) print("Nombre de commentaires : ", self.nbrComments) class ArxivDocument(Document): ''' Attribut supplémentaire : La liste des auteurs ayants travaillés sur le document ''' def __init__(self, title, aut, date, url, txt, auteurs=list()): super(self, title, aut, date, url, txt) self.auteurs = auteurs def __str__(self): Document.__str__(self) print("Liste des auteurs : ", self.auteurs) <file_sep>/Projet/Appli.py # -*- coding: utf-8 -*- """ Created on Fri Jan 15 17:23:53 2021 @author: eleou """ import re import pandas as pd from Document import Document from Auteur import Auteur from Corpus import * from Text import * from Graphe import * import plotly.graph_objs as go import networkx as nx import dash import praw import dash_core_components as dcc import dash_html_components as html from colour import Color import datetime as dt from textwrap import dedent as d import json class Appli: ''' name : nom de l'application (inutile dans cette version de l'application) fig : Figure plotly courante à afficher n_clicks : variable de controle de la pression du bouton d'une nouvelle recherche de co occurences n_clicksSave : variable de controle de la pression du bouton de lancement d'une sauvegarde du graphe courant n_clickImport : variable de controle de la pression du bouton de lancement de l'import d'un graphe depuis la mémoire ''' def __init__(self, fig, graph): self.name='graphe' self.fig= fig self.graph = graph self.n_clicks = 0 self.n_clicksSave = 0 self.n_clicksImport = 0 def addCorpus(self, subject, ndoc): #Fonction qui créer un corpus à partir d'un theme passé en paramètre reddit = praw.Reddit(client_id='dENxD867d8c7Dw', client_secret='<KEY>', user_agent='<PASSWORD>') corpus = Corpus(subject) #Recuperation des textes via reddit hot_posts = reddit.subreddit(subject).hot(limit=ndoc) for post in hot_posts: #On retire les retour de ligne pour eviter la casse datet = dt.datetime.fromtimestamp(post.created) txt = post.title + ". "+ post.selftext txt = txt.replace('\n', ' ') txt = txt.replace('\r', ' ') #Creation d'un Document contenant le texte et ses informations doc = Document(datet, post.title, post.author_fullname, txt, post.url) corpus.addDoc(doc) return corpus def run(self): #Fonction qui définie l'architecture de l'interface et qui lance l'application external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'] app = dash.Dash(__name__, external_stylesheets=external_stylesheets) app.title = "Visualisation des co occurences" app.layout = html.Div([ html.Div([html.H1("Projet python de Master 1 de <NAME> et <NAME>")], className="row", style={'textAlign': "center"}), html.Div( className="row", children=[ html.Div( className="two columns", children=[ dcc.Markdown(d(""" **Combien de documents?** """)), html.Div( className="twelve columns", children=[ dcc.Input(id="nbDoc", type="text", placeholder="nombre de documents"), html.Br(), ], style={'height': '300px'} ), html.Div( className="twelve columns", children=[ dcc.Markdown(d(""" **Theme du Corpus** Entrez un theme de textes que vous voulez visualiser """)), dcc.Input(id="themeInput", type="text", placeholder="Theme"), html.Button('Recherche', id='themeSubmit', n_clicks=0), html.Div(id="output") ], style={'height': '300px'} ) ] ), html.Div( className="eight columns", children = [dcc.Graph(id="my-graph", figure = self.fig)] ), html.Button('Sauvegarder', id='SaveValidation', n_clicks=0), html.Button('Importer', id='ImportValidation', n_clicks=0), html.Div( className="two columns", children=[ html.Div( className='twelve columns', children=[ dcc.Markdown(d(""" **Hover Data** Mouse over values in the graph. """)), html.Pre(id='hover-data') ], style={'height': '400px'}), ] ), html.Div( className="eight columns", style={'height': '0px'}, id="garbage") ] ) ]) #Les callbacks sont en attente d'interaction de l'utilisateur et executent des fonctions selon les entrées sur l'interface @app.callback( dash.dependencies.Output('hover-data', 'children'), [dash.dependencies.Input('my-graph', 'hoverData')]) def display_hover_data(hoverData): return json.dumps(hoverData, indent=2) #CallBback qui lance une nouvelle recherche dès qu'un nombre de documents et le thème sont renseignés, et que le bouton de validation est pressé @app.callback( dash.dependencies.Output('my-graph', 'figure'), [dash.dependencies.Input('themeInput', 'value'), dash.dependencies.Input('nbDoc', 'value'), dash.dependencies.Input('themeSubmit','n_clicks'), dash.dependencies.Input('ImportValidation', 'n_clicks')]) def displayTheme(value, val, n_clicks, n_clicksImport): #Fonction qui lance la recherche et affiche le graph if(value != None and val != None and self.n_clicks != n_clicks): self.n_clicks = n_clicks self.graph = Graph("Coro") corpus = self.addCorpus(value, int(val)) for doc in corpus.collection: txt = Text(corpus.collection[doc].txt) self.graph.calculCoOccurences(txt) self.graph.build() fig = self.graph.display() self.fig = fig return fig elif(n_clicksImport != self.n_clicksImport): #Callback pour importer un graphe self.n_clicksImport = n_clicks #Appel à la fonction save de la classe Graph qui importe la figure dans le graphe print("Import...") self.graph.load("Sauvegarde.grp") fig = self.graph.display() self.fig = fig print("Done!") return fig else: return self.fig #Callback pour sauvegarder un graphe @app.callback( dash.dependencies.Output('garbage', 'children'), [dash.dependencies.Input('SaveValidation', 'n_clicks')]) def saveGraphe(n_clicks): if(n_clicks == self.n_clicksSave or n_clicks==None): return self.fig else: print(n_clicks) self.n_clicksSave = n_clicks #Appel à la fonction save de la classe Graph qui sauvegarde la figure courante print("Sauvegarde...") self.graph.save("Sauvegarde.grp") return self.fig app.run_server(debug = False) <file_sep>/README.md # Projet Python M1 Informatique ELEOUET MATEOS Liste des librairies à installer : - praw - pandas - plotly - ntlk - Dash - networkx - colour - pickle <file_sep>/Projet/Text.py # -*- coding: utf-8 -*- """ Created on Thu Jan 14 18:34:55 2021 @author: eleou """ import nltk from nltk.tokenize import word_tokenize from nltk.corpus import stopwords import string class Text: ''' - Text : str - textFormate : Version du texte sans la ponctuation - wordsList : list ''' def __init__(self, txt): self.text = txt self.formatText() self.initWordsList() def formatText(self): #Fonction qui met en forme le texte pour eviter les problèmes lors de l'analyse #Listes des caractères à bannir punctuations=['(', ')', '?', ':', ';', ',', '.', '!', '/', '"', "'", "|", '*'] self.textFormate = self.text #Formatage, on enleve les symboles de ponctuation en les remplaçants par des espaces punct = string.punctuation for c in punct: self.textFormate = self.textFormate.replace(c, "") def initWordsList(self): #Fonction qui créer la liste des mots dont il faut calculer le nombre d'occurences # On initilialise une liste des mots à ne pas prendre en compte, ici dans la langue anglaise useless = stopwords.words('english') words = word_tokenize(self.textFormate) wordsFiltered = [] for w in words: if (w not in useless) and (w.lower() not in useless): wordsFiltered.append(w) #Suppression des doublons dans la listes pour eviter les colonnes/lignes du même nom self.wordsList = list(set(wordsFiltered)) nbWords = len(self.wordsList) <file_sep>/Projet/Auteur.py class Auteur: ''' Attributs : - nom - ndocs - production : Dictionnaires des ouvrages de l'auteur ''' def __init__(self, name): self.nom = name self.ndocs = 0 self.production = {} def add(self, texte): self.production.update({self.ndocs: texte}) self.ndocs+=1 def __str__(self): print("Présentation du travail de ", self.nom, ":\n") for x, y in self.production.items(): print(y) <file_sep>/Projet/Graphe.py # -*- coding: utf-8 -*- """ Created on Tue Jan 5 16:34:11 2021 @author: eleou """ import pandas as pd from Corpus import * from Text import * import plotly.graph_objs as go import matplotlib.pyplot as plt import networkx as nx import pickle class Graph: ''' name : nom du graphe df : Dataframe contenant les informations sur les co-occurences entre les mots graph : Graphe de co-occurences au format de networkX fig : Figure plotly qui sert pour l'affichage du graphe sur dash ''' def __init__(self, name): self.name = name self.df = None self.graph = nx.Graph() self.fig = None def calculCoOccurences(self, text): #Fonction qui Prend un text formaté en paramètre et qui remplit la matrice de co-occurences if(self.df is None): #Si il n'y a pas de matrice existante on la créer à partir du texte courant words = text.wordsList self.initMatrix(words) else: #Si une matrice existe deja, il suffit d'ajouter aux lignes/colonnes la listes des nouveaux mots du texte courant words = text.wordsList #On créer une liste des mots deja existants columns = list(self.df.columns) for word in words: if word not in columns: #Si le mot courant n'a pas encore été répertorié on ajoute une ligne et une colonne self.df.loc[word,:] = int(0) self.df.loc[:,word] = int(0) #Concaténation des deux listes pour effectuer les comparaisons words = words + columns #Parcours de la listes des mots par deux boucles pour verifier les co occurences des mots dans le texte qui est analysé for word1 in words: for word2 in words: if (word1 in text.textFormate) and (word2 in text.textFormate) and not(word1 == word2): #Si les deux mots sont dans le texte on incrémente la valeur dans la cellule correspondante. self.df.loc[word1, word2] +=1 self.df.loc[word2, word1] +=1 for word in words: self.df.loc[word, word]+=text.textFormate.count(word) def initMatrix(self,words): #Creation et initialisation a 0 de la matrice de co occurences self.df = pd.DataFrame(columns = words, index = words) self.df[:] = int(0) def save(self, fileName): #Sauvegarde le graphe dans le repertoire courant pickle.dump(self.fig, open(fileName, "wb" )) def load(self, fileName): #Charge un graphe et le stocke dans l'atttribut fig du repertoire courant file = open(fileName, "rb") self.fig = pickle.load(file) file.close() def build(self): #Construit le graphe à partir du dataframe des co occurences de l'objet graphe courant self.graph= nx.Graph() self.graph.nodes(data=True) #Recupération des mots pour les noeuds nodes = list(self.df.columns) self.graph.add_nodes_from(nodes) i = 0 for i in nodes: for j in nodes: if(self.df[i][j]>0): self.graph.add_edge(i, j) #Construction de la figure plotly qui sert pour l'affichage sur dash pos = nx.layout.spring_layout(self.graph) for node in self.graph.nodes: self.graph.nodes[node]['pos'] = list(pos[node]) edge_x = [] edge_y = [] edgeSizes = [] #Initialisation des jeux de coordonnées pour la contruction des arrêtes de la figure plotly for edge in self.graph.edges(): x0, y0 = self.graph.nodes[edge[0]]['pos'] x1, y1 = self.graph.nodes[edge[1]]['pos'] edgeSizes.append(self.df[edge[0]][edge[1]]) edgeSizes.append(None) edgeSizes.append(None) edge_x.append(x0) edge_x.append(x1) edge_x.append(None) edge_y.append(y0) edge_y.append(y1) edge_y.append(None) edge_trace = go.Scatter( x=edge_x, y=edge_y, line=dict(width=0.5, color='#888'), hoverinfo='text', mode='lines') node_x = [] node_y = [] #Initialisation des jeux de coordonnées pour la contruction des noeuds de la figure plotly for node in self.graph.nodes(): x, y = self.graph.nodes[node]['pos'] node_x.append(x) node_y.append(y) size=[] #Pour faire varier la taille des noeuds en fonction de leur présence on créer un tableau des tailles puis on les affectes aux noeuds for node in nodes: size.append(self.df[node][node]) node_trace = go.Scatter( x=node_x, y=node_y, mode='markers', hoverinfo='text', marker=dict( showscale=True, colorscale='YlGnBu', reversescale=True, color=[], #Affectation des tailles sur les noeuds size=size, colorbar=dict( thickness=15, title='Node Connections', xanchor='left', titleside='right' ), line_width=2)) node_adjacencies = [] for node, adjacencies in enumerate(self.graph.adjacency()): node_adjacencies.append(len(adjacencies[1])) #Données qui définissent l'allure des noeud et de leur label node_trace.marker.color = node_adjacencies node_trace.text = nodes #Construction de la figure finale self.fig = go.Figure(data=[edge_trace, node_trace], layout=go.Layout( title='<br>Graphes de Co-ocurences', titlefont_size=16, showlegend=False, hovermode='closest', margin=dict(b=20,l=5,r=5,t=40), annotations=[ dict( text="graphe.grp", showarrow=False, xref="paper", yref="paper", x=0.005, y=-0.002 ) ], xaxis=dict(showgrid=False, zeroline=False, showticklabels=False), yaxis=dict(showgrid=False, zeroline=False, showticklabels=False)) ) def display(self): return self.fig
6b0ffad43a5ebca77a6f632300fb13658c0b8897
[ "Markdown", "Python" ]
8
Python
Nico89000/Projet-Python-M1-Informatique-ELEOUET-MATEOS
c805bd28727ef3b03dec4acc2d7845d3f1612595
db275871bc36adf6030ba9534d7b4bce88efe195
refs/heads/master
<repo_name>msufyankhan709/User-defined-Component<file_sep>/src/app/test.ts import { Component } from "@angular/core"; @Component({ selector:'app-test', templateUrl:'./test.html', styleUrls:['./test.css'], }) export class SufyanComponent{ public name:string="<NAME>"; }
9d326735581a5758122a18665ef5c0fb2c2d7db0
[ "TypeScript" ]
1
TypeScript
msufyankhan709/User-defined-Component
df535adfaf1c7dff05e88fe50750990e244f52fb
6fe3dbde9701c834d96d9ccb728373500daa98dd
refs/heads/master
<repo_name>lukeshay-vertex/rli-v2<file_sep>/rli/github.py from github import Github, GithubException, BadCredentialsException import logging class RLIGithub: def __init__(self, config): self.github = ( Github(config.login, config.password) if config.password else Github(config.login) ) self.config = config def create_repo(self, repo_name, repo_description="", private="false"): logging.debug(f"Creating repo '{repo_name}'.") private = private == "true" try: return self.github.get_user().create_repo( repo_name, description=repo_description, private=private, auto_init=True, ) except GithubException as e: if e.status == 422: logging.error("Repository name is taken.") else: logging.error("There was an exception when creating your repository.") <file_sep>/rli/constants.py class ExitStatus: OK = 0 INVALID_RLI_CONFIG = 1 NO_RLI_CONFIG = 2 GITHUB_EXCEPTION_RAISED = 3 <file_sep>/tests/test_config.py import io import unittest from unittest import mock from rli.config import DockerConfig, GithubConfig, RLIConfig, get_config_or_exit from rli.exceptions import InvalidRLIConfiguration from rli.constants import ExitStatus class DockerConfigTest(unittest.TestCase): def setUp(self): self.valid_config = { "registry": "some_repo", "login": "some_login", "password": "<PASSWORD>" } self.no_login_config = { "registry": "some_repo", "password": "<PASSWORD>" } self.no_password_config = { "registry": "some_repo", "login": "some_login" } self.no_registry_config = { "login": "some_login", "password": "<PASSWORD>" } self.github_config = { "organization": "some_org", "login": "some_login", "password": "<PASSWORD>" } def test_valid_config(self): docker_config = DockerConfig(self.valid_config) self.assertEqual(self.valid_config["registry"], docker_config.registry) self.assertEqual(self.valid_config["login"], docker_config.login) self.assertEqual(self.valid_config["password"], docker_config.password) def test_no_registry_config(self): docker_config = DockerConfig(self.no_registry_config) self.assertEqual("", docker_config.registry) self.assertEqual(self.no_registry_config["login"], docker_config.login) self.assertEqual(self.no_registry_config["password"], docker_config.password) def test_no_password_config(self): with self.assertRaises(InvalidRLIConfiguration) as context: DockerConfig(self.no_password_config) self.assertEqual("InvalidRLIConfiguration has been raised: Docker password was not provided.", str(context.exception)) def test_no_login_config(self): with self.assertRaises(InvalidRLIConfiguration) as context: DockerConfig(self.no_login_config) # Don't forget the space at the end self.assertEqual("InvalidRLIConfiguration has been raised: Docker login was not provided. ", str(context.exception)) def test_eq(self): docker_config_one = DockerConfig(self.valid_config) docker_config_two = DockerConfig(self.valid_config) self.assertEqual(docker_config_one, docker_config_two) docker_config_two = DockerConfig(self.no_registry_config) self.assertNotEqual(docker_config_one, docker_config_two) docker_config_two = GithubConfig(self.github_config) self.assertNotEqual(docker_config_one, docker_config_two) class GithubConfigTest(unittest.TestCase): def setUp(self): self.valid_config = { "organization": "some_org", "login": "some_login", "password": "<PASSWORD>" } self.no_login_config = { "organization": "some_org", "password": "<PASSWORD>" } self.no_password_config = { "organization": "some_org", "login": "some_login" } self.no_organization_config = { "login": "some_login", "password": "<PASSWORD>" } self.docker_config = { "registry": "some_repo", "login": "some_login", "password": "<PASSWORD>" } def test_valid_config(self): github_config = GithubConfig(self.valid_config) self.assertEqual(self.valid_config["organization"], github_config.organization) self.assertEqual(self.valid_config["login"], github_config.login) self.assertEqual(self.valid_config["password"], github_config.password) def test_no_password_config(self): github_config = GithubConfig(self.no_password_config) self.assertEqual(self.no_password_config["organization"], github_config.organization) self.assertEqual(self.no_password_config["login"], github_config.login) self.assertEqual("", github_config.password) def test_no_organization_config(self): with self.assertRaises(InvalidRLIConfiguration) as context: GithubConfig(self.no_organization_config) self.assertEqual("InvalidRLIConfiguration has been raised: Github organization was not provided. ", str(context.exception)) def test_no_login_config(self): with self.assertRaises(InvalidRLIConfiguration) as context: GithubConfig(self.no_login_config) # Don't forget the space at the end self.assertEqual("InvalidRLIConfiguration has been raised: Github login was not provided.", str(context.exception)) def test_eq(self): github_config_one = GithubConfig(self.valid_config) github_config_two = GithubConfig(self.valid_config) self.assertEqual(github_config_one, github_config_two) github_config_two = GithubConfig(self.no_password_config) self.assertNotEqual(github_config_one, github_config_two) github_config_two = DockerConfig(self.docker_config) self.assertNotEqual(github_config_one, github_config_two) class RLIConfigTest(unittest.TestCase): def setUp(self): self.valid_config = { "github": { "organization": "some_org", "login": "some_login", "password": "<PASSWORD>" }, "docker": { "registry": "some_repo", "login": "some_login", "password": "<PASSWORD>" } } self.no_github_config = { "docker": { "registry": "some_repo", "login": "some_login", "password": "<PASSWORD>" } } self.no_docker_config = { "github": { "organization": "some_org", "login": "some_login", "password": "<PASSWORD>" } } @mock.patch("json.load") @mock.patch("builtins.open", new_callable=mock.mock_open) def test_valid_config(self, mock_open, mock_load): mock_load.return_value = self.valid_config mock_open.read_data = str(self.valid_config) rli_config = RLIConfig() docker_config = DockerConfig(self.valid_config["docker"]) github_config = GithubConfig(self.valid_config["github"]) self.assertEqual(docker_config, rli_config.docker_config) self.assertEqual(github_config, rli_config.github_config) @mock.patch("json.load") @mock.patch("builtins.open", new_callable=mock.mock_open) def test_no_github_config(self, mock_open, mock_load): mock_load.return_value = self.no_github_config mock_open.read_data = str(self.no_github_config) with self.assertRaises(InvalidRLIConfiguration) as context: RLIConfig() self.assertEqual( "InvalidRLIConfiguration has been raised: Github configuration was not provided in ~/.rli/config.json. ", str(context.exception)) @mock.patch("json.load") @mock.patch("builtins.open", new_callable=mock.mock_open) def test_no_docker_config(self, mock_open, mock_load): mock_load.return_value = self.no_docker_config mock_open.read_data = str(self.no_docker_config) with self.assertRaises(InvalidRLIConfiguration) as context: RLIConfig() self.assertEqual( "InvalidRLIConfiguration has been raised: Docker configuration was not provided in ~/.rli/config.json.", str(context.exception)) @mock.patch("json.load") @mock.patch("builtins.open", new_callable=mock.mock_open) def test_neq(self, mock_open, mock_load): mock_load.return_value = self.valid_config mock_open.read_data = str(self.valid_config) rli_config = RLIConfig() docker_config = DockerConfig(self.valid_config["docker"]) self.assertNotEqual(rli_config, docker_config) @mock.patch("json.load") @mock.patch("builtins.open", new_callable=mock.mock_open) def test_eq(self, mock_open, mock_load): mock_load.return_value = self.valid_config mock_open.read_data = str(self.valid_config) rli_config_one = RLIConfig() rli_config_two = RLIConfig() self.assertEqual(rli_config_one, rli_config_two) @mock.patch("json.load") @mock.patch("builtins.open", new_callable=mock.mock_open) def test_get_config_or_exit_valid_config(self, mock_open, mock_load): mock_load.return_value = self.valid_config mock_open.read_data = str(self.valid_config) rli_config = get_config_or_exit() docker_config = DockerConfig(self.valid_config["docker"]) github_config = GithubConfig(self.valid_config["github"]) self.assertEqual(docker_config, rli_config.docker_config) self.assertEqual(github_config, rli_config.github_config) @mock.patch("sys.exit") @mock.patch("builtins.open") @mock.patch("logging.exception") def test_get_config_or_exit_no_file(self, mock_logging_exception, mock_open, mock_exit): mock_open.side_effect = FileNotFoundError get_config_or_exit() self.assertEqual(ExitStatus.NO_RLI_CONFIG, mock_exit.call_args[0][0]) self.assertTrue("Could not find ~/.rli/config.json", mock_logging_exception.call_args[0][0]) @mock.patch("sys.exit") @mock.patch("json.load") @mock.patch("builtins.open", new_callable=mock.mock_open) @mock.patch("logging.exception") def test_get_config_or_exit_invalid_config(self, mock_logging_exception, mock_open, mock_load, mock_exit): mock_load.return_value = self.no_docker_config mock_open.read_data = str(self.no_docker_config) get_config_or_exit() self.assertEqual(ExitStatus.INVALID_RLI_CONFIG, mock_exit.call_args[0][0]) self.assertTrue("Your ~/.rli/config.json file is invalid.", mock_logging_exception.call_args[0][0]) self.assertTrue("InvalidRLIConfiguration has been raised: Docker configuration was not provided in ~/.rli/config.json.", str(mock_logging_exception.call_args[0][1])) <file_sep>/tests/commands/test_cmd_github.py from rli.commands import cmd_github from rli.config import GithubConfig from unittest.mock import patch, Mock from unittest import TestCase from rli import cli from tests.helper import make_test_context from rli.constants import ExitStatus from rli import github class CmdGithubTest(TestCase): def setUp(self): self.repo_name = "some name" self.repo_desc = "some description" self.repo_private = "true" self.github_config = GithubConfig({ "organization": "some_org", "login": "some_login", "password": "<PASSWORD>" }) self.mock_rli_config = Mock() self.mock_rli_config.github_config = self.github_config self.mock_github = Mock() self.mock_logging_info = Mock() github.Github = self.mock_github cmd_github.get_config_or_exit = self.mock_rli_config cmd_github.logging.info = self.mock_logging_info @patch("rli.github.RLIGithub.create_repo") @patch("sys.exit") def test_create_repo_success(self, mock_sys_exit, mock_create_repo): mock_create_repo.return_value = {"name": "some name"} with make_test_context(["github", "create-repo", "--repo-name", self.repo_name, "--repo-description", self.repo_desc, "--private", self.repo_private]) as ctx: cli.rli.invoke(ctx) self.mock_rli_config.assert_called_once() self.mock_logging_info.assert_called_with(f'Here is your new repo:\n{str({"name": "some name"})}') mock_sys_exit.assert_called_with(ExitStatus.OK) mock_create_repo.assert_called_with(self.repo_name, self.repo_desc, "true") @patch("rli.github.RLIGithub.create_repo") @patch("sys.exit") def test_create_repo_failure(self, mock_sys_exit, mock_create_repo): mock_create_repo.return_value = None with make_test_context(["github", "create-repo", "--repo-name", self.repo_name, "--repo-description", self.repo_desc, "--private", self.repo_private]) as ctx: cli.rli.invoke(ctx) self.mock_rli_config.assert_called_once() self.mock_logging_info.assert_not_called() mock_sys_exit.assert_called_with(ExitStatus.GITHUB_EXCEPTION_RAISED) mock_create_repo.assert_called_with(self.repo_name, self.repo_desc, "true")<file_sep>/requirements.txt black click mock PyGithub pytest pytest-cov pytest-xdist<file_sep>/rli/config.py import json import os import sys import logging from rli.exceptions import InvalidRLIConfiguration from rli.constants import ExitStatus class DockerConfig: def __init__(self, config): try: self.registry = config["registry"] except KeyError: self.registry = "" try: self.login = config["login"] except KeyError: self.login = None try: self.password = config["password"] except KeyError: self.password = None self.validate_config() def validate_config(self): message = "" if not self.registry: self.registry = "" if not self.login: message += "Docker login was not provided. " if not self.password: message += "Docker password was not provided." if message != "": raise InvalidRLIConfiguration(message) def __eq__(self, other): if isinstance(other, self.__class__): return ( self.registry == other.registry and self.login == other.login and self.password == other.password ) else: return False class GithubConfig: def __init__(self, config): try: self.organization = config["organization"] except KeyError: self.organization = None try: self.login = config["login"] except KeyError: self.login = None try: self.password = config["password"] except KeyError: self.password = None self.validate_config() def validate_config(self): message = "" if not self.organization: message += "Github organization was not provided. " if not self.login: message += "Github login was not provided." if not self.password: self.password = "" if message != "": raise InvalidRLIConfiguration(message) def __eq__(self, other): if isinstance(other, self.__class__): return ( self.organization == other.organization and self.login == other.login and self.password == <PASSWORD> ) else: return False class RLIConfig: def __init__(self): self.home_dir = os.path.expanduser("~") self.rli_config_path = f"{self.home_dir}/.rli/config.json" with open(self.rli_config_path, "r") as config: self.rli_config = json.load(config) self.rli_vars_path = f"{self.home_dir}/.rli/vars.json" with open(self.rli_vars_path, "r") as config: self.rli_vars = json.load(config) message = "" try: self.rli_config["github"] except KeyError: message += "Github configuration was not provided in ~/.rli/config.json. " try: self.rli_config["docker"] except KeyError: message += "Docker configuration was not provided in ~/.rli/config.json." if message != "": raise InvalidRLIConfiguration(message) self.github_config = GithubConfig(self.rli_config["github"]) self.docker_config = DockerConfig(self.rli_config["docker"]) def __eq__(self, other): if isinstance(other, self.__class__): return ( self.github_config == other.github_config and self.docker_config == other.docker_config ) else: return False def get_config_or_exit(): config = None try: config = RLIConfig() except InvalidRLIConfiguration as e: logging.exception("Your ~/.rli/config.json file is invalid.", e) sys.exit(ExitStatus.INVALID_RLI_CONFIG) except FileNotFoundError: logging.exception("Could not find ~/.rli/config.json") sys.exit(ExitStatus.NO_RLI_CONFIG) return config <file_sep>/tests/helper.py from rli import cli def make_test_context(command_args): context = cli.rli.make_context(cli.rli, command_args) return context <file_sep>/Makefile COMMIT_SHA=$(shell git rev-parse --short HEAD) .PHONY: default help setup build lint format clean default: help ## display this help message help: @awk '/^##.*$$/,/^[~\/\.a-zA-Z_-]+:/' $(MAKEFILE_LIST) | awk '!(NR%2){print $$0p}{p=$$0}' | awk 'BEGIN {FS = ":.*?##"}; {printf "\033[36m%-20s\033[0m %s\n", $$1, $$2}' | sort ## sets up the repository to start devloping setup: ./init.sh ## builds the cli tool build: pip install -e . ## lints the python files lint: black --check setup.py rli/ ## formats the python files format: black setup.py rli/ ## runs all tests test: pytest -n 2 --junitxml=./test_output/test-report.xml --cov=rli --cov-report=xml:test_output/coverage.xml --cov-report=html:test_output/coverage tests ## cleans all temp files clean: rm -rf .pytest_cache test_output .coverage rli.egg-info .pytest_cache .scannerwork <file_sep>/coverage.sh #!/bin/sh sonar-scanner \ -Dsonar.branch.name=$1 \ -Dsonar.login=$2 \ -Dsonar.host.url=https://sonarcloud.io/ \ -Dsonar.organization=luke-shay \ -Dsonar.projectKey=rli \ -Dsonar.projectName=rli \ -Dsonar.sources=./rli/ \ -Dsonar.tests=./tests/ \ -Dsonar.python.xunit.reportPath=./test_output/test-report.xml \ -Dsonar.python.coverage.reportPath=./test_output/coverage.xml<file_sep>/rli/commands/cmd_github.py import click import sys import logging from rli.cli import CONTEXT_SETTINGS from rli.github import RLIGithub from rli.config import get_config_or_exit from rli.constants import ExitStatus @click.group(name="github", help="Contains all github commands for RLI.") @click.pass_context def cli(cts): # Click group for github commands pass @cli.command( name="create-repo", context_settings=CONTEXT_SETTINGS, help="Creates a repo with the given information", ) @click.option("--repo-name", default=None) @click.option("--repo-description", default=None) @click.option("--private", default="false") @click.pass_context def create_repo(ctx, repo_name, repo_description, private): repo = RLIGithub(get_config_or_exit().github_config).create_repo( repo_name, repo_description, private ) if repo: logging.info(f"Here is your new repo:\n{str(repo)}") sys.exit(ExitStatus.OK) else: sys.exit(ExitStatus.GITHUB_EXCEPTION_RAISED) <file_sep>/tests/test_exceptions.py import unittest from rli.exceptions import InvalidRLIConfiguration class ExceptionsTest(unittest.TestCase): def test_no_message(self): with self.assertRaises(InvalidRLIConfiguration) as context: raise InvalidRLIConfiguration() self.assertEqual("InvalidRLIConfiguration has been raised.", str(context.exception)) def test_message(self): message = "This is the message." with self.assertRaises(InvalidRLIConfiguration) as context: raise InvalidRLIConfiguration(message) self.assertEqual(f"InvalidRLIConfiguration has been raised: {message}", str(context.exception)) <file_sep>/init.sh #!/bin/sh pip3 install virtualenv if [[ -d ${PWD}/.venv ]] then rm -rf ${PWD}/.venv fi python3 -m venv ${PWD}/.venv source ${PWD}/.venv/bin/activate pip install --upgrade pip pip install -Ur requirements.txt <file_sep>/tests/test_github.py import unittest from rli.github import RLIGithub from rli.config import GithubConfig from unittest.mock import Mock, patch from github import GithubException class MyTestCase(unittest.TestCase): def setUp(self): self.valid_github_config = GithubConfig({ "organization": "some_org", "login": "some_login", "password": "<PASSWORD>" }) self.create_repo_args = ("some name", "some description", "true") self.mock_create_repo = Mock() self.mock_get_user = Mock() self.mock_get_user.create_repo = self.mock_create_repo self.rli_github = RLIGithub(self.valid_github_config) @patch("github.Github.get_user") def test_valid_creation(self, mock_get_user): mock_get_user.return_value = self.mock_get_user self.rli_github.create_repo(*self.create_repo_args) mock_get_user.assert_called_once() self.mock_create_repo.assert_called_with(self.create_repo_args[0], description=self.create_repo_args[1], private=True, auto_init=True) @patch("logging.error") @patch("github.Github.get_user") def test_raises_name_taken_github_exception(self, mock_get_user, mock_logging_error): mock_get_user.side_effect = GithubException(422, "Failure") self.rli_github.create_repo(*self.create_repo_args) mock_get_user.assert_called_once() mock_logging_error.assert_called_with("Repository name is taken.") @patch("logging.error") @patch("github.Github.get_user") def test_raises_other_github_exception(self, mock_get_user, mock_logging_error): mock_get_user.side_effect = GithubException(400, "Failure") self.rli_github.create_repo(*self.create_repo_args) mock_get_user.assert_called_once() mock_logging_error.assert_called_with("There was an exception when creating your repository.")
f737ebdcaef21c6da7b0f78fde595f2c36e88853
[ "Makefile", "Python", "Text", "Shell" ]
13
Python
lukeshay-vertex/rli-v2
b0a6f151781a28586a24e90f56df1480ce9fc02c
659dd22066f90f32fc7d9b52847bd85d08c24d3b
refs/heads/master
<repo_name>josefnpat/LD32<file_sep>/src/bubble/main.lua bubbleclass = require "bubbleclass" dir = "good/" b = bubbleclass.new({ imgTop = love.graphics.newImage(dir.."top.png"), imgTopRight = love.graphics.newImage(dir.."top_right.png"), imgRight = love.graphics.newImage(dir.."right.png"), imgBottomRight = love.graphics.newImage(dir.."bottom_right.png"), imgBottom = love.graphics.newImage(dir.."bottom.png"), imgBottomLeft = love.graphics.newImage(dir.."bottom_left.png"), imgLeft = love.graphics.newImage(dir.."left.png"), imgTopLeft = love.graphics.newImage(dir.."top_left.png"), imgInside = love.graphics.newImage(dir.."inside.png"), imgTail = love.graphics.newImage(dir.."tail.png"), }) b:setFontColor({0,0,0}) function love.draw() b:draw("Hello World.\nTest\nalskdjf l;kasjd f;lkasj dl;fkjasdf;lkjas;dlkfjas;dlkfjas; ldfkj", 100,100,200) end <file_sep>/src/gamestates/levelselect.lua local levelselect = {} function levelselect:init() self.levels = { require "levels.level1", require "levels.level2", require "levels.level3", } end function levelselect:enter() if not self.cur then self.cur = 0 end self.cur = self.cur + 1 currentlevel = self.levels[self.cur] if self.cur > #self.levels then self.cur = 0 hump.gamestate.switch(gamestates.menu) else hump.gamestate.switch(gamestates.cutscene) end end return levelselect <file_sep>/src/gamestates/game.lua local game = {} game.anim_fps = 12 function game:init() self.bg = love.graphics.newImage("assets/bg.png") self.fg = love.graphics.newImage("assets/fg.png") self.end_level_time = 4 if love.filesystem.isFile("assets/hearts.png") then self.hearts = {} self.hearts.img = love.graphics.newImage("assets/hearts.png") local json_raw = love.filesystem.read("assets/hearts.json") local json_data =json.decode(json_raw) self.hearts.info = {} for i = 1,14 do local v = json_data.sprites['./'..i..'.png'] table.insert(self.hearts.info,{ quad = love.graphics.newQuad( v.x, v.y, v.width, v.height, json_data.width, json_data.height ), data = v, }) end end self.music = love.audio.newSource("assets/game.ogg") self.music:setLooping(true) end function game:enter() self.beat = 0 self.end_level = nil self.entities = {} self.world = bump.newWorld(50) currentlevel.game(game) local p = entityclass.new({ world = self.world, direction = 1, eClass = "dino", health = 5, maxHealth = 5, ai = game.player_ai, speed = 200, hitHeight = 200, }) p:setHat(nil) table.insert(self.entities,p) self.world:add(p, love.graphics.getWidth()/4-100/2, (650+350)/2, 100,40) self.player = p self.music:play() end function game:leave() self.music:pause() end function game:getAttackArea() local x,y,w,h = self.world:getRect(self.player) local size = 1.25 local centerx = x + w/2 local aw = w*size local ax = centerx - aw/2 + self.player.direction*aw/2 local ay = y - h/2 local ah = 2*h return ax,ay,aw,ah end function game:draw() love.graphics.draw(self.bg,-40,-40) if not ssloader.success then love.graphics.printf("The sprite sheets have not been generated.\n".. "Please run `dev/gen.sh`.", 0,love.graphics.getHeight()/2,love.graphics.getWidth(),"center") return end table.sort(self.entities,function(a,b) local ax,ay,aw,ah = a:getWorld():getRect(a) local bx,by,bw,bh = b:getWorld():getRect(b) if ay == by then return ax < bx end return ay < by end) local bread_alive = 0 for _,e in pairs(self.entities) do if e:getHealth() > 0 and e:getEClass() == "bread" then bread_alive = bread_alive + 1 end e:draw() end for i = 1,self.player:getHealth() do local frame = math.floor(self.beat*4 % 3) + 1 love.graphics.draw(self.hearts.img,self.hearts.info[frame].quad, 80*(i-1)+16,16) end if self.end_level then love.graphics.setColor(0,0,0,(1-self.end_level/self.end_level_time)*255) love.graphics.rectangle("fill",0,0,love.graphics.getWidth(),love.graphics.getHeight()) love.graphics.setColor(255,255,255) end local text if self.player:getHealth() <= 0 then text = "OH NO, BRO!" if not self.end_level then self.end_level = self.end_level_time sfx:play("failure") end elseif bread_alive > 0 then text = "Bread Alive: "..bread_alive else if not self.end_level then self.end_level = self.end_level_time sfx:play("success") end text = "GOOD JOB BRO! TIME FOR THE NEXT LEVEL!" end love.graphics.printf(text,0,love.graphics.getHeight()/8,love.graphics.getWidth(),"center") end function game:update(dt) self.beat = self.beat + dt if self.end_level then self.end_level = math.max(0,self.end_level - dt) if self.end_level == 0 then self.end_level = nil if self.player:getHealth() <= 0 then hump.gamestate.switch(gamestates.failure) else hump.gamestate.switch(gamestates.levelselect) end end end for _,e in pairs(self.entities) do e:update(dt) if global_debug and love.keyboard.isDown("1") and e:getEClass() == "bread" then e:setHealth(0) end end end function game.player_ai(self) local v = {x=0,y=0} -- Control Parsing if bindings.right() then v.x = 1 end if bindings.left() then v.x = -1 end if bindings.up() then v.y = -1 end if bindings.down() then v.y = 1 end return v,bindings.getTrigger(bindings.jump),bindings.getTrigger(bindings.attack) end function game.bread_ai(self,dt) if self:getDelay() > 0 then self:setDelay( self:getDelay() - dt ) return {x=0,y=0} end local x,y,w,h = self:getWorld():getRect(self) local px,py,pw,ph = self:getWorld():getRect(gamestates.game.player) local dy = py - y local dx = px - x local angle = math.atan2(dy,dx) local v = { x = math.cos(angle), y = math.sin(angle) } return v,nil,nil end function game.dumb_bread_ai(self,dt) return {x=0,y=0},nil,nil end function game.king_bread_ai(self,dt) local x,y,w,h = self:getWorld():getRect(self) if x > love.graphics.getWidth()+200 then self:setHealth(0) end if self:getHealth() < 100 then return {x=1,y=0},nil,nil else return {x=0,y=0},nil,nil end end return game <file_sep>/src/entityclass.lua local entity = {} entity.sprite_fps = 12 entity.hats = {} entity.hats.random = { love.graphics.newImage("assets/hats/pickelhaupe.png"), } entity.hats.special = { crown = love.graphics.newImage("assets/hats/crown.png"), } entity.shadow = love.graphics.newImage("assets/shadow.png") entity.animations = {} for _,vanim in pairs({ {class="bread",name="stand",count=8}, {class="bread",name="walk",count=8}, {class="bread",name="death",count=22}, {class="dino",name="stand",count=10}, {class="dino",name="walk",count=8}, {class="dino",name="jump",count=9}, {class="dino",name="attack",count=6}, {class="dino",name="death",count=24}, }) do if not entity.animations[vanim.class] then entity.animations[vanim.class] = {} end entity.animations[vanim.class][vanim.name] = {} for i = 1, vanim.count do local i,q,d = ssloader.lookup('./'..vanim.class..'/'..vanim.name..'/'..i..'.png') if i then curi,curq,curd = i,q,d end table.insert(entity.animations[vanim.class][vanim.name],{ image = curi, quad = curq, data = curd, }) end end function entity:draw() local x,y,w,h = self:getWorld():getRect(self) local anim_loop = true local anim local default_anim = entity.animations[self:getEClass()].walk if self:getHealth() <= 0 then anim = entity.animations[self:getEClass()].death or default_anim anim_loop = false elseif self:getJumping() then anim = entity.animations[self:getEClass()].jump or default_anim anim_loop = false elseif self:getAttacking() then anim = entity.animations[self:getEClass()].attack or default_anim anim_loop = false elseif self:getWalking() then anim = entity.animations[self:getEClass()].walk or default_anim else anim = entity.animations[self:getEClass()].stand or default_anim end local frame = math.floor(self:getDt()*entity.sprite_fps) if anim_loop then frame = (frame % #anim)+1 else frame = math.min(#anim,frame+1) end local draw_info = anim[frame] local forced_scale = 2 local scale = w/draw_info.data.real_width*2*forced_scale local jump_offset = 0 if self:getJumping() and self:getJumping() < 0.6 then jump_offset = math.sin( self:getJumping() / 0.6 * math.pi ) * 200 end local hit_offset = 0 if self:getHit() and self:getHit() < 1 then hit_offset = math.sin( self:getHit() / 1 * math.pi ) * self:getHitHeight() end local shadow_scale = w/entity.shadow:getWidth() love.graphics.draw(entity.shadow,x,y+h/2,0,shadow_scale,shadow_scale) if self:getInvuln() == nil or self:getInvuln()*8%1 > 0.5 then if self:getDirection() == -1 then love.graphics.draw(draw_info.image,draw_info.quad, x-w/2+(draw_info.data.xoffset-draw_info.data.real_width/(2*2))*scale, y+h-jump_offset-hit_offset, 0,scale,scale, 0,draw_info.data.height) else love.graphics.draw(draw_info.image,draw_info.quad, x+w*1.5-(draw_info.data.xoffset-draw_info.data.real_width/(2*2))*scale, y+h-jump_offset-hit_offset, 0,-scale,scale, 0,draw_info.data.height) end if self:getHat() then local hx = x+w/2-32*self:getDirection() local hy = y-draw_info.data.height*scale-hit_offset-jump_offset local hsy = 64/self:getHat():getWidth() local hsx = hsy*self:getDirection() love.graphics.draw(self:getHat(),hx,hy,0,hsx,hsy) end end if global_debug then love.graphics.rectangle("line",x,y,w,h) love.graphics.rectangle("line", x-draw_info.data.real_width/(2*2)*scale, y-draw_info.data.real_height*scale+h, draw_info.data.real_width*scale, draw_info.data.real_height*scale) love.graphics.rectangle("line",x,y,w,h) love.graphics.setColor(255,0,0,127) love.graphics.rectangle("fill",x,y, w*self:getHealth()/self:getMaxHealth(), h) love.graphics.setColor(255,255,255) local ax,ay,aw,ah = self:getAttackArea() love.graphics.rectangle("line",ax,ay,aw,ah) end end function entity:update(dt) self:setDt( self:getDt() + dt) if self:getInvuln() and self:getEClass() == "dino" then self:setInvuln( self:getInvuln() - dt ) if self:getInvuln() <= 0 then self:setInvuln( nil ) end end local v,jump,attack = self:getAi()(self,dt) if attack and not self:getAttacking() then sfx:play("attack") end if self:getHit() then self:setHit( self:getHit() - dt) v.x = self:getHitDirection()*2 v.y = 0 if self:getHit() <= 0 then self:setHit( nil ) self:setHitDirection( nil ) end end if self:getHealth() > 0 then if jump and not self:getAttacking() then if not self:getJumping() then self:setJumping(1) self:setDt(0) sfx:play("jump") end end if attack and not self:getJumping() then if not self:getAttacking() then self:setAttacking( #entity.animations.dino.attack/entity.sprite_fps ) self:setDt( 0 ) local x,y,w,h = self:getAttackArea() local items = self:getWorld():queryRect(x,y,w,h) for _,e in pairs(items) do if e ~= self then e:damage(self,1) end end end end else v.x = 0 v.y = 0 end -- Action parsing if self:getJumping() then if self:getJumping() < 0.6 then v.x = self:getDirection()*4 v.y = 0 else v.x = 0 v.y = 0 end self:setJumping( self:getJumping() - dt ) if self:getJumping() <= 0 then self:setJumping(nil) sfx:play("land") end end if self:getAttacking() then self:setAttacking( self:getAttacking() - dt ) if self:getAttacking() <= 0 then self:setAttacking( nil ) end v.x = v.x/4 v.y = v.y/4 end if v.x > 0 then self:setDirection( 1 ) elseif v.x < 0 then self:setDirection( -1 ) end if self:getHitDirection() then self:setDirection( -self:getHitDirection() ) end self:setWalking( v.x ~= 0 or v.y ~= 0 ) local x,y,w,h = self:getWorld():getRect(self) local tx = x+v.x*self:getSpeed()*dt local ty = y+v.y*self:getSpeed()/2*dt if self:getEClass() == "dino" then -- clamp player tx = math.max(0,math.min(love.graphics.getWidth() - w,tx)) ty = math.max(350,math.min(650,ty)) end local actualX, actualY, cols, len = self:getWorld():move(self,tx,ty,function(item,other) if item:getJumping() or other:getJumping() or item:getHit() or other:getHit() or item:getHealth() <= 0 or other:getHealth() <= 0 then return nil else return "cross" end end) for _,v in pairs(cols) do local bx,by,bw,bh = v.other:getWorld():getRect(v.other) local dy = by - y local dx = bx - x local angle = math.atan2(dy,dx) + math.pi local tx = x + math.cos(angle)*dt*100 local ty = y + math.sin(angle)*dt*100 -- clamp bread local ctx = math.max(-2000,math.min(love.graphics.getWidth()+2000,tx)) local cty = math.max(350,math.min(650,ty)) self:getWorld():move(self,ctx,cty,function() end) if v.other == gamestates.game.player then gamestates.game.player:damage(self,1) self:damage(gamestates.game.player,1) end end end function entity:getAttackArea() local x,y,w,h = self:getWorld():getRect(self) local size = 1.25 local centerx = x + w/2 local aw = w*size local ax = centerx - aw/2 + self:getDirection()*aw/2 local ay = y - h/2 local ah = 2*h return ax,ay,aw,ah end function entity:damage(other,dmg) if not self:getHit() and not self:getInvuln() then if self:getHealth() > 0 then sfx:play(self:getEClass().."_hurt") end if self:getEClass() == "dino" then self:setInvuln(2) end self:setHit(1) self:setHitDirection(other:getDirection()) local orig_health = self:getHealth() self:setHealth( math.max(0,self:getHealth() - dmg) ) if orig_health ~= self:getHealth() and self:getHealth() == 0 then self:setDt( 0 ) end end end -- LuaClassGen pregenerated functions function entity.new(init) init = init or {} local self={} self.draw=entity.draw self.update=entity.update self.damage=entity.damage self.getAttackArea=entity.getAttackArea self._ai=init.ai or function() end self.getAi=entity.getAi self.setAi=entity.setAi self._dt=init.dt or 0 self.getDt=entity.getDt self.setDt=entity.setDt self._direction=init.direction or 1 self.getDirection=entity.getDirection self.setDirection=entity.setDirection self._health=init.health or 2 self.getHealth=entity.getHealth self.setHealth=entity.setHealth self._maxHealth=init.maxHealth or 2 self.getMaxHealth=entity.getMaxHealth self.setMaxHealth=entity.setMaxHealth self._eClass=init.eClass self.getEClass=entity.getEClass self.setEClass=entity.setEClass self._world=init.world self.getWorld=entity.getWorld self.setWorld=entity.setWorld self._jumping=init.jumping self.getJumping=entity.getJumping self.setJumping=entity.setJumping self._attacking=init.attacking self.getAttacking=entity.getAttacking self.setAttacking=entity.setAttacking self._walking=init.walking self.getWalking=entity.getWalking self.setWalking=entity.setWalking self._hit=init.hit self.getHit=entity.getHit self.setHit=entity.setHit self._hitDirection=init.hitDirection self.getHitDirection=entity.getHitDirection self.setHitDirection=entity.setHitDirection self._speed=init.speed self.getSpeed=entity.getSpeed self.setSpeed=entity.setSpeed self._hitHeight=init.hitHeight or 500 self.getHitHeight=entity.getHitHeight self.setHitHeight=entity.setHitHeight self._invuln=init.invuln self.getInvuln=entity.getInvuln self.setInvuln=entity.setInvuln self._hat=init.hat or (math.random(0,1) == 1 and entity.hats.random[#entity.hats.random] or nil) self.getHat=entity.getHat self.setHat=entity.setHat self._delay=init.delay self.getDelay=entity.getDelay self.setDelay=entity.setDelay return self end function entity:getAi() return self._ai end function entity:setAi(val) self._ai=val end function entity:getDt() return self._dt end function entity:setDt(val) self._dt=val end function entity:getDirection() return self._direction end function entity:setDirection(val) self._direction=val end function entity:getHealth() return self._health end function entity:setHealth(val) self._health=val end function entity:getMaxHealth() return self._maxHealth end function entity:setMaxHealth(val) self._maxHealth=val end function entity:getEClass() return self._eClass end function entity:setEClass(val) self._eClass=val end function entity:getWorld() return self._world end function entity:setWorld(val) self._world=val end function entity:getJumping() return self._jumping end function entity:setJumping(val) self._jumping=val end function entity:getAttacking() return self._attacking end function entity:setAttacking(val) self._attacking=val end function entity:getWalking() return self._walking end function entity:setWalking(val) self._walking=val end function entity:getHit() return self._hit end function entity:setHit(val) self._hit=val end function entity:getHitDirection() return self._hitDirection end function entity:setHitDirection(val) self._hitDirection=val end function entity:getSpeed() return self._speed end function entity:setSpeed(val) self._speed=val end function entity:getHitHeight() return self._hitHeight end function entity:setHitHeight(val) self._hitHeight=val end function entity:getInvuln() return self._invuln end function entity:setInvuln(val) self._invuln=val end function entity:getHat() return self._hat end function entity:setHat(val) self._hat=val end function entity:getDelay() return self._delay end function entity:setDelay(val) self._delay=val end return entity <file_sep>/src/levels/level2.lua local level = {} level.game = function(self) for i = 1,99 do local e = entityclass.new({ world = self.world, direction = -1, eClass = "bread", health = 1, ai = self.bread_ai, speed = math.random(90,110), delay=math.max(i-5), }) table.insert(self.entities,e) self.world:add(e, -1500 + math.random(0,1)*(love.graphics.getWidth()+3000), math.random(350,650),math.random(80,200), 40) end -- KING local e = entityclass.new({ world = self.world, direction = -1, eClass = "bread", health = 10, maxHealth = 100, ai = self.bread_ai, speed = 100, delay = 100, hat = entityclass.hats.special.crown, }) table.insert(self.entities,e) self.world:add(e,love.graphics.getWidth()*3/4,3000,300,40) end function level.cutscene() local cutscene = cutsceneclass.new() local sub = subtitleclass.new() cutscene.audio = {} cutscene:addThing({ time = 0, data = cutscenethingclass.new({ zindex = -10, image = love.graphics.newImage("cutscene/bg.png"), update = function(self,dt) local color = self:getColor() color[4] = math.min( (color[4] or 0) + dt*255, 255 ) end }) }) local dino_bro = cutscenethingclass.new({ image = love.graphics.newImage("cutscene/stand.png"), x = love.graphics.getWidth(), y = 100, zindex=-5, lifespan = 5, time=1, init = function(self) hump.timer.tween(2, self, {_x = 550} , 'out-back') end, }) cutscene:addThing({time=0,data=dino_bro}) cutscene:addThing({ time = 1, lifespan = 5.5, data = cutscenethingclass.new({ init = function(self) local s = love.audio.newSource("cutscene/level2_1.ogg") s:play() table.insert(cutscene.audio,s) end, draw = function(self) sub:draw("<NAME> was lucky that day, as he had his oversized butter knife.") end }) }) cutscene:addThing({ time = 6.5, lifespan = 2.5, data = cutscenethingclass.new({ init = function(self) local s = love.audio.newSource("cutscene/level2_2.ogg") s:play() table.insert(cutscene.audio,s) end, draw = function(self) sub:draw("<NAME>: I was using it to open beers!") end }) }) local king_cs = cutscenethingclass.new({ image = love.graphics.newImage("cutscene/king_angry.png"), x = -400, y = 100, zindex=-5, lifespan = 5, time=3, init = function(self) hump.timer.tween(2, self, {_x = 50} , 'out-back') end, }) cutscene:addThing({time=3,data=king_cs}) cutscene:addThing({ time = 3, lifespan = 8, data = cutscenethingclass.new({ init = function(self) local s = love.audio.newSource("cutscene/level2_3.ogg") s:play() table.insert(cutscene.audio,s) end, draw = function(self) sub:draw("The Bread King, his ego wounded by his previous encounter with <NAME>, called his army to defeat him.") end }) }) cutscene:addThing({ time = 8.5, lifespan = 3, data = cutscenethingclass.new({ init = function(self) local s = love.audio.newSource("cutscene/level2_4.ogg") s:play() table.insert(cutscene.audio,s) end, draw = function(self) sub:draw("<NAME>: Time to Bro Down!") end }) }) cutscene:addThing({ time = 3.5, lifespan = 3, data = cutscenethingclass.new({ init = function(self) local s = love.audio.newSource("cutscene/level2_5.ogg") s:play() table.insert(cutscene.audio,s) end, draw = function(self) sub:draw("And Bro Down he did.") end }) }) cutscene:addThing({ time = 3.5, lifespan = 3, data = cutscenethingclass.new({ init = function(self) cutscene.done = true end, }) }) return cutscene end return level <file_sep>/src/gamestates/cutscene.lua local cutscene = {} function cutscene:enter() self.data = currentlevel.cutscene() end function cutscene:draw() if self.data then self.data:draw() end end function cutscene:update(dt) if global_debug and love.keyboard.isDown("tab") then dt = dt * 8 end if self.data then self.data:update(dt) hump.timer.update(dt) if self.data.done then hump.gamestate.switch(gamestates.game) end if bindings.getTrigger(bindings.select) then if self.data and self.data.audio then for i,v in pairs(self.data.audio) do v:stop() end self.data.cutscene_audio = {} end hump.gamestate.switch(gamestates.game) end else hump.gamestate.switch(gamestates.game) end end return cutscene <file_sep>/src/bindings.lua local bindings = {} bindings._triggers = {} function bindings.getTrigger(bind) local player = "player_1" local index = tostring(player).."_"..tostring(bind) if bind() then -- no player relation as of yet if bindings._triggers[index] then bindings._triggers[index] = nil return true end else bindings._triggers[index] = true return end end bindings.select = function() return love.keyboard.isDown(" ","return") end bindings.up = function() return love.keyboard.isDown("up","w") end bindings.down = function() return love.keyboard.isDown("down","s") end bindings.left = function() return love.keyboard.isDown("left","a") end bindings.right = function() return love.keyboard.isDown("right","d") end bindings.attack = function() return love.keyboard.isDown("z",".","y") -- QWERTZ end bindings.jump = function() return love.keyboard.isDown("x","/") end bindings.debug = function() return love.keyboard.isDown("`") end return bindings <file_sep>/dev/gen.sh #!/bin/sh cd assets find . -name "*.png" > list texpack --trim --pretty --max-size 2048x2048 --padding 1 --output ../../src/assets/ss list rm list cd - cd hearts find . -name "*.png" > list texpack --output ../../src/assets/hearts --max-size 2048x2048 --pretty --trim list rm list cd - <file_sep>/src/cutscene/cutsceneclass.lua local cutscene = {} function cutscene:draw() for _,v in pairs(self._things) do if v.data then if self._curtime >= v.time then love.graphics.setColor(v.data:getColor()) v.data:getDraw()(v.data) end end end end function cutscene:update(dt) self._curtime = self._curtime + dt table.sort(self._things,function(a,b) return a.data:getZindex() < b.data:getZindex() end) for _,v in pairs(self._things) do if v.lifespan then v.lifespan = v.lifespan - dt if v.lifespan <= 0 then self:removeThing(v) end end if self._curtime >= v.time then if not v.init then v.init = true if v.data then v.data:getInit()(v.data) end end if v.data then v.data:getUpdate()(v.data,dt) end end end self:removeThing() -- cleanup end -- LuaClassGen pregenerated functions function cutscene.new(init) init = init or {} local self={} self.draw=cutscene.draw self.update=cutscene.update self._width=init.width or love.graphics.getWidth() self.getWidth=cutscene.getWidth self.setWidth=cutscene.setWidth self._height=init.height or love.graphics.getHeight() self.getHeight=cutscene.getHeight self.setHeight=cutscene.setHeight self._audio=init.audio self.getAudio=cutscene.getAudio self.setAudio=cutscene.setAudio self._things={} self.addThing=cutscene.addThing self.removeThing=cutscene.removeThing self.getThings=cutscene.getThings self._curtime = 0 self._addtime = 0 return self end function cutscene:getWidth() return self._width end function cutscene:setWidth(val) self._width=val end function cutscene:getHeight() return self._height end function cutscene:setHeight(val) self._height=val end function cutscene:getAudio() return self._audio end function cutscene:setAudio(val) self._audio=val end function cutscene:addThing(val) assert(type(val)=="table","Error: collection `self._things` can only add `table`") self._addtime = self._addtime + val.time val.time = self._addtime if val.lifespan then val.lifespan = val.lifespan + val.time end table.insert(self._things,val) end function cutscene:removeThing(val) if val == nil then for i,v in pairs(self._things) do if v._remove then table.remove(self._things,i) end end self._things_dirty=nil else local found = false for i,v in pairs(self._things) do if v == val then found = true break end end assert(found,"Error: collection `self._things` does not contain `val`") val._remove=true self._things_dirty=true end end function cutscene:getThings() assert(not self._things_dirty,"Error: collection `self._things` is dirty.") return self._things end return cutscene <file_sep>/src/levels/level1.lua local level = {} level.game = function(self) -- KING local e = entityclass.new({ world = self.world, direction = -1, eClass = "bread", health = 100, maxHealth = 100, ai = self.king_bread_ai, speed = 100, hat = entityclass.hats.special.crown, }) table.insert(self.entities,e) self.world:add(e,love.graphics.getWidth()*1/2,500,300,40) end level.cutscene = function() local cutscene = cutsceneclass.new() local sub = subtitleclass.new() cutscene.audio = {} cutscene:addThing({ time=0, lifespan=5, data = cutscenethingclass.new({ zindex=-10, image = love.graphics.newImage("assets/dinotopia.png"), init = function(self) hump.timer.tween(5,self, {_sx=1.2,_sy=1.2,_x=-1000/2,_y=-580/2,_r=-0.2},'linear') end, }) }) cutscene:addThing({ time = 0, lifespan = 5, data = cutscenethingclass.new({ init = function(self) local s = love.audio.newSource("cutscene/level1_1.ogg") s:play() table.insert(cutscene.audio,s) end, draw = function(self) sub:draw("A Long time ago there was a planet called dinotopia...") end, }) }) cutscene:addThing({ time = 5, data = cutscenethingclass.new({ zindex = -10, image = love.graphics.newImage("cutscene/bg.png"), update = function(self,dt) local color = self:getColor() color[4] = math.min( (color[4] or 0) + dt*255, 255 ) end }) }) cutscene:addThing({ time = 1, lifespan = 3, data = cutscenethingclass.new({ init = function(self) local s = love.audio.newSource("cutscene/level1_2.ogg") s:play() table.insert(cutscene.audio,s) end, draw = function(self) sub:draw("And on this planet, there was a dinosaur.") end }) }) local dino_bro = cutscenethingclass.new({ image = love.graphics.newImage("cutscene/stand.png"), x = love.graphics.getWidth(), y = 100, zindex=-5, init = function(self) hump.timer.tween(2, self, {_x = 300} , 'out-back') end, }) cutscene:addThing({time=1,data=dino_bro}) cutscene:addThing({ time=3, lifespan=2, data = cutscenethingclass.new({ init = function(self) local s = love.audio.newSource("cutscene/level1_3.ogg") s:play() table.insert(cutscene.audio,s) end, draw = function(self) sub:draw("The Dino Bro.") end }) }) cutscene:addThing({ time=3, lifespan=2, data = cutscenethingclass.new({ init = function(self) local s = love.audio.newSource("cutscene/level1_4.ogg") s:play() table.insert(cutscene.audio,s) end, draw = function(self) sub:draw("Dino Bro: Where all the dino-hos at?") end }) }) cutscene:addThing({ time=3, lifespan=4, data = cutscenethingclass.new({ init = function(self) local s = love.audio.newSource("cutscene/level1_5.ogg") s:play() table.insert(cutscene.audio,s) end, draw = function(self) sub:draw("He lived a life one would expect of a dinosaur.") end }) }) cutscene:addThing({ time=4, lifespan=3.5, data = cutscenethingclass.new({ init = function(self) local s = love.audio.newSource("cutscene/level1_6.ogg") s:play() table.insert(cutscene.audio,s) end, draw = function(self) sub:draw("Dino Bro: Bro everyday, bro! I'm six deep!") end }) }) cutscene:addThing({ time=4, lifespan=11.5, data = cutscenethingclass.new({ init = function(self) local s = love.audio.newSource("cutscene/level1_7.ogg") s:play() table.insert(cutscene.audio,s) end, draw = function(self) sub:draw("One day, as <NAME> was swaggering through the prehistoric forest thinking about all the hot bangin' dino-ladies, he came upon a sandwich.") end }) }) cutscene:addThing({ time = 10, lifespan = 0, data = cutscenethingclass.new({ init = function(self) dino_bro:setImage( love.graphics.newImage("cutscene/eating.png") ) end }) }) cutscene:addThing({ time=3, lifespan=4.5, data = cutscenethingclass.new({ init = function(self) local s = love.audio.newSource("cutscene/level1_8.ogg") s:play() table.insert(cutscene.audio,s) end, draw = function(self) sub:draw("Dino Bro: It's Bro-Tien time! *Manf Manf Manf*") end }) }) cutscene:addThing({ time = 0, lifespan = 0, data = cutscenethingclass.new({ init = function(self) hump.timer.tween(2, dino_bro, {_x = -1200} , 'out-back') end }) }) cutscene:addThing({ time = 5, lifespan = 7, data = cutscenethingclass.new({ init = function(self) local s = love.audio.newSource("cutscene/level1_9.ogg") s:play() table.insert(cutscene.audio,s) end, draw = function(self) sub:draw("The Dino Bro was not a fan of crusts, so he threw them to the ground for the birds.") end, }) }) local king = cutscenethingclass.new({ time = 2, image = love.graphics.newImage("cutscene/king_sad.png"), x = love.graphics.getWidth(), y = 100, zindex=-5, init = function(self) hump.timer.tween(2, self, {_x = 300} , 'out-back') end, }) cutscene:addThing({time=4,data=king}) cutscene:addThing({ time = 3, lifespan = 7, data = cutscenethingclass.new({ init = function(self) local s = love.audio.newSource("cutscene/level1_10.ogg") s:play() table.insert(cutscene.audio,s) end, draw = function(self) sub:draw("The Bread King happened upon the remains of the sandwich which was the princess, his daughter.") end, }) }) cutscene:addThing({ time = 7, lifespan = 7, data = cutscenethingclass.new({ init = function(self) local s = love.audio.newSource("cutscene/level1_11.ogg") s:play() table.insert(cutscene.audio,s) end, draw = function(self) sub:draw("He vowed revenge on the Dino Bro, as no other dinosaur would leave just the crusts.") end, }) }) cutscene:addThing({ time = 7, lifespan = 3.5, data = cutscenethingclass.new({ init = function(self) local s = love.audio.newSource("cutscene/level1_12.ogg") s:play() table.insert(cutscene.audio,s) end, draw = function(self) sub:draw("Bread King: I shall exact my vengance on you, <NAME>!") end, }) }) cutscene:addThing({ time = 4.5, lifespan = 3, data = cutscenethingclass.new({ init = function(self) cutscene.done = true end, }) }) return cutscene end return level <file_sep>/src/cutscene/main.lua local cutsceneclass = require "cutsceneclass" local cutscenethingclass = require "cutscenethingclass" cut = cutsceneclass.new() bg = cutscenethingclass.new({ image = love.graphics.newImage("bg.png") }) cut:addThing({time=0,data=bg}) dino = cutscenethingclass.new({ zindex = 1, alpha = 0, image = love.graphics.newImage("stand.png"), update = function(self,dt) local color = self:getColor() color[4] = math.min((color[4] or 0) + dt*255,255) self:setColor(color) end, }) cut:addThing({time=1,data=dino}) function love.draw() cut:draw() end function love.update(dt) cut:update(dt) end <file_sep>/restart.sh #!/bin/sh while [ true ]; do ./run.sh; sleep 1; done <file_sep>/src/bubble/bubbleclass.lua local bubble = {} function bubble:draw(text,x,y,target_w,pos) local font = love.graphics.getFont() local w,lines = font:getWrap(text,target_w) local h = font:getHeight()*lines love.graphics.draw(self:getImgTop(), x, y-self:getImgTop():getHeight(), 0,w/self:getImgTop():getWidth(),1) love.graphics.draw(self:getImgTopRight(), x+w, y-self:getImgTopRight():getHeight(), 0,1,1) love.graphics.draw(self:getImgRight(), x+w, y, 0,1,h/self:getImgRight():getHeight()) love.graphics.draw(self:getImgBottomRight(), x+w, y+h, 0,1,1) love.graphics.draw(self:getImgBottom(), x, y+h, 0,w/self:getImgBottom():getWidth(),1) love.graphics.draw(self:getImgBottomLeft(), x-self:getImgBottomLeft():getWidth(), y+h, 0,1,1) love.graphics.draw(self:getImgLeft(), x-self:getImgLeft():getWidth(), y, 0,1,h/self:getImgLeft():getHeight()) love.graphics.draw(self:getImgTopLeft(), x-self:getImgTopLeft():getWidth(), y-self:getImgTopLeft():getHeight(), 0,1,1) love.graphics.draw(self:getImgInside(), x,y,0, w/self:getImgInside():getWidth(), h/self:getImgInside():getHeight()) local tailx = x + (w - self:getImgTail():getWidth())/2 if pos == "left" then tailx = x elseif pos == "right" then tailx = x + w - self:getImgTail():getWidth() end love.graphics.draw(self:getImgTail(), tailx,y+h,0,1,1) local old = {love.graphics.getColor()} love.graphics.setColor(self:getFontColor()) love.graphics.printf(text,x,y,w,"center") love.graphics.setColor(old) -- TODO (bubbleclass.draw.lcg.lua) end -- LuaClassGen pregenerated functions function bubble.new(init) init = init or {} local self={} self.draw=bubble.draw self._imgTop=init.imgTop self.getImgTop=bubble.getImgTop self.setImgTop=bubble.setImgTop self._imgTopRight=init.imgTopRight self.getImgTopRight=bubble.getImgTopRight self.setImgTopRight=bubble.setImgTopRight self._imgRight=init.imgRight self.getImgRight=bubble.getImgRight self.setImgRight=bubble.setImgRight self._imgBottomRight=init.imgBottomRight self.getImgBottomRight=bubble.getImgBottomRight self.setImgBottomRight=bubble.setImgBottomRight self._imgBottom=init.imgBottom self.getImgBottom=bubble.getImgBottom self.setImgBottom=bubble.setImgBottom self._imgBottomLeft=init.imgBottomLeft self.getImgBottomLeft=bubble.getImgBottomLeft self.setImgBottomLeft=bubble.setImgBottomLeft self._imgLeft=init.imgLeft self.getImgLeft=bubble.getImgLeft self.setImgLeft=bubble.setImgLeft self._imgTopLeft=init.imgTopLeft self.getImgTopLeft=bubble.getImgTopLeft self.setImgTopLeft=bubble.setImgTopLeft self._imgTail=init.imgTail self.getImgTail=bubble.getImgTail self.setImgTail=bubble.setImgTail self._imgInside=init.imgInside self.getImgInside=bubble.getImgInside self.setImgInside=bubble.setImgInside self._fontColor=init.fontColor self.getFontColor=bubble.getFontColor self.setFontColor=bubble.setFontColor return self end function bubble:getImgTop() return self._imgTop end function bubble:setImgTop(val) self._imgTop=val end function bubble:getImgTopRight() return self._imgTopRight end function bubble:setImgTopRight(val) self._imgTopRight=val end function bubble:getImgRight() return self._imgRight end function bubble:setImgRight(val) self._imgRight=val end function bubble:getImgBottomRight() return self._imgBottomRight end function bubble:setImgBottomRight(val) self._imgBottomRight=val end function bubble:getImgBottom() return self._imgBottom end function bubble:setImgBottom(val) self._imgBottom=val end function bubble:getImgBottomLeft() return self._imgBottomLeft end function bubble:setImgBottomLeft(val) self._imgBottomLeft=val end function bubble:getImgLeft() return self._imgLeft end function bubble:setImgLeft(val) self._imgLeft=val end function bubble:getImgTopLeft() return self._imgTopLeft end function bubble:setImgTopLeft(val) self._imgTopLeft=val end function bubble:getImgTail() return self._imgTail end function bubble:setImgTail(val) self._imgTail=val end function bubble:getImgInside() return self._imgInside end function bubble:setImgInside(val) self._imgInside=val end function bubble:getFontColor() return self._fontColor end function bubble:setFontColor(val) self._fontColor=val end return bubble <file_sep>/src/levels/level3.lua local level = {} level.game = function(self) end function level.cutscene() local cutscene = cutsceneclass.new() local sub = subtitleclass.new() cutscene.audio = {} cutscene:addThing({ time = 0, data = cutscenethingclass.new({ zindex = -10, image = love.graphics.newImage("cutscene/bros.png"), update = function(self,dt) local color = self:getColor() color[4] = math.min( (color[4] or 0) + dt*255, 255 ) end }) }) cutscene:addThing({ time = 1, lifespan = 7, data = cutscenethingclass.new({ init = function(self) local s = love.audio.newSource("cutscene/level3_1.ogg") s:play() table.insert(cutscene.audio,s) end, draw = function(self) sub:draw("With the Bread King and his bread army defeated, <NAME> returns to his normal daily life.") end }) }) local dino = cutscenethingclass.new({ time = 1, image = love.graphics.newImage("cutscene/stand.png"), x = love.graphics.getWidth(), y = 100, zindex=-5, lifespan = 5, time=1, init = function(self) hump.timer.tween(2, self, {_x = 50} , 'out-back') end, }) cutscene:addThing({time=0,data=dino}) cutscene:addThing({ time = 8, lifespan = 1.5, data = cutscenethingclass.new({ init = function(self) local s = love.audio.newSource("cutscene/level3_2.ogg") s:play() table.insert(cutscene.audio,s) end, draw = function(self) sub:draw("Dino Bro: Bro") end }) }) cutscene:addThing({ time = 2, lifespan = 1.5, data = cutscenethingclass.new({ init = function(self) local s = love.audio.newSource("cutscene/level3_3.ogg") s:play() table.insert(cutscene.audio,s) end, draw = function(self) sub:draw("Bro of Dino Bro: Bro") end }) }) cutscene:addThing({ time = 2, lifespan = 1.5, data = cutscenethingclass.new({ init = function(self) local s = love.audio.newSource("cutscene/level3_4.ogg") s:play() table.insert(cutscene.audio,s) end, draw = function(self) sub:draw("Bro of Bro of Dino Bro: Bro") end }) }) cutscene:addThing({ time = 2, lifespan = 1.5, data = cutscenethingclass.new({ init = function(self) local s = love.audio.newSource("cutscene/level3_5.ogg") s:play() table.insert(cutscene.audio,s) end, draw = function(self) sub:draw("Dino Bro: Bro") end }) }) cutscene:addThing({ time = 2, lifespan = 7, data = cutscenethingclass.new({ init = function(self) local s = love.audio.newSource("cutscene/level3_6.ogg") s:play() table.insert(cutscene.audio,s) end, draw = function(self) sub:draw("And he lived happily every after, eating tasty sandwiches every day for the rest of his life.") end }) }) cutscene:addThing({ time = 9, lifespan = 3, data = cutscenethingclass.new({ init = function(self) hump.gamestate.switch(gamestates.menu) end, }) }) return cutscene end return level <file_sep>/src/subtitle/subtitleclass.lua local subtitle = {} function subtitle:draw(text) local font = love.graphics.getFont() local tw,lines = font:getWrap(text,love.graphics.getWidth()) local w = love.graphics.getWidth() local h = font:getHeight()*lines local padding = 16 local x,y = 0,love.graphics.getHeight()*3/4 local oldcolor = {love.graphics.getColor()} love.graphics.setColor(0,0,0,127) love.graphics.rectangle("fill",x,y-padding,w,h+padding*2) love.graphics.setColor(255,255,255) love.graphics.printf(text,x+padding,y,w-padding*2,"center") love.graphics.setColor(oldcolor) end function subtitle:update(dt) -- TODO (subtitleclass.update.lcg.lua) end -- LuaClassGen pregenerated functions function subtitle.new(init) init = init or {} local self={} self.draw=subtitle.draw self.update=subtitle.update self._text=init.text self.getText=subtitle.getText self.setText=subtitle.setText return self end function subtitle:getText() return self._text end function subtitle:setText(val) self._text=val end return subtitle <file_sep>/src/main.lua hump = { camera = require "hump.camera", gamestate = require "hump.gamestate", timer = require "hump.timer", } bubbleclass = require "bubble.bubbleclass" subtitleclass = require "subtitle.subtitleclass" require 'json' splashclass = require "splashclass" ssloader = require "ssloader" ssloader.load("assets/") entityclass = require "entityclass" bump = require "bump" fonts = { speechbubble = love.graphics.newFont("assets/Schoolbell.ttf",32) } sfx = require "sfxclass" bindings = require "bindings" love.graphics.setFont(fonts.speechbubble) dir = "bubble/good/" bubble = bubbleclass.new({ imgTop = love.graphics.newImage(dir.."top.png"), imgTopRight = love.graphics.newImage(dir.."top_right.png"), imgRight = love.graphics.newImage(dir.."right.png"), imgBottomRight = love.graphics.newImage(dir.."bottom_right.png"), imgBottom = love.graphics.newImage(dir.."bottom.png"), imgBottomLeft = love.graphics.newImage(dir.."bottom_left.png"), imgLeft = love.graphics.newImage(dir.."left.png"), imgTopLeft = love.graphics.newImage(dir.."top_left.png"), imgInside = love.graphics.newImage(dir.."inside.png"), imgTail = love.graphics.newImage(dir.."tail.png"), fontColor={0,0,0} }) cutsceneclass = require "cutscene.cutsceneclass" cutscenethingclass = require "cutscene.cutscenethingclass" gamestates = { splash = require "gamestates.splash", menu = require "gamestates.menu", levelselect = require "gamestates.levelselect", cutscene = require "gamestates.cutscene", game = require "gamestates.game", failure = require "gamestates.failure", } function love.load() hump.gamestate.registerEvents() hump.gamestate.switch(gamestates.splash) end function love.update(dt) if bindings.getTrigger(bindings.debug) then global_debug = not global_debug end end <file_sep>/src/ssloader.lua local ssloader = {} function ssloader.load(dir) local files = love.filesystem.getDirectoryItems( dir ) ssloader.img = {} ssloader.data = {} for i,v in pairs(files) do local d = string.match(v,'ss%-(%d+)%.png') if d then local json_file = dir..'ss-'..d..'.json' --print("loading",dir..v) ssloader.img[d] = love.graphics.newImage(dir..v) --print("loading",json_file) local json_raw = love.filesystem.read(json_file) local json_data = json.decode(json_raw) ssloader.data[d] = json_data ssloader.success = true end end end function ssloader.lookup(name) for isheet,vsheet in pairs(ssloader.data) do for isprite,vsprite in pairs(vsheet.sprites) do if isprite == name then local quad = love.graphics.newQuad( vsprite.x,vsprite.y, vsprite.width,vsprite.height, vsheet.width,vsheet.height) return ssloader.img[isheet],quad,vsprite end end end end return ssloader <file_sep>/src/subtitle/main.lua subtitleclass = require "subtitleclass" s = subtitleclass.new() function love.update(dt) s:update(dt) end function love.draw() love.graphics.setColor(126,126,12) love.graphics.rectangle("fill",0,0,10000,10000) love.graphics.setColor(255,255,255) s:draw("And so the story goes ....") end <file_sep>/story.md # Level 1 ## Cutscene * _Show planet_ * 1 Narrator: A Long time ago on the planet of dinotopia * _Show forest_ * 2 Narrator: And on this planet, there was a dinosaur. * _Show Dino Bro_ * 3 Narrator: The Dino Bro * 4 Dino Bro: Where all the dino-hos at? * 5 Narrator: He lived a life one would expect of a dinosaur. * _Show dino bro shaking_ * 6 Dino Bro: Bro everyday bro! I'm six deep! * _Show sandwich_ * 7 Narrator: One day, as Dino Bro was swaggering through the prehistoric forest thinking about all the hot "bangin' dino-ladies", he came upon a sandwich. * _Show Dino Eating sandwich_ * 8 Dino Bro: It's Bro-Tien time! *Manf Manf Manf* * 9 Narrator: The Dino Bro was not a fan of crusts, so he threw them to the ground for the birds. * _Show sad king_ * 10 Narrator: The Bread King happened upon the remains of the sandwich which was the princess, his daughter. * 11 Narrator: He vowed revenge on the Dino Bro, as no other dinosaur would leave just the crusts. * 12 Bread King: "I shall exact my vengance on you, Dino Bro!" ## Level * The king is huge. * The King with a huge amount of health walks to the center of the right half of the screen, and just stands there. * Once the player hits the king, the bread runs to the right, and is removed from the game. # Level 2 ## Cutscene * _Show dino bro with knife (use one of anim assets)_ * 1 Narrator: Dino Bro was lucky that day, as he had his oversized butter knife. * 2 Dino Bro: I was using it to open beers! * _Show forest covered in bread people._ * 3 Narrator: The Bread King, his ego wounded by his previous encounter with <NAME>, called his army to defeat him. * _Show dino bro_ * 4 Dino Bro: Time to Bro Down * 5 Narrator: And Bro Down he did. ## Level * The king is huge. * Many bread people, all with varying size, HP and speed are created over time, ending with a huge bread that has like 10 HP and is really big (e.g. the King) # Level 3 * _Show dino bros scene_ * 1 Narrator: With the Bread King and his bread army defeated, <NAME> returns to his normal daily life. * 2 Dino Bro: Bro * 3 Dino Bro #2: Bro * 4 Dino Bro #3: Bro * 5 Dino Bro: Bro * 6 Narrator: And he lived happily every after, eating tasty sandwiches every day for the rest of his life. ## Level * Change gamestate to game win <file_sep>/run.sh #!/bin/sh # Love doesn't like symlinks! Oh noes! SRC="src" LOVE="love" sh ./gengit.sh $SRC # *.love cd $SRC TEMPFILE="._temp.love" echo "Updating '$TEMPFILE' ..." zip --filesync -r ../$TEMPFILE * cd .. exec $LOVE --fused $TEMPFILE "$@" <file_sep>/src/gamestates/failure.lua local failure = {} function failure:init() self.bg = love.graphics.newImage("assets/failure.png") end function failure:draw() love.graphics.draw(self.bg) end function failure:update(dt) if bindings.getTrigger(bindings.select) then gamestates.levelselect.cur=0 hump.gamestate.switch(gamestates.menu) end end return failure <file_sep>/src/sfxclass.lua local sfxclass = {} sfxclass.data = { attack = { love.audio.newSource("assets/sfx/attack.wav","static"), }, bread_hurt = { love.audio.newSource("assets/sfx/bread_hurt1.wav","static"), love.audio.newSource("assets/sfx/bread_hurt2.wav","static"), love.audio.newSource("assets/sfx/bread_hurt3.wav","static"), }, dino_hurt = { love.audio.newSource("assets/sfx/dino_hurt1.wav","static"), love.audio.newSource("assets/sfx/dino_hurt2.wav","static"), love.audio.newSource("assets/sfx/dino_hurt3.wav","static"), }, failure = { love.audio.newSource("assets/sfx/failure.wav","static"), }, success = { love.audio.newSource("assets/sfx/success.wav","static"), }, jump = { love.audio.newSource("assets/sfx/jump.wav","static"), }, land = { love.audio.newSource("assets/sfx/land.wav","static"), } } function sfxclass:play(sfx_name) --print("Playing",sfx_name) if self.data[sfx_name] then local sound = self.data[sfx_name][math.random(1,#self.data[sfx_name])] if sound:isPlaying() then sound:stop() end sound:play() else print("Warning: This sound does not exist.") end end return sfxclass <file_sep>/src/cutscene/cutscenethingclass.lua local cutscenething = {} function cutscenething.new(init) init = init or {} local self={} self._x=init.x or 0 self.getX=cutscenething.getX self.setX=cutscenething.setX self._y=init.y or 0 self.getY=cutscenething.getY self.setY=cutscenething.setY self._sx=init.sx or 1 self.getSx=cutscenething.getSx self.setSx=cutscenething.setSx self._sy=init.sy or 1 self.getSy=cutscenething.getSy self.setSy=cutscenething.setSy self._r=init.r or 0 self.getR=cutscenething.getR self.setR=cutscenething.setR self._color=init.color or {255,255,255} self.getColor=cutscenething.getColor self.setColor=cutscenething.setColor self._zindex=init.zindex or 0 self.getZindex=cutscenething.getZindex self.setZindex=cutscenething.setZindex self._image=init.image self.getImage=cutscenething.getImage self.setImage=cutscenething.setImage self._draw=init.draw or cutscenething._defaultDraw self._init=init.init or function(self) end self.getInit=cutscenething.getInit self.setInit=cutscenething.setInit self.getDraw=cutscenething.getDraw self.setDraw=cutscenething.setDraw self._update=init.update or function(self,dt) end self.getUpdate=cutscenething.getUpdate self.setUpdate=cutscenething.setUpdate return self end function cutscenething._defaultDraw(self) if self:getImage() then love.graphics.draw(self:getImage(), self:getX(),self:getY(),self:getR(), self:getSx(),self:getSy()) end end function cutscenething:getX() return self._x end function cutscenething:setX(val) self._x=val end function cutscenething:getY() return self._y end function cutscenething:setY(val) self._y=val end function cutscenething:getSx() return self._sx end function cutscenething:setSx(val) self._sx=val end function cutscenething:getSy() return self._sy end function cutscenething:setSy(val) self._sy=val end function cutscenething:getR() return self._r end function cutscenething:setR(val) self._r=val end function cutscenething:getColor() return self._color end function cutscenething:setColor(val) self._color=val end function cutscenething:getZindex() return self._zindex end function cutscenething:setZindex(val) self._zindex=val end function cutscenething:getImage() return self._image end function cutscenething:setImage(val) self._image=val end function cutscenething:getInit() return self._init end function cutscenething:setInit(val) self._init=val end function cutscenething:getDraw() return self._draw end function cutscenething:setDraw(val) self._draw=val end function cutscenething:getUpdate() return self._update end function cutscenething:setUpdate(val) self._update=val end return cutscenething <file_sep>/src/gamestates/menu.lua local menu = {} function menu:init() self.bg = love.graphics.newImage("assets/menu.png") self.music = love.audio.newSource("assets/menu.ogg","stream") self.music:setLooping(true) end function menu:enter() self.music:play() end function menu:leave() self.music:stop() end function menu:draw() love.graphics.draw(self.bg) end function menu:update(dt) if bindings.getTrigger(bindings.select) then hump.gamestate.switch(gamestates.levelselect) end end return menu <file_sep>/notes.txt Theme: An Unconventional Weapon * Cutscenes entity - x,y,sx,sy,r,alpha,image * Dino has different silly weapons? * Local Multiplayer? * Platformer or TMNT3 Staged? * Parralax? [NOPE] Current Assets: * Background (3 layers) * Entities * Bread * Moldy * King * Queen * Rye * White * Dino - Player * Animations * Walking * Death * Jump * Standing (dino only) * Attack (dino only) GUI * Hearts
5455e9fa24e741c642eec94d2babb274d117b59b
[ "Markdown", "Text", "Shell", "Lua" ]
25
Lua
josefnpat/LD32
427e65ec6db67e11c0e6b2560478b70f219032a5
65dce957616a77e8e95a69e1e04c8660e8076398
refs/heads/master
<repo_name>CrytonAndrew/Portfolio-Site-V2<file_sep>/projects/book-landing/app.js gsap.from(".main-image", {duration: 1.5, opacity: 0, scale: 0.3, ease: "back"}); // Starts with this animation gsap.to(".main-image", {duration: 2, x: 200}); // Moves the element from its current position to 300 pixels down gsap.to(".main-title", {duration: 2, y: 100}); gsap.to(".main-description", {duration: 2, y: 100}); gsap.to(".sign-up-btn", {duration: 2, y: 100}); gsap.to(".contact-btn", {duration: 2, y: 100}); const sr = ScrollReveal({ origin: "top", distance: "80px", duration: 2000, reset: true, }); // About Section Reveal sr.reveal(".about-book-icon", {}); sr.reveal(".about-book-title", {}); sr.reveal(".about-book-p", {delay: 200}); sr.reveal(".about-book-quote", {delay: 200}); sr.reveal(".vl", {delay: 200}); // Review Section Reveal sr.reveal(".review-text", {}); sr.reveal(".visually-hidden", {delay: 200}); // About author Section sr.reveal(".about-author-title", {}); sr.reveal(".about-author-hr", {}); sr.reveal(".author-images", {delay: 200}); sr.reveal(".about-author-p", {delay: 200}); // Contact section Reveal sr.reveal(".contact-me-title", {}); sr.reveal(".form-control", {delay: 200}); sr.reveal(".form-label", {delay: 200}); sr.reveal(".info-title", {}); sr.reveal(".info-p", {delay: 200}); sr.reveal(".submit-form", {delay: 200});<file_sep>/projects/book-landing/README.md # Book Landing Page
56df39cfb39e7f2dd44882deaf94bf951d1119ca
[ "JavaScript", "Markdown" ]
2
JavaScript
CrytonAndrew/Portfolio-Site-V2
ebf05613e36f9c1076975f9621f7480308f20d56
9fcaded1a0ab544c8954966a965a72e938dace8b
refs/heads/master
<file_sep>/* *********************************************************************************************************** * Bdds16.c * * Wersja:pre-alpha * * e-mail:<EMAIL> * * 2014 * *********************************************************************************************************** Plik aktualnie tymczasowo dołączany do głównego pliku jądra kernel.c, zawierający podstawowe procedury obsługujce podstawowe urządzenia systemowe (ekran, klawiaturę, FDD, PIC,DMA) w 16 bitowym trybie rzeczyw istym. Zalążek sterownika Basic Device Drivers.*/ /*Ekran:*/ void printrm(text)char text[]; { /* Procedura wyświetla tekst podany w parametrze text.Działa w trybie rzeczywistym */ char c,temp; c = 14; for (temp=0;text[temp] != 0; temp++) { c = text[temp]; asm(".intel_syntax noprefix\n" "push ax\n" "push bx\n" "push cx\n" "push dx\n" "mov ah,0xE\n" "mov al,%[res]\n" "mov bl,7\n" "mov bh,0\n" "int 0x10\n" "pop dx\n" "pop cx\n" "pop bx\n" "pop ax\n" ".att_syntax prefix\n" : :[res] "r" (c) ); } }<file_sep>/* *********************************************************************************************************** * Bdds.c * * Wersja:pre-alpha * * e-mail:<EMAIL> * * 2014 * *********************************************************************************************************** Plik aktualnie tymczasowo dołączany do głównego pliku jądra kernel.c, zawierający podstawowe procedury obsługujce podstawowe urządzenia systemowe (ekran, klawiaturę, FDD, PIC,DMA) zarówno w trybie rzeczyw istym jak i chronionym. Zalążek sterownika Basic Device Drivers.*/ #include "data.h" #include <stdarg.h> /*Kontroler przerwań (PIC 8259A) */ void PICInitInPM() { /*Przygotowuje system obsługi przerwań sprzętowych do pracy w trybie chronionym.Mskuje wszystkie przerywania maskowalne */ uchar temp; SetCallStack(9) /*Najpierw zamaskowanie wszystkich przerwań */ /*Najpier zamaskowanie przerwań w układach master i slave */ outb(0x21,0xFF); outb(0x0A1,0xFF); /*Następnie przygotowanie układów do pracy w trybie chronionym CPU.Master: */ outb(0x20,0x11); //Wysłanie bajtu ICW1 do układu master DelayLoop(100); //Opóźnienie outb(0x21,0x20); //Wysłanie bajtu ICW2 do układu master, ten bajt to przemieszczenie wektora przerwań. W trybie chronionym procesor rezerwuje pierwsze 32 przerywania do własnych celów, dlatego pierwsze przerywanie sprzętowe w idt ma wartość 32 DelayLoop(100); //Opóźnienie outb(0x21,4); //Wysłanie ICW3 DelayLoop(100); //Opóźnienie outb(0x21,1); //Wysłanie ICW4 /*Układ slave: */ outb(0x0A0,0x11); //Wysłanie ICW1 DelayLoop(100); outb(0x0A1,0x28); //Wysłanie bajtu ICW2 do układu slave, ten bajt to przemieszczenie wektora przerwań. DelayLoop(100); outb(0x0A1,2); //Wysłanie ICW3 DelayLoop(100); //Opóźnienie outb(0x0A1,1); //Wysłanie ICW4 DelayLoop(100); /*Ponowne zamaskowanie przerwań */ DelayLoop(100); //Opóźnienie outb(0x21,0xFF); DelayLoop(100); //Opóźnienie outb(0x0A1,0xFF); ReturnCallStack } void EnableIRQ(uchar IRQ,uchar PIC) { /* procedura włącza podane przerywanie sprżetowe w kontrolerze przerwań. Parametry: IRQ numer przerywania sprzętowego,PIC - 0 układ master 1 -układ slave */ u16int Port; uchar OCW1,temp; if (PIC == 0) {Port = 0x21; } else { Port = 0xA1;} if (IRQ == 0) { OCW1 = 1; } else { OCW1 = 1 << IRQ; } temp = inb(Port); DelayLoop(1); OCW1= temp ^ OCW1; outb(Port,OCW1); } void DisableIRQ(uchar IRQ,uchar PIC) { /* procedura wyłącza podane przerywanie sprżetowe w kontrolerze przerwań. Parametry: IRQ numer przerywania sprzętowego,PIC - 0 układ master 1 -układ slave */ u16int Port; uchar OCW1,temp; if (PIC == 0) {Port = 0x21; } else { Port = 0xA1;} if (IRQ == 0) { OCW1 = 1; } else { OCW1 = 1 << IRQ; } temp = inb(Port); DelayLoop(1); OCW1= temp | OCW1; outb(Port,OCW1); } /*Ekran:*/ uchar TextColor=7; //Kolor aktualnie wyświetlanego tekstu przez kprintf. Poprzednie teksty nie są zmieniane. uchar CurX = 0; /*Pozycja kursora na ekranie */ uchar CurY = 0; void kputc(uchar c) { /* Wstawia znak o odpowiednim kolorze w pozycję kursora i przesuwa kursor. Działa w trybie chronionym.PARAMETRY: c - znak; color - kolor znaku */ u16int temp; SetCallStack(7); if (CurX >79) { CurX = 0; CurY++; if (CurY > 24) CurY = 0; } temp = (80*CurY+CurX)*2; asm( "pushw %%es\n" "movw $0x20,%%ax\n" "movw %%ax,%%es\n" //"movw $[cont],%%si\n" "movb %[chr],%%es:(%%si)\n" //"movb $66,%%es:(0)\n" "inc %%si\n" "movb TextColor,%%al\n" "movb %%al,%%es:(%%si)\n" "popw %%es\n" : : [cont] "S"(temp), [chr] "r"(c) : "%ax" ); CurX++; ReturnCallStack } void kprintf(uchar text[],...) {/* Standardowa procedura printf z biblioteki stdio.Działa zarówno w trybie rzeczywistym jak i chronionym */ uchar IntToStr(u32int value,uchar str[]) { //Funkcja konwertuje integer ze znakiem lub bez na string.Obcina początkowe zera PARAMETRY: value - wartość do przekonwertowania; sign - 0 bez znaku 1 ze znakiem ZWRACANE: Długość liczby; w *str napis z liczbą. uchar temp; u32int temp2=1000000000; u32int value2=value; uchar len=0; uchar c; uchar z=0; // Jeżeli z=0 znaczy że podczas konwersjii nie wystąpiła jeszcze cyfra >0 , a zera są obcinane. for (temp=0; temp <=9; temp++) { c=(value2 / temp2); value2= value2 % temp2; if (c > 0 | z == 1) { z=1; str[len]=c+48; len++; } temp2=temp2 /10; } if (z == 0) { str[0]='0'; return 1; } else return len; } uchar IntToHex(u32int value,uchar Hex[]) { //Funkcja konwertuje integer na hex. Nie dodaje 0x i obcina początkowe 0.PARAMETRY: value - wartość do przekonwertowania. ZWRACANE: Długość liczby; w hex liczba w systemie szesnastkowym uchar temp; u32int temp2=0x10000000; u32int value2=value; uchar len=0; uchar c; uchar z=0; // Jeżeli z=0 znaczy że podczas konwersjii nie wystąpiła jeszcze cyfra >0 , a zera są obcinane. for (temp=0; temp <=7; temp++) { c=(value2 / temp2); value2= value2 % temp2; if (c > 0 | z == 1) { z=1; switch (c) { case 10: Hex[len]='A'; break; case 11: Hex[len]='B'; break; case 12: Hex[len]='C'; break; case 13: Hex[len]='D'; break; case 14: Hex[len]='E'; break; case 15: Hex[len]='F'; break; default: Hex[len]=c+48; break; } len++; } temp2=temp2 /16; } if (z == 0) { Hex[0]='0'; return 1; } else return len; } va_list parg; u16int temp,temp2; uchar ArgStr[11]; uchar *ArgStrP; uchar strlen; uchar paramscount=0; u32int ArgInt; va_start(parg,text); SetCallStack(6) temp=0; temp2=0; strlen=0; ArgInt = 0; for (temp=0;text[temp] != '\0' & temp <= 65535;temp++) { switch (text[temp]) { case '\n': SetCurPos(0,CurY+1); break; case '\r': SetCurPos(0,CurY); break; default: if (text[temp] == '%') { switch (text[temp+1]) { case 'x': ArgInt = va_arg( parg,u32int); strlen = IntToHex(ArgInt,ArgStr); kputc('0'); kputc('x'); for (temp2=0;temp2 < strlen;temp2++) { kputc(ArgStr[temp2]); } break; case 'u': ArgInt = va_arg( parg,u32int); strlen=IntToStr(ArgInt,ArgStr); for (temp2=0;temp2 < strlen;temp2++) { kputc(ArgStr[temp2]); } break; case 'c': ArgStrP = va_arg( parg,uchar*); for (temp2=0;ArgStrP[temp2] != '\0';temp2++) kputc(ArgStrP[temp2]); break; default: kputc('%'); kputc(text[temp+1]); break; } temp++; } else { kputc(text[temp]); } break; } } va_end(parg); ReturnCallStack } void SetCurPos(uchar x,uchar y) { //Procedura ustawia pozycję kursora. PARAMETRY : x,y - pozycja kursora, X musi być <= 79 a Y <= 24, w przeciwnym wypadku procedura ustawia X badź Y na 0. if (x > 80) x = 0; if (y > 25) y = 0; CurX = x; CurY = y; } void kprintFAILED() { /* Procedura wyświetla czerwony migający tekst:[FAILED] na końcu linii. */ uchar OldCol; OldCol = TextColor; TextColor = 4 | 128; SetCurPos(71,CurY); kprintf("[FAILED]\n"); TextColor = OldCol; } void kprintOK() { /* Procedura wyświetla zielony tekst:[OK] na końcu linii. */ uchar OldCol; OldCol = TextColor; TextColor = 2; SetCurPos(76,CurY); kprintf("[OK]\n"); TextColor = OldCol; } void ClearScreen() { /*Procedura czyści ekran */ u16int temp; SetCurPos(0,0); for (temp = 0; temp <= 1896; temp++) kputc(' '); SetCurPos(0,0); } <file_sep>/******************************************************************************************************************************** * tasks.c * * Wersja: pre-alpha * * e-mail:<EMAIL> * * 2014 * ******************************************************************************************************************************** Plik zawiera niezbędne procedury i funkcje służące podstawowej obsłudze wątków i procesów, oraz zawiera planistę. Samo jądro nie obsługuje żadnego formatu plików wykonywalnych, wczytanie pliku wykonywalnego do pamięci leży w gestii innych części systemu. */ #include "data.h" u32int AddToProcessList(u32int EntryPoint,uchar PrvLevel,u32int EFLAGS,u16int SS0,u16int SS1,u16int SS2,u16int SS,u32int ESP0,u32int ESP1,u32int ESP2,u32int ESP,u16int IOMAP,u32int PDBR,u32int MaxTicks) /*Funkcja tworzy wpis w tablicy procesów.Utworzony proces ma status 2 Parametry: EntryPoint - punkt wejścia PrvLevel - poziom uprzywilejowania, 0,1,2,3 EFLAGS - rejestr FLAG SS0 - selektor segmentu stosu, gdy program przechodzi na 0 poziom uprzywilejowania (np. wystąpienie przerwania, bądź wywołanie funkcji systemowej, furtki, itp) SS1 - selektor segmentu stosu, gdy program przechodzi na 1 poziom uprzywilejowania (np. wystąpienie przerwania, bądź wywołanie funkcji systemowej, furtki, itp) SS2 - selektor segmentu stosu, gdy program przechodzi na 2 poziom uprzywilejowania (np. wystąpienie przerwania, bądź wywołanie funkcji systemowej, furtki, itp) SS - selektor segmentu stosu, gdy program pracuje na swoim domyślnym poziomie uprzywilejowania (zadeklarowanym w parametrze PrvLevel) ESP0 - zawartość rejestru ESP, gdy program przechodzi na 0 poziom uprzywilejowania (np. wystąpienie przerwania, bądź wywołanie funkcji systemowej, furtki, itp) ESP1 - zawartość rejestru ESP, gdy program przechodzi na 1 poziom uprzywilejowania (np. wystąpienie przerwania, bądź wywołanie funkcji systemowej, furtki, itp) ESP2 - zawartość rejestru ESP, gdy program przechodzi na 2 poziom uprzywilejowania (np. wystąpienie przerwania, bądź wywołanie funkcji systemowej, furtki, itp) ESP - zawartość rejestru ESP, gdy program pracuje na swoim domyślnym poziomie uprzywilejowania (zadeklarowanym w parametrze PrvLevel) IOMAP - adres tablicy zezwoleń we/wy (narazie nie wykorzystywane) PDBR - wartość rejestru CR3, adres katalogu stron (aktualnie stronnicowanie nie jest wykorzystywane) MaxTicks - ilość tyknięć zegara systemowego przeznaczonego dla zadania, ilość czasu CPU Zwracane: PID procesu( tymczasowo nic nie jest zwracane */ { struct TSSSeg *temp; u32int temp2; TasksN++; Tasks[TasksN].State=1; Tasks[TasksN].PrvLevel = PrvLevel; switch (PrvLevel) { case 0: Tasks[TasksN].TSS.CS = KernelCS ; Tasks[TasksN].CodeSegment = KernelCS; break; case 1: Tasks[TasksN].TSS.CS = Prv1CS ; Tasks[TasksN].CodeSegment = Prv1CS; break; case 2: Tasks[TasksN].TSS.CS = Prv2CS ; Tasks[TasksN].CodeSegment = Prv2CS; break; case 3: Tasks[TasksN].TSS.CS = Prv3CS; Tasks[TasksN].CodeSegment = Prv3CS; break; } Tasks[TasksN].DataSegment = Prv3DS; Tasks[TasksN].StackSegment = SS; Tasks[TasksN].EntryPoint = EntryPoint; Tasks[TasksN].PDBR = PDBR; Tasks[TasksN].TickCount = 0; Tasks[TasksN].MaxTick = MaxTicks; Tasks[TasksN-1].TSSNext = &Tasks[TasksN].TSS; Tasks[TasksN-1].Next = TasksN; Tasks[TasksN].Next = 1; Tasks[TasksN].TSSNext = &Tasks[1].TSS; Tasks[TasksN].TSS.Back = 0; Tasks[TasksN].TSS.ESP0 = ESP0; Tasks[TasksN].TSS.ESP1 = ESP1; Tasks[TasksN].TSS.ESP2 = ESP2; Tasks[TasksN].TSS.ESP = ESP; Tasks[TasksN].TSS.EAX = 0; Tasks[TasksN].TSS.EBX = 0; Tasks[TasksN].TSS.ECX = 0; Tasks[TasksN].TSS.EDX = 0; Tasks[TasksN].TSS.EBP = 0; Tasks[TasksN].TSS.ESI = 0; Tasks[TasksN].TSS.EDI = 0; Tasks[TasksN].TSS.EFLAGS = EFLAGS; Tasks[TasksN].TSS.ES = Prv3DS; Tasks[TasksN].TSS.DS = Prv3DS; Tasks[TasksN].TSS.FS = Prv3DS; Tasks[TasksN].TSS.GS = Prv3DS; Tasks[TasksN].TSS.SS0 = SS0; Tasks[TasksN].TSS.SS1 = SS1; Tasks[TasksN].TSS.SS2 = SS2; Tasks[TasksN].TSS.SS = SS; Tasks[TasksN].TSS.LDT = 0; Tasks[TasksN].TSS.TRAP = 0; Tasks[TasksN].TSS.IOMAP = IOMAP; Tasks[TasksN].TSS.CR3 = PDBR; Tasks[TasksN].TSS.EIP = EntryPoint; return 0; } void SetClockFrequency() /* Procedura ustawia częsotliwość generatora nr 0 zegara czasu rzeczywistego, czyli tego który wyzwala IRQ 0 i jest podstawą przełączania zadań oraz odmierzania czasu rzeczywistego. Częstotliwość zapisana jest w stałej ClockFrequency */ { #define DelayConst 1000 uchar LSB; uchar MSB; u16int temp; asm("cli"); temp = 1193180 / ClockFrequency; //Wyliczenie współczynnika podziału LSB = temp & 0xFF; //Wyliczenie mniej znaczącego bajtu licznika MSB = (temp & 0xFF00) >> 8; //Wyliczenie bardziej znaczącego bajtu licznika outb(0x43,0x34); // Rozkaz programowania układu 8254, Generator 0 ,rozkaz zapisu mniej znaczącego bajtu licznika (LSB), tryb pracy 2 DelayLoop(DelayConst); outb(0x40,LSB); // Wysłanie mniej znaczącego bajtu DelayLoop(DelayConst); /*outb(0x43,0x24); // Rozkaz programowania układu 8254, Generator 0 ,rozkaz zapisu bardziej znaczącego bajtu licznika (MSB), tryb pracy 2 DelayLoop(DelayConst);*/ outb(0x40,MSB); // Wysłanie bardziej znaczącego bajtu DelayLoop(DelayConst); /*outb(0x43,0x4); */ } uchar CallToTask(u32int TaskN) /* Funkcja dokonuje przeskoku do zadania podanego w parametrze TaskN. Następuje przełączenie zadania podobnbe do tego, jakie następuje w procedurze SystemClock. Procesor podejmie wykonanie od pierwszej instrukji procesu ZWRACANE: 0 - OK 1 - Numer zadania podany w TaskN jest większy niż ilość wszystkich zadań (TasksN) */ { struct TSSSeg *temp; u16int temp2; if (TaskN > TasksN) { return 1; } else { } return 0; } void SystemClock() /* Procedura zegara systemowego, jest wektorem IRQ 0. Obsługuje zegar czasu rzeczywistego oraz wywołuje planistę krótkoterminowego Przełączanie będzie odbywać się z pominięciem sprzętowego mechanizmu TSS, za pomocą operacji stosowych pusha, popa, push i pop, oraz z wykorzystaniem dalekiego powrotu z przerywania. Ze względu na optymalizację, większość kodu tej procedury zostanie zapisana w Assemblerze. */ { //BOCHSDBG asm("cli\n" "movl %esp,SystemClockESP\n" //Zachowanie rejestru ESP w zmiennej tymczasowej "movw %ss,%sp\n" //TYMCZASOWO!!!:Zmiana selektora segmentu stosu na selektor stosu jądra "movw %sp,SystemClockSS\n" "movw $0x18,%sp\n" "movw %sp,%ss\n" "movl ActTaskTSS,%esp\n" "addl $72,%esp\n" //W ESP, adres w TSS gdzie za pomocą pusha zachowamy rejestry ogólnego przeznaczenia "pusha \n" //Zachowanie rejestów ogólnego przeznaczenia "movw SystemClockSS,%sp\n" //TYMCZASOWO!!!: Odtworzenie selektora segmentu stosu "movw %sp,%ss\n" "movl SystemClockESP,%esp\n" //Odtworzenie ESP "movl ActTaskTSS,%eax\n" "cmpb $0,ActTaskPrvLevel\n" // Jeżeli poziom uprzywilejowania przerywanego wątku jest taki sam jak tej procedury, ESP przerwanego wątku nie jest pobierany ze stosu, a trzeba go wyliczyć ręcznie "jne SystemClockSaveStateGetESPFromStack\n" "movl %esp,%ebx\n" /* W NAWIASIE WARTOŚCI PRAWIDŁOWE, PO USUNIĘCIU EditGDTEntry */ "addl $24,%ebx\n" //W EBX ESP przerwanego wątku (16) "jmp SystemClockSaveStateNext\n" "SystemClockSaveStateGetESPFromStack:\n" "movl 24(%esp),%ebx\n" //W EBX esp przerwanego wątku (16) "SystemClockSaveStateNext:\n" "movl %ebx,84(%eax)\n" // Zapisanie w TSS ESP przerwanego programu "movl 8(%esp),%ebx\n" // W EBX EBP programu (0) "movl %ebx,48(%eax)\n" //Zachowanie EBP w TSS "movl 12(%esp),%ebx\n" //W EBX EIP przerwanego wątku (4) "movl %ebx,72(%eax)\n" //Zachowanie EIP w TSS ); ActTaskTSS = Tasks[ActTaskN].TSSNext; ActTaskN = Tasks[ActTaskN].Next; ActTaskPrvLevel = Tasks[ActTaskN].PrvLevel; /*TYMCZASOWO: */ EditGDTEntry(5,sizeof(Tasks[ActTaskN].TSS),(u32int) &Tasks[ActTaskN].TSS,1,0,0,1,0,0,1,0,1,0); asm("movw $0x28,%ax\n" "ltr %ax\n"); /*Odtworzenie stanu następnego zadania */ asm("movw %ss,%sp\n" //TYMCZASOWO!!!:Zmiana selektora segmentu stosu na selektor stosu jądra "movw %sp,SystemClockSS\n" "movw $0x18,%sp\n" "movw %sp,%ss\n" "movl ActTaskTSS,%esp\n" "addl $40,%esp\n" //Przygotowanie ESP do przywrócenia rejestów ogólnego przeznaczenia "popa\n" //Przywrócenie zawartości rejestrów ogólnego przeznaczenia "cmpb $0,ActTaskPrvLevel\n" /* W zależności od poziomu uprzywilejowania wznawianego procesu, wybór metody przywrócenia rejestrów EIP,CS,EFLAGS,ESP,SS i skoku. Jak poziom uprzywilejowania jest różny od 0, procedura jest dużo prostrza, sprowadza się do wykonania rozkazu iret. A jak poziom uorzywilejowania wynosi 0, proces ten jest bardziej skomplikowany */ "je SystemClockRestoreStateWithoutChangePrvLevel\n" "movl %eax,SystemClockEAX\n" "movb $0x20,%al\n" "outb %al,$0x20\n" //EOI "movl SystemClockEAX,%eax\n" "iret\n" //Powrót z przerywania. Skok do zadania ze zmianą poziomu uprzywilejowania "SystemClockRestoreStateWithoutChangePrvLevel:\n" // Skok do zadania bez zmiany poziomu uprzywilejowania "movl %eax,SystemClockEAX\n" "addl $8,%esp\n" //Dodanie 8 do ESP powoduje, że ESP teraz wskazuje na EFLAGS odtwarzanego programu "popfl\n" //Wpisanie do rejestru EFLAGS przerwanego programu "movl -12(%esp),%eax\n" //Pobranie adresu do skoku "movl 4(%esp),%eax\n" //W EAX SS odtwarzanego zadania "popl %esp\n" // Odtworzenie %ESP "movl %eax,%ss\n" //Odtworzenie %SS "movb $0x20,%al\n" "outb %al,$0x20\n" //EOI "movl SystemClockEAX,%eax\n" "jmp *-12(%esp)\n"); //I Skok } <file_sep>/* *********************************************************************************************************** * init.c * * Wersja:pre-alpha * * e-mail:<EMAIL> * * 2014 * *********************************************************************************************************** Pierwszy i najważniejszy proces w systemie. Plik ten jest uruchamiany zanim zostanie uruchomione jądro,przechodzi do trybu chronionego, i uruchamia cały sdystem. rvl;kjrkjgtvjkrhtvbikrhtgbviuhriub */ #include "./include/data.h" void EnablePaging() { /* Procedura włącza stronicowanie */ u32int temp2; u32int temp3; KernelPDEA.P = 1; KernelPDEA.RW = 0; KernelPDEA.US = 0; KernelPDEA.PWT = 0; KernelPDEA.PCD = 0; KernelPDEA.A = 0; KernelPDEA.Zero = 0; KernelPDEA.PageSize = 0; KernelPDEA.G = 0; KernelPDEA.AVL = 0; KernelPTEA.P = 1; KernelPTEA.RW = 0; KernelPTEA.US = 1; KernelPTEA.PWT = 0; KernelPTEA.PCD = 0; KernelPTEA.A = 0; KernelPTEA.Zero = 0; KernelPTEA.D = 0; KernelPTEA.G = 0; KernelPTEA.AVL = 0; AllocPsyhicalMemory(&KernelPDE,&KernelPTEs,0,0, KernelSpaceEndAddress ,&KernelPDEA,&KernelPTEA); BOCHSDBG asm( "cli\n" "movl %[KernelPDEOffset],%%eax\n" "movl %%eax,%%cr3\n" "movl %%cr0,%%eax\n" "or $0x80000000,%%eax\n" // Ustawienie bitu odpowiedzialnego za stronicowanie "movl %%eax,%%cr0\n" // i start... "ljmp $0x8,$AfterEnablePaging\n" "AfterEnablePaging:\n" "movl $0,%%eax\n" :: [KernelPDEOffset] "r" (&KernelPDE) :"%eax"); } void Log2Phy(s,o,AddrH,AddrL) u16int s,o; u16int *AddrH;u16int *AddrL; { /* Procedura konwertuj¹ca adres logiczny na 20 bitowy adres fizyczny, wed³ug wzoru Ap=16*S+Ofs PARAMETRY: s- segment o- offset ZWRACANE: AddrH- starsze 16 bitów adresu fizycznego AddrL - m³odsze 16 bitów adresu fizycznego */ u16int t1; SetCallStack(4) t1=s; t1=t1 >> 12; /*Przemieszczenie bitowe o 12 bitów w prawo, teraz 4 najstarsze bity to 4 najm³odsze bity */ *AddrH=t1; t1=s; t1=t1 << 4; /*Przemieszczenie bitowe o 4 bity w prawo, a 4 najmo³odsze bity zostaj¹ wyzerowane */ *AddrL=t1+o; ReturnCallStack } void CreateGDTIDT() { //Procedura tworzy tablice GDT i IDT, i wczytuje je za pomocą instrukcjii lgdt i lidt, tworzy w GDT desktyptory jądra. //Numer funkcji: 3 u32int temp; SetCallStack(3) //Stworzenie pustego deskryptora. tzw Null Deskryptora EditGDTEntry(0,0,0,0,0,0,0,0,0,0,0,0,0); //Stworzenie segmentu kodu dla jądra, będzie on zajmować całą przestrzeń adresową 4 GB EditGDTEntry(1,0xFFFFF,0,0,1,0,1,1,0,1,0,1,1); //Stworzenie segmentu danych dla całego systemu, będzie on zajmować całą przestrzeń adresową 4 GB i posiadać poziom uprzywilejowania 3 EditGDTEntry(2,0xFFFFF,0,0,1,0,0,1,3,1,0,1,1); //Stworzenie segmentu stosu dla jądra EditGDTEntry(3,0xFFFFF,0,0,1,0,0,1,0,1,0,1,1); //Tymczasowo tworzenie segmentu ekranu dostęonego z każdego poziomu uprzywilejowania EditGDTEntry(4,4000,0xB8000,0,1,0,0,1, 3 ,1,0,1,0); //Segment stanu TSS EditGDTEntry(5,sizeof(KernelTSS),(u32int) &KernelTSS,1,0,0,1,0,0,1,0,1,0); EditGDTEntry(6,0xFFFFF,0,0,1,1,1,1, 1 ,1,0,1,1); //Segment kodu dla procesów pracujących z poziomem uprzywilejowania 1 EditGDTEntry(7,0xFFFFF,0,0,1,1,1,1, 2 ,1,0,1,1); //Segment kodu dla procesów pracujących z poziomem uprzywilejowania 2 EditGDTEntry(8,0xFFFFF,0,0,1,1,1,1, 3 ,1,0,1,1); //Segment kodu dla procesów pracujących z poziomem uprzywilejowania 3 GDTC=10; //Stworzenie deskryptorów tablic GDT i LDT GDTDescr.Size = GDTSMAX*8-1; IDTDescr.Size = IDTSMAX*8-1; /*Log2Phy(KernelSegment,&GDTS[0],&GDTDescr.AddrH,&GDTDescr.AddrL); Log2Phy(KernelSegment,&IDTS[0],&IDTDescr.AddrH,&IDTDescr.AddrL); */ temp = (u32int) &GDTS[0]; temp = temp & 0xFFFF0000; temp = temp >> 16; GDTDescr.AddrH = temp; temp = (u32int) &GDTS[0]; temp = temp & 0x0000FFFF; GDTDescr.AddrL = temp; temp = (u32int) &IDTS[0]; temp = temp & 0xFFFF0000; temp = temp >> 16; IDTDescr.AddrH = temp; temp = (u32int) &IDTS[0]; temp = temp & 0x0000FFFF; IDTDescr.AddrL = temp; asm("lgdt GDTDescr\n"); asm("lidt IDTDescr\n"); ReturnCallStack } u16int temp; u32int temp2; void InitKernel() { /* Procedura tworzy podstawowe struktury systemowe (GDT,IDT,...) uruchamia bramkę A20, uruchamia tryb chroniony,wczytuje jądro pod podany adres. Numer funkcji: 2 */ SetCallStack(2) /*asm("pushw %ds\n" "popw KernelSegment\n" "pushw %ds\n" "popw KernelSegmentInRM\n" );*/ //SetA20State(1); temp=0; CreateGDTIDT(); BOCHSDBG asm("ljmp $0x8,$InitKernelSetRegs\n" "InitKernelSetRegs:\n" "movl $0,%eax\n" "movl %eax,%cr2\n" "movl %eax,%cr3\n" "movl %eax,%cr4\n" "movw $0x13,%ax\n" "movw %ax,%ds\n" "movw %ax,%es\n" "movw %ax,%gs\n" "movw %ax,%fs\n" "movw $0x18,%ax\n" "movw %ax,%ss\n"); KernelBase=KernelCS*0x10; /*Wypełnienie tablicy IDT wektorem do pustej procedury przerywania */ for (temp=32;temp <= 255;temp++) { temp2 = (u32int) & EmptyInterrupt; IDTS[temp].Offset1 = temp2 & 0xFFFF; IDTS[temp].Selector = 0x8; IDTS[temp].Zero = 0; IDTS[temp].W = 0; IDTS[temp].MB3 = 3; IDTS[temp].D = 1; IDTS[temp].Zero2 = 0; IDTS[temp].DPL = 0; IDTS[temp].P = 1; temp2 = temp2 & 0xFFFF0000; IDTS[temp].Offset2 = temp2 >> 16 ; } FramesN = 8192; //Tymczasowa ilość ramek EnablePaging(); InitMain(); } /*TYMCZASOWO!!!!: */ #include "./include/temp.c" void InitMain() { /* Główna procedura procesu init. Początkowo uruchamia cały system */ struct _PDE *temp; ClearScreen(); kprintf("GRUB"); kprintOK(); SetExceptions(); //Ustawienie przerywań wyjątków kprintf("Set vectors of internal exceptions"); kprintOK(); PICInitInPM(); kprintf("PIC registers set to protected mode"); kprintOK(); kprintf("Enable paging"); kprintOK(); kprintOK(); BOCHSDBG BOCHSDBGprintf("Clock \nTest\n"); DisablePaging Tasks[0].PDBR=SetClosestFreeFrameBit(); Tasks[0].PDEsN = 1; Tasks[0].PTEsN = 1; temp = Tasks[0].PDBR; temp -> Base = SetClosestFreeFrameBit() >> 12; PagingEnable AllocMemoryWithAttribs(0,4096,KernelPDEA,KernelPTEA); //Clock(); /*asm( "pushl $0\n" "popfl\n" "movl 30485760,%eax\n" "movw $0xABCD,%cx\n" "movw $0,%ax\n" "div %ax\n"); */ asm("cli\n" "hlt\n"); for (;;) { } //HALT } <file_sep> /* *********************************************************************************************************** * temp.c * * Wersja:pre-alpha * * e-mail:<EMAIL> * * 2014 * *********************************************************************************************************** Plik tymczasowo dołączany do jądra zawierający różne tymczasowe rzeczy, przeznaczony do testowania. Docelowo nie będzie wchodził w skład jądra. */ #include <stdarg.h> asm(".code32"); uchar NextTask=0; uchar temp10=1; struct TSSSeg TaskTSS; struct TSSSeg TaskTSS0; struct TSSSeg TaskTSS1; struct TSSSeg TaskTSS2; volatile uchar StackTask0[0xFFFF]; volatile uchar StackTask1[0xFFFF]; volatile uchar StackTask1SS0[0xFFFF]; volatile uchar StackTask2[0xFFFF]; volatile uchar StackTask2SS0[0xFFFF]; volatile uchar StackTask3[0xFFFF]; volatile uchar StackTask3SS0[0xFFFF]; u32int tempx; //uchar CurX=0,CurY=0; //Pozycja kursora, jeżeli procesor pracuje w trybie chronionym void KeybIRQ() { BOCHSDBG asm("cli\n"); TextColor=2; SetCurPos(0,7); //kprintf("KLAWISZ :):):)\n"); TextColor=7; asm("pushw %ax\n" "movb $0x20,%al\n" "outb %al,$0x20\n" //EOI "popw %ax\n" "leave\n" "iret\n"); } void Task1() { //asm("movw $0x10,%ax\n"); //asm("movw %ax,%ds\n"); BOCHSDBG for (;;) { for (;;) { // SetCurPos(0,0); kprintf("Teraz dziala zadanie nr 1"); } } //printf("eflags:\n\r"); asm("iret \n"); } void Task2() { //asm("movw $0x10,%ax\n"); //asm("movw %ax,%ds\n"); //BOCHSDBG SetCurPos(0,0); for (;;) { for (;;) { // SetCurPos(0,0); kprintf("Teraz dziala zadanie nr 2"); } } //printf("eflags:\n\r"); asm("iret \n"); } void Task3() { //asm("movw $0x10,%ax\n"); //asm("movw %ax,%ds\n"); //BOCHSDBG SetCurPos(0,0); for (;;) { for (;;) { // SetCurPos(0,0); kprintf("Teraz dziala zadanie nr 3"); } } //printf("eflags:\n\r"); asm("iret \n"); } void Task4() { //asm("movw $0x10,%ax\n"); //asm("movw %ax,%ds\n"); //BOCHSDBG SetCurPos(0,0); for (;;) { for (;;) { // SetCurPos(0,0); kprintf("Teraz dziala zadanie nr 4"); } } //printf("eflags:\n\r"); asm("iret \n"); } void Task5() { //asm("movw $0x10,%ax\n"); //asm("movw %ax,%ds\n"); //BOCHSDBG SetCurPos(0,0); for (;;) { for (;;) { // SetCurPos(0,0); kprintf("Teraz dziala zadanie nr 5"); } } //printf("eflags:\n\r"); asm("iret \n"); } void Task6() { //asm("movw $0x10,%ax\n"); //asm("movw %ax,%ds\n"); //BOCHSDBG SetCurPos(0,0); for (;;) { for (;;) { // SetCurPos(0,0); kprintf("Teraz dziala zadanie nr 6"); } } //printf("eflags:\n\r"); asm("iret \n"); } void Task7() { //asm("movw $0x10,%ax\n"); //asm("movw %ax,%ds\n"); //BOCHSDBG SetCurPos(0,0); for (;;) { for (;;) { // SetCurPos(0,0); kprintf("Teraz dziala zadanie nr 7"); } } //printf("eflags:\n\r"); asm("iret \n"); } void Task8() { //asm("movw $0x10,%ax\n"); //asm("movw %ax,%ds\n"); //BOCHSDBG SetCurPos(0,0); for (;;) { for (;;) { // SetCurPos(0,0); kprintf("Teraz dziala zadanie nr 8"); } } //printf("eflags:\n\r"); asm("iret \n"); } void Task9() { //asm("movw $0x10,%ax\n"); //asm("movw %ax,%ds\n"); //BOCHSDBG SetCurPos(0,0); for (;;) { for (;;) { // SetCurPos(0,0); kprintf("Teraz dziala zadanie nr 9"); } } //printf("eflags:\n\r"); asm("iret \n"); } void Task10() { //asm("movw $0x10,%ax\n"); //asm("movw %ax,%ds\n"); //BOCHSDBG SetCurPos(0,0); for (;;) { for (;;) { // SetCurPos(0,0); kprintf("Teraz dziala zadanie nr 10"); } } //printf("eflags:\n\r"); asm("iret \n"); } void Clock() { u32int temp2; TasksN=0; ActTaskN = 1; GDTC=20; ActTaskTSS = &Tasks[1].TSS; //Zadanie nr 1, poziom uprzywilejowania:0: EditGDTEntry(9,0xFFFF,(u32int) &StackTask1,0,1,0,0,1,0,1,0,1,0); //Stos zadania nr 1 AddToProcessList((u32int) &Task1,0,0x200,0x48,0,0,0x48,0xFFFF,0xFFFF,0xFFFF,0xFFFF,0,0,0); //Zadanie nr 2, poziom uprzywilejowania:3: EditGDTEntry(10,0xFFFF,(u32int) &StackTask2,0,1,0,0,1, 3 ,1,0,1,0); //Stos zadania nr 2 EditGDTEntry(11,0xFFFF,(u32int) &StackTask2SS0,0,1,0,0,1, 0 ,1,0,1,0); //Stos zadania nr 2 SS0 AddToProcessList((u32int) &Task2,3,0x200,0x58, 0 , 0 ,0x53,0xFFFF,0xFFFF,0xFFFF,0xFFFF,0,0,0); //Zadanie nr 3, poziom uprzywilejowania:2: EditGDTEntry(12,0xFFFF,(u32int) &StackTask3,0,1,0,0,1, 2 ,1,0,1,0); //Stos zadania nr 3 EditGDTEntry(13,0xFFFF,(u32int) &StackTask3SS0,0,1,0,0,1, 0 ,1,0,1,0); //Stos zadania nr 3 SS0 AddToProcessList((u32int) &Task3,2,0x200,0x68, 0 , 0x62 ,0x62,0xFFFF,0xFFFF,0xFFFF,0xFFFF,0,0,0); EditGDTEntry(5,sizeof(Tasks[1].TSS),(u32int) &Tasks[1].TSS,1,0,0,1,0,0,1,0,1,0); asm("movw $0x28,%ax\n" "ltr %ax\n" //"ljmp $0x30,$0\n" ); temp2 = (u32int) & SystemClock; IDTS[0x20].Offset1 = temp2& 0xFFFF; IDTS[0x20].Selector = 0x8; IDTS[0x20].Zero = 0; IDTS[0x20].W = 0; IDTS[0x20].MB3 = 3; IDTS[0x20].D = 1; IDTS[0x20].Zero2 = 0; IDTS[0x20].DPL = 0; IDTS[0x20].P = 1; IDTS[0x20].Offset2 = (temp2 & 0xFFFF0000) >> 16; SetClockFrequency(); EnableIRQ(0,0); temp2 = (u32int) & KeybIRQ; IDTS[0x21].Offset1 = temp2& 0xFFFF; IDTS[0x21].Selector = 0x8; IDTS[0x21].Zero = 0; IDTS[0x21].W = 0; IDTS[0x21].MB3 = 3; IDTS[0x21].D = 1; IDTS[0x21].Zero2 = 0; IDTS[0x21].DPL = 0; IDTS[0x21].P = 1; IDTS[0x21].Offset2 = (temp2 & 0xFFFF0000) >> 16; EnableIRQ(1,0); BOCHSDBGprintf("xxxcccc\n"); BOCHSDBG asm("movl $0xFFFF,%esp\n" "movw $0x48,%ax\n" "movw %ax,%ss\n" "sti\n"); //CallToTask(1); for (;;) { Task1(); } } u32int tempxxx; u32int tempxxx2; void putc(uchar c) { /* Wstawia znak w pozycję kursora i przesuwa kursor. Działa w trybie rzeczywistym i chronionym */ u16int temp; //SetCallStack(7); temp = (80*CurY+CurX)*2; BOCHSDBG asm( "movw $0x20,%%ax\n" "movw %%ax,%%es\n" //"movw $[cont],%%si\n" "movb %[chr],%%es:(%%si)\n" //"movb $66,%%es:(0)\n" "inc %%si\n" "movb TextColor,%%al\n" "movb %%al,%%es:(%%si)\n" "inc %%si\n" : : [cont] "S"(temp), [chr] "r"(c) : "%ax" ); CurX++; if (CurX > 79) { CurX = 0; CurY++; if (CurY > 24) CurY = 0; } //ReturnCallStack } asm(".code32\n"); void printf(uchar text[],...) {/* Standardowa procedura printf z biblioteki stdio.Działa zarówno w trybie rzeczywistym jak i chronionym */ uchar IntToStr(u32int value,uchar str[]) { //Funkcja konwertuje integer ze znakiem lub bez na string.Obcina początkowe zera PARAMETRY: value - wartość do przekonwertowania; sign - 0 bez znaku 1 ze znakiem ZWRACANE: Długość liczby; w *str napis z liczbą. uchar temp; u32int temp2=1000000000; u32int value2=value; uchar len=0; uchar c; uchar z=0; // Jeżeli z=0 znaczy że podczas konwersjii nie wystąpiła jeszcze cyfra >0 , a zera są obcinane. for (temp=0; temp <=9; temp++) { c=(value2 / temp2); value2= value2 % temp2; if (c > 0 | z == 1) { z=1; str[len]=c+48; len++; } temp2=temp2 /10; } if (z == 0) { str[0]='0'; return 1; } else return len; } uchar IntToHex(u32int value,uchar Hex[]) { //Funkcja konwertuje integer na hex. Nie dodaje 0x i obcina początkowe 0.PARAMETRY: value - wartość do przekonwertowania. ZWRACANE: Długość liczby; w hex liczba w systemie szesnastkowym uchar temp; u32int temp2=0x10000000; u32int value2=value; uchar len=0; uchar c; uchar z=0; // Jeżeli z=0 znaczy że podczas konwersjii nie wystąpiła jeszcze cyfra >0 , a zera są obcinane. for (temp=0; temp <=7; temp++) { c=(value2 / temp2); value2= value2 % temp2; if (c > 0 | z == 1) { z=1; switch (c) { case 10: Hex[len]='A'; break; case 11: Hex[len]='B'; break; case 12: Hex[len]='C'; break; case 13: Hex[len]='D'; break; case 14: Hex[len]='E'; break; case 15: Hex[len]='F'; break; default: Hex[len]=c+48; break; } len++; } temp2=temp2 /16; } if (z == 0) { Hex[0]='0'; return 1; } else return len; } va_list parg; u16int temp,temp2; uchar ArgStr[11]; uchar *ArgStrP; uchar strlen; uchar paramscount=0; u32int ArgInt; va_start(parg,text); //SetCallStack(6) for (temp=0;text[temp] != '\0' & temp <= 65535;temp++) { switch (text[temp]) { case '\n': SetCurPos(CurX,CurY+1); break; case '\r': SetCurPos(0,CurY); break; default: if (text[temp] == '%') { switch (text[temp+1]) { case 'x': ArgInt = va_arg( parg,u32int); strlen = IntToHex(ArgInt,ArgStr); putc('0'); putc('x'); for (temp2=0;temp2 < strlen;temp2++) { putc(ArgStr[temp2]); } break; case 'u': ArgInt = va_arg( parg,u32int); strlen=IntToStr(ArgInt,ArgStr); for (temp2=0;temp2 < strlen;temp2++) { putc(ArgStr[temp2]); } break; case 'c': ArgStrP = va_arg( parg,uchar*); for (temp2=0;ArgStrP[temp2] != '\0';temp2++) putc(ArgStrP[temp2]); break; default: putc('%'); putc(text[temp+1]); break; } temp++; } else { putc(text[temp]); } break; } } va_end(parg); //ReturnCallStack }<file_sep>/* *************************************************************************************** * exceptions.c * * Wersja: pre-alpha * * e-mail:<EMAIL> * * 2014 * *************************************************************************************** Plik zawiera procedury obsługujące wyjątki i błedy występujące podczas pracy jądrą i aplikacjii użytkowych. Zawiera również tymczasowo procedurę krenel panic, która tak jak w linuxie wywoływana jest podczas wsytąpienia wyjątku w pracy jądra, wyświetlająca komunikat i szczegółowy stan systemu, wykonuje inne procedury sygnalizacyjne i zawiesza system. */ #include "data.h" void DivBy0Exception(u32int EIP,u32int CS,u32int EFLAGS,u32int ESP,u32int SS) { /*Procedura obsługi wyjątku, podane parametry są odkładane na stos automatycznie poprzez CPU. SS,ESP - parametr, których należy używać tylko w przypadku gdy, poziom uprzywilejowania odczytywany z parametru CS jest różny od 0, W przeciwnej możliwości ESP należy wyliczyć ręcznie. Obsługa błedu dzielenia przez 0. Numer przerywania:0 */ u32int TempESP; u32int TempEBP; u32int CR0; u32int CR2; u32int CR3; u32int CR4; u32int Nothing; struct _Regs Regs; BOCHSDBG asm("cli\n"); asm("subl $4,%ebp\n"); asm("movl %%esp,%[TempESP]\n" "leal 40%[Regs],%%esp\n" //W ESP adres w Regs gdzie zachowujemy rejestry ogólnego przeznacznenia "pusha \n" //Zachowanie rejestrów ogólnego przeznaczenia "movl %[TempESP],%%esp\n" //Przywrócenie ESP "movl 96(%%esp),%%esp\n" "movl %%esp,%[TempEBP]\n" //Zachowanie EBP programu który spowodował błąd "movl %[TempESP],%%esp\n" //Przywrócenie ESP : : [Regs] "m" (Regs), [TempESP] "m" (TempESP), [TempEBP] "m" (TempEBP) :); if (CS & 3 != 0) { Regs.SS = SS; Regs.ESP = ESP; } else { Regs.SS = KernelSS; asm("movl %%esp,%[TempESP]\n" "addl $128,%[TempESP]\n" : :[TempESP] "m" (TempESP) :); Regs.ESP = TempESP; } Regs.EFLAGS = EFLAGS; asm("movl %%cr0,%%eax\n" "movl %%eax,%[CR0]\n" "movl %%cr2,%%eax\n" "movl %%eax,%[CR2]\n" "movl %%cr3,%%eax\n" "movl %%eax,%[CR3]\n" "movl %%cr4,%%eax\n" "movl %%eax,%[CR4]\n" : : [CR0] "m" (CR0), [CR2] "m" (CR2), [CR3] "m" (CR3), [CR4] "m" (CR4) :"%eax"); Regs.CR0 = CR0; Regs.CR2 = CR2; Regs.CR3 = CR3; Regs.CR4 = CR4; Regs.CS = CS; Regs.EIP = EIP; Regs.DS = Prv3DS; Regs.ES = Prv3DS; Regs.GS = Prv3DS; Regs.FS = Prv3DS; Regs.ErrorCode = 0; KernelPanic(Regs,"Divide by 0"); HALT } void OffsetTooLargeException(u32int EIP,u32int CS,u32int EFLAGS,u32int ESP,u32int SS) {/* Ten wyjątek jest generowany, gdy podany offset przekracza granicę segmentu.Numer przerywania:5 */ u32int TempESP; u32int TempEBP; u32int CR0; u32int CR2; u32int CR3; u32int CR4; u32int Nothing; struct _Regs Regs; BOCHSDBG asm("cli\n"); asm("subl $4,%ebp\n"); asm("movl %%esp,%[TempESP]\n" "leal 40%[Regs],%%esp\n" //W ESP adres w Regs gdzie zachowujemy rejestry ogólnego przeznacznenia "pusha \n" //Zachowanie rejestrów ogólnego przeznaczenia "movl %[TempESP],%%esp\n" //Przywrócenie ESP "movl 96(%%esp),%%esp\n" "movl %%esp,%[TempEBP]\n" //Zachowanie EBP programu który spowodował błąd "movl %[TempESP],%%esp\n" //Przywrócenie ESP : : [Regs] "m" (Regs), [TempESP] "m" (TempESP), [TempEBP] "m" (TempEBP) :); if (CS & 3 != 0) { Regs.SS = SS; Regs.ESP = ESP; } else { Regs.SS = KernelSS; asm("movl %%esp,%[TempESP]\n" "addl $128,%[TempESP]\n" : :[TempESP] "m" (TempESP) :); Regs.ESP = TempESP; } Regs.EFLAGS = EFLAGS; asm("movl %%cr0,%%eax\n" "movl %%eax,%[CR0]\n" "movl %%cr2,%%eax\n" "movl %%eax,%[CR2]\n" "movl %%cr3,%%eax\n" "movl %%eax,%[CR3]\n" "movl %%cr4,%%eax\n" "movl %%eax,%[CR4]\n" : : [CR0] "m" (CR0), [CR2] "m" (CR2), [CR3] "m" (CR3), [CR4] "m" (CR4) :"%eax"); Regs.CR0 = CR0; Regs.CR2 = CR2; Regs.CR3 = CR3; Regs.CR4 = CR4; Regs.CS = CS; Regs.EIP = EIP; Regs.DS = Prv3DS; Regs.ES = Prv3DS; Regs.GS = Prv3DS; Regs.FS = Prv3DS; Regs.ErrorCode = 0; KernelPanic(Regs,"Offset to large exception"); HALT } void UnknowInstruction(u32int EIP,u32int CS,u32int EFLAGS,u32int ESP,u32int SS) { /*Wyjątek wysŧepuje gdy procesor podczas wykonywania kodu napotka na niedozwolony kod rozkazu.Numer przerywania:6 */ u32int TempESP; u32int TempEBP; u32int CR0; u32int CR2; u32int CR3; u32int CR4; u32int Nothing; struct _Regs Regs; BOCHSDBG asm("cli\n"); asm("subl $4,%ebp\n"); asm("movl %%esp,%[TempESP]\n" "leal 40%[Regs],%%esp\n" //W ESP adres w Regs gdzie zachowujemy rejestry ogólnego przeznacznenia "pusha \n" //Zachowanie rejestrów ogólnego przeznaczenia "movl %[TempESP],%%esp\n" //Przywrócenie ESP "movl 96(%%esp),%%esp\n" "movl %%esp,%[TempEBP]\n" //Zachowanie EBP programu który spowodował błąd "movl %[TempESP],%%esp\n" //Przywrócenie ESP : : [Regs] "m" (Regs), [TempESP] "m" (TempESP), [TempEBP] "m" (TempEBP) :); if (CS & 3 != 0) { Regs.SS = SS; Regs.ESP = ESP; } else { Regs.SS = KernelSS; asm("movl %%esp,%[TempESP]\n" "addl $128,%[TempESP]\n" : :[TempESP] "m" (TempESP) :); Regs.ESP = TempESP; } Regs.EFLAGS = EFLAGS; asm("movl %%cr0,%%eax\n" "movl %%eax,%[CR0]\n" "movl %%cr2,%%eax\n" "movl %%eax,%[CR2]\n" "movl %%cr3,%%eax\n" "movl %%eax,%[CR3]\n" "movl %%cr4,%%eax\n" "movl %%eax,%[CR4]\n" : : [CR0] "m" (CR0), [CR2] "m" (CR2), [CR3] "m" (CR3), [CR4] "m" (CR4) :"%eax"); Regs.CR0 = CR0; Regs.CR2 = CR2; Regs.CR3 = CR3; Regs.CR4 = CR4; Regs.CS = CS; Regs.EIP = EIP; Regs.DS = Prv3DS; Regs.ES = Prv3DS; Regs.GS = Prv3DS; Regs.FS = Prv3DS; Regs.ErrorCode = 0; KernelPanic(Regs,"Unknown instruction"); HALT } void DoubleFault(u32int ErrorCode,u32int EIP,u32int CS,u32int EFLAGS,u32int ESP,u32int SS) { /*Jest to wyjątek podwójnego błędu, występuje gdy podczas przekazywania sterowania do obsługi jakiegoś wyjątku pojawi się inny wyjątek. Przykładowo jeżeli podczas wykonywania programu procesor napotka na nieobecny segment / stronę, generuje wyjątek, a kod obsługujący ten wyjątek również jest nieobecny w pamięci procesor generuje wyjątek podwójnego błędu (DoubleFault) Jeżeli i podczas generowania wyjątku podwójnego błedu nastąpi jakiś wyjątek, wtedy wystąpi zjawisko potrójnego błędu (Triple Fault) a procesor wygeneruje sprzętowy sygnał RESET i nastąpi reset komputera. Triple fault można użyć do obsługi procedury resetującej komputer, jest to znacznie prostsze niż użycie kontrolera klawiatury. Numer przerywania:8 */ u32int TempESP; u32int TempEBP; u32int CR0; u32int CR2; u32int CR3; u32int CR4; u32int Nothing; struct _Regs Regs; BOCHSDBG asm("cli\n"); asm("subl $4,%ebp\n"); asm("movl %%esp,%[TempESP]\n" "leal 40%[Regs],%%esp\n" //W ESP adres w Regs gdzie zachowujemy rejestry ogólnego przeznacznenia "pusha \n" //Zachowanie rejestrów ogólnego przeznaczenia "movl %[TempESP],%%esp\n" //Przywrócenie ESP "movl 96(%%esp),%%esp\n" "movl %%esp,%[TempEBP]\n" //Zachowanie EBP programu który spowodował błąd "movl %[TempESP],%%esp\n" //Przywrócenie ESP : : [Regs] "m" (Regs), [TempESP] "m" (TempESP), [TempEBP] "m" (TempEBP) :); if (CS & 3 != 0) { Regs.SS = SS; Regs.ESP = ESP; } else { Regs.SS = KernelSS; asm("movl %%esp,%[TempESP]\n" "addl $128,%[TempESP]\n" : :[TempESP] "m" (TempESP) :); Regs.ESP = TempESP; } Regs.EFLAGS = EFLAGS; asm("movl %%cr0,%%eax\n" "movl %%eax,%[CR0]\n" "movl %%cr2,%%eax\n" "movl %%eax,%[CR2]\n" "movl %%cr3,%%eax\n" "movl %%eax,%[CR3]\n" "movl %%cr4,%%eax\n" "movl %%eax,%[CR4]\n" : : [CR0] "m" (CR0), [CR2] "m" (CR2), [CR3] "m" (CR3), [CR4] "m" (CR4) :"%eax"); Regs.CR0 = CR0; Regs.CR2 = CR2; Regs.CR3 = CR3; Regs.CR4 = CR4; Regs.CS = CS; Regs.EIP = EIP; Regs.DS = Prv3DS; Regs.ES = Prv3DS; Regs.GS = Prv3DS; Regs.FS = Prv3DS; Regs.ErrorCode = ErrorCode; KernelPanic(Regs,"Double fault exception"); HALT } void TSSException(u32int ErrorCode,u32int EIP,u32int CS,u32int EFLAGS,u32int ESP,u32int SS) { /* CPU generuje ten wyjątek, jeżeli podczas przełączania zadania wystąpi błąd podczas operowania na segmencie TSS zadania.Numer przerywania:10 */ u32int TempESP; u32int TempEBP; u32int CR0; u32int CR2; u32int CR3; u32int CR4; u32int Nothing; struct _Regs Regs; BOCHSDBG asm("cli\n"); asm("subl $4,%ebp\n"); asm("movl %%esp,%[TempESP]\n" "leal 40%[Regs],%%esp\n" //W ESP adres w Regs gdzie zachowujemy rejestry ogólnego przeznacznenia "pusha \n" //Zachowanie rejestrów ogólnego przeznaczenia "movl %[TempESP],%%esp\n" //Przywrócenie ESP "movl 96(%%esp),%%esp\n" "movl %%esp,%[TempEBP]\n" //Zachowanie EBP programu który spowodował błąd "movl %[TempESP],%%esp\n" //Przywrócenie ESP : : [Regs] "m" (Regs), [TempESP] "m" (TempESP), [TempEBP] "m" (TempEBP) :); if (CS & 3 != 0) { Regs.SS = SS; Regs.ESP = ESP; } else { Regs.SS = KernelSS; asm("movl %%esp,%[TempESP]\n" "addl $128,%[TempESP]\n" : :[TempESP] "m" (TempESP) :); Regs.ESP = TempESP; } Regs.EFLAGS = EFLAGS; asm("movl %%cr0,%%eax\n" "movl %%eax,%[CR0]\n" "movl %%cr2,%%eax\n" "movl %%eax,%[CR2]\n" "movl %%cr3,%%eax\n" "movl %%eax,%[CR3]\n" "movl %%cr4,%%eax\n" "movl %%eax,%[CR4]\n" : : [CR0] "m" (CR0), [CR2] "m" (CR2), [CR3] "m" (CR3), [CR4] "m" (CR4) :"%eax"); Regs.CR0 = CR0; Regs.CR2 = CR2; Regs.CR3 = CR3; Regs.CR4 = CR4; Regs.CS = CS; Regs.EIP = EIP; Regs.DS = Prv3DS; Regs.ES = Prv3DS; Regs.GS = Prv3DS; Regs.FS = Prv3DS; Regs.ErrorCode = ErrorCode; KernelPanic(Regs,"TSS Exception"); HALT } void SegNotPresentException(u32int ErrorCode,u32int EIP,u32int CS,u32int EFLAGS,u32int ESP,u32int SS) {/* Brak segmentu. Numer przerywania:11 */ u32int TempESP; u32int TempEBP; u32int CR0; u32int CR2; u32int CR3; u32int CR4; u32int Nothing; struct _Regs Regs; BOCHSDBG asm("cli\n"); asm("subl $4,%ebp\n"); asm("movl %%esp,%[TempESP]\n" "leal 40%[Regs],%%esp\n" //W ESP adres w Regs gdzie zachowujemy rejestry ogólnego przeznacznenia "pusha \n" //Zachowanie rejestrów ogólnego przeznaczenia "movl %[TempESP],%%esp\n" //Przywrócenie ESP "movl 96(%%esp),%%esp\n" "movl %%esp,%[TempEBP]\n" //Zachowanie EBP programu który spowodował błąd "movl %[TempESP],%%esp\n" //Przywrócenie ESP : : [Regs] "m" (Regs), [TempESP] "m" (TempESP), [TempEBP] "m" (TempEBP) :); if (CS & 3 != 0) { Regs.SS = SS; Regs.ESP = ESP; } else { Regs.SS = KernelSS; asm("movl %%esp,%[TempESP]\n" "addl $128,%[TempESP]\n" : :[TempESP] "m" (TempESP) :); Regs.ESP = TempESP; } Regs.EFLAGS = EFLAGS; asm("movl %%cr0,%%eax\n" "movl %%eax,%[CR0]\n" "movl %%cr2,%%eax\n" "movl %%eax,%[CR2]\n" "movl %%cr3,%%eax\n" "movl %%eax,%[CR3]\n" "movl %%cr4,%%eax\n" "movl %%eax,%[CR4]\n" : : [CR0] "m" (CR0), [CR2] "m" (CR2), [CR3] "m" (CR3), [CR4] "m" (CR4) :"%eax"); Regs.CR0 = CR0; Regs.CR2 = CR2; Regs.CR3 = CR3; Regs.CR4 = CR4; Regs.CS = CS; Regs.EIP = EIP; Regs.DS = Prv3DS; Regs.ES = Prv3DS; Regs.GS = Prv3DS; Regs.FS = Prv3DS; Regs.ErrorCode = ErrorCode; KernelPanic(Regs,"Segment not present exception"); HALT } void SSException(u32int ErrorCode,u32int EIP,u32int CS,u32int EFLAGS,u32int ESP,u32int SS) { /* Wyjątek generowany z powodu błędnych operacji w segmencie stosu (np segmentu stosu nie ma w pamięci ) Numer przerywania:12 */ u32int TempESP; u32int TempEBP; u32int CR0; u32int CR2; u32int CR3; u32int CR4; u32int Nothing; struct _Regs Regs; BOCHSDBG asm("cli\n"); asm("subl $4,%ebp\n"); asm("movl %%esp,%[TempESP]\n" "leal 40%[Regs],%%esp\n" //W ESP adres w Regs gdzie zachowujemy rejestry ogólnego przeznacznenia "pusha \n" //Zachowanie rejestrów ogólnego przeznaczenia "movl %[TempESP],%%esp\n" //Przywrócenie ESP "movl 96(%%esp),%%esp\n" "movl %%esp,%[TempEBP]\n" //Zachowanie EBP programu który spowodował błąd "movl %[TempESP],%%esp\n" //Przywrócenie ESP : : [Regs] "m" (Regs), [TempESP] "m" (TempESP), [TempEBP] "m" (TempEBP) :); if (CS & 3 != 0) { Regs.SS = SS; Regs.ESP = ESP; } else { Regs.SS = KernelSS; asm("movl %%esp,%[TempESP]\n" "addl $128,%[TempESP]\n" : :[TempESP] "m" (TempESP) :); Regs.ESP = TempESP; } Regs.EFLAGS = EFLAGS; asm("movl %%cr0,%%eax\n" "movl %%eax,%[CR0]\n" "movl %%cr2,%%eax\n" "movl %%eax,%[CR2]\n" "movl %%cr3,%%eax\n" "movl %%eax,%[CR3]\n" "movl %%cr4,%%eax\n" "movl %%eax,%[CR4]\n" : : [CR0] "m" (CR0), [CR2] "m" (CR2), [CR3] "m" (CR3), [CR4] "m" (CR4) :"%eax"); Regs.CR0 = CR0; Regs.CR2 = CR2; Regs.CR3 = CR3; Regs.CR4 = CR4; Regs.CS = CS; Regs.EIP = EIP; Regs.DS = Prv3DS; Regs.ES = Prv3DS; Regs.GS = Prv3DS; Regs.FS = Prv3DS; Regs.ErrorCode = ErrorCode; KernelPanic(Regs,"SS exception"); HALT } void GeneralProtectionException(u32int ErrorCode,u32int EIP,u32int CS,u32int EFLAGS,u32int ESP,u32int SS) { /* Wyjtek generowany gdy wystąpi naruszenie mechanizmu ochrony. Naruszeniem mechanizmu ochrony nzaywamy grupę błędów: Próbę wykoniania rozkazu niedozwolnego w aktualnym poziomie uprzywilejowania; Próbę bezpośredniego odwołania się do segmentu o wyższym poziomie uprzywilejowania (niższym DPL) Numer przerywania:13*/ u32int TempESP; u32int TempEBP; u32int CR0; u32int CR2; u32int CR3; u32int CR4; u32int Nothing; struct _Regs Regs; BOCHSDBG asm("cli\n"); asm("subl $4,%ebp\n"); asm("movl %%esp,%[TempESP]\n" "leal 40%[Regs],%%esp\n" //W ESP adres w Regs gdzie zachowujemy rejestry ogólnego przeznacznenia "pusha \n" //Zachowanie rejestrów ogólnego przeznaczenia "movl %[TempESP],%%esp\n" //Przywrócenie ESP "movl 96(%%esp),%%esp\n" "movl %%esp,%[TempEBP]\n" //Zachowanie EBP programu który spowodował błąd "movl %[TempESP],%%esp\n" //Przywrócenie ESP : : [Regs] "m" (Regs), [TempESP] "m" (TempESP), [TempEBP] "m" (TempEBP) :); if (CS & 3 != 0) { Regs.SS = SS; Regs.ESP = ESP; } else { Regs.SS = KernelSS; asm("movl %%esp,%[TempESP]\n" "addl $128,%[TempESP]\n" : :[TempESP] "m" (TempESP) :); Regs.ESP = TempESP; } Regs.EFLAGS = EFLAGS; asm("movl %%cr0,%%eax\n" "movl %%eax,%[CR0]\n" "movl %%cr2,%%eax\n" "movl %%eax,%[CR2]\n" "movl %%cr3,%%eax\n" "movl %%eax,%[CR3]\n" "movl %%cr4,%%eax\n" "movl %%eax,%[CR4]\n" : : [CR0] "m" (CR0), [CR2] "m" (CR2), [CR3] "m" (CR3), [CR4] "m" (CR4) :"%eax"); Regs.CR0 = CR0; Regs.CR2 = CR2; Regs.CR3 = CR3; Regs.CR4 = CR4; Regs.CS = CS; Regs.EIP = EIP; Regs.DS = Prv3DS; Regs.ES = Prv3DS; Regs.GS = Prv3DS; Regs.FS = Prv3DS; Regs.ErrorCode = ErrorCode; KernelPanic(Regs,"General protection exception"); HALT } void PageFaultExceptopn(u32int ErrorCode,u32int EIP,u32int CS,u32int EFLAGS,u32int ESP,u32int SS) { u32int TempESP; u32int TempEBP; u32int CR0; u32int CR2; u32int CR3; u32int CR4; u32int Nothing; struct _Regs Regs; BOCHSDBG asm("cli\n"); asm("subl $4,%ebp\n"); asm("movl %%esp,%[TempESP]\n" "leal 40%[Regs],%%esp\n" //W ESP adres w Regs gdzie zachowujemy rejestry ogólnego przeznacznenia "pusha \n" //Zachowanie rejestrów ogólnego przeznaczenia "movl %[TempESP],%%esp\n" //Przywrócenie ESP "movl 96(%%esp),%%esp\n" "movl %%esp,%[TempEBP]\n" //Zachowanie EBP programu który spowodował błąd "movl %[TempESP],%%esp\n" //Przywrócenie ESP : : [Regs] "m" (Regs), [TempESP] "m" (TempESP), [TempEBP] "m" (TempEBP) :); if (CS & 3 != 0) { Regs.SS = SS; Regs.ESP = ESP; } else { Regs.SS = KernelSS; asm("movl %%esp,%[TempESP]\n" "addl $128,%[TempESP]\n" : :[TempESP] "m" (TempESP) :); Regs.ESP = TempESP; } Regs.EFLAGS = EFLAGS; asm("movl %%cr0,%%eax\n" "movl %%eax,%[CR0]\n" "movl %%cr2,%%eax\n" "movl %%eax,%[CR2]\n" "movl %%cr3,%%eax\n" "movl %%eax,%[CR3]\n" "movl %%cr4,%%eax\n" "movl %%eax,%[CR4]\n" : : [CR0] "m" (CR0), [CR2] "m" (CR2), [CR3] "m" (CR3), [CR4] "m" (CR4) :"%eax"); Regs.CR0 = CR0; Regs.CR2 = CR2; Regs.CR3 = CR3; Regs.CR4 = CR4; Regs.CS = CS; Regs.EIP = EIP; Regs.DS = Prv3DS; Regs.ES = Prv3DS; Regs.GS = Prv3DS; Regs.FS = Prv3DS; Regs.ErrorCode = ErrorCode; KernelPanic(Regs,"Page fault exception"); HALT}/* Brak strony. Numer przerywania:14 */ void KernelPanic(struct _Regs Regs, uchar Message[]) { /* Legendarna procedura, która wywoływana jest podczas wystąpienia błędu w pracy jądra. Wyświetla komunikat, dodatkowe parametry,miejsce wystąpienia błędu,stan rejestrów, stan danych systemowych,itp, następnie zawiesza system */ u16int temp,temp2; u32int *temp3; ClearScreen(); kprintf("Kernel panic!!!%c in kernel area at: %x:%x.\n\rCall stack:%x.\n\rRegisters:\n\r",Message,Regs.CS,Regs.EIP,CallStack); kprintf("Error code: %x\n\r",Regs.ErrorCode); kprintf("EAX: %x EBX: %x ECX: %x \n\r",Regs.EAX,Regs.EBX,Regs.ECX); kprintf("EDX: %x ESI: %x EDI: %x \n\r",Regs.EDX,Regs.ESI,Regs.EDI); kprintf("EBP: %x ESP: %x EFLAGS: %x \n\r",Regs.EBP,Regs.ESP,Regs.EFLAGS); kprintf("Segment registers:\n\r"); kprintf("CS: %x DS: %x ES: %x \n\r",Regs.CS,Regs.DS,Regs.ES); kprintf("SS: %x GS: %x FS: %x \n\r",Regs.SS,Regs.GS,Regs.FS); kprintf("Control registers (CRx):\n\rCR0: %x CR1: Reserved CR2: %x CR3: %x CR4: %x\n\r",Regs.CR0,Regs.CR2,Regs.CR3,Regs.CR4); kprintf("Task state register: 5 \n\r"); temp3 = 0; BOCHSDBG kprintf("System halted!!!\n\r"); asm("cli\n" "hlt\n"); } void SetExceptions() { /*Procedura inicjuje obsługę wyjątków, poprzez wpisanie odpowiednich wartości do tablicy IDT Numer funkcji: 8*/ u32int temp2; SetCallStack(8) /*for (temp=0;temp != 100;temp++) {* IDTS[temp].Offset1 = &DivBy0Exception; // Wpisanie offsetu procedury obsługi wyjątku IDTS[temp].Selector = 0x8; //Selektor segmentu jądra IDTS[temp].Zero = 0; IDTS[temp].W=0; IDTS[temp].MB3=3; IDTS[temp].D=1; IDTS[temp].Zero2 = 0; IDTS[temp].DPL = 0; IDTS[temp].P = 1; IDTS[temp].Offset2 = 0; //}*/ temp2 = (u32int) & DivBy0Exception; IDTS[0].Offset1 = temp2 & 0xFFFF; // Wpisanie offsetu procedury obsługi wyjątku IDTS[0].Selector = 0x8; //Selektor segmentu jądra IDTS[0].Zero = 0; IDTS[0].W=0; IDTS[0].MB3=3; IDTS[0].D=1; IDTS[0].Zero2 = 0; IDTS[0].DPL = 0; IDTS[0].P = 1; temp2 = temp2 & 0xFFFF0000; IDTS[0].Offset2 = temp2 >> 16 ; temp2 = (u32int) & OffsetTooLargeException; IDTS[5].Offset1 = temp2 & 0xFFFF; // Wpisanie offsetu procedury obsługi wyjątku IDTS[5].Selector = 0x8; //Selektor segmentu jądra IDTS[5].Zero = 0; IDTS[5].W=0; IDTS[5].MB3=3; IDTS[5].D=1; IDTS[5].Zero2 = 0; IDTS[5].DPL = 0; IDTS[5].P = 1; temp2 = temp2 & 0xFFFF0000; IDTS[5].Offset2 = temp2 >> 16 ; temp2 = (u32int) & UnknowInstruction; IDTS[6].Offset1 = temp2 & 0xFFFF; // Wpisanie offsetu procedury obsługi wyjątku ; // Wpisanie offsetu procedury obsługi wyjątku IDTS[6].Selector = 0x8; //Selektor segmentu jądra IDTS[6].Zero = 0; IDTS[6].W=0; IDTS[6].MB3=3; IDTS[6].D=1; IDTS[6].Zero2 = 0; IDTS[6].DPL = 0; IDTS[6].P = 1; temp2 = temp2 & 0xFFFF0000; IDTS[6].Offset2 = temp2 >> 16 ; temp2 = (u32int) & DoubleFault; IDTS[8].Offset1 = temp2 & 0xFFFF;; // Wpisanie offsetu procedury obsługi wyjątku IDTS[8].Selector = 0x8; //Selektor segmentu jądra IDTS[8].Zero = 0; IDTS[8].W=0; IDTS[8].MB3=3; IDTS[8].D=1; IDTS[8].Zero2 = 0; IDTS[8].DPL = 0; IDTS[8].P = 1; temp2 = temp2 & 0xFFFF0000; IDTS[8].Offset2 = temp2 >> 16 ; temp2 = (u32int) & TSSException; IDTS[10].Offset1 = temp2 & 0xFFFF; // Wpisanie offsetu procedury obsługi wyjątku IDTS[10].Selector = 0x8; //Selektor segmentu jądra IDTS[10].Zero = 0; IDTS[10].W=0; IDTS[10].MB3=3; IDTS[10].D=1; IDTS[10].Zero2 = 0; IDTS[10].DPL = 0; IDTS[10].P = 1; temp2 = temp2 & 0xFFFF0000; IDTS[10].Offset2 = temp2 >> 16; temp2 = (u32int) & SegNotPresentException; IDTS[11].Offset1 = temp2 & 0xFFFF; // Wpisanie offsetu procedury obsługi wyjątku IDTS[11].Selector = 0x8; //Selektor segmentu jądra IDTS[11].Zero = 0; IDTS[11].W=0; IDTS[11].MB3=3; IDTS[11].D=1; IDTS[11].Zero2 = 0; IDTS[11].DPL = 0; IDTS[11].P = 1; temp2 = temp2 & 0xFFFF0000; IDTS[11].Offset2 = temp2 >> 16; temp2 = (u32int) & SSException; IDTS[12].Offset1 = temp2 & 0xFFFF; // Wpisanie offsetu procedury obsługi wyjątku IDTS[12].Selector = 0x8; //Selektor segmentu jądra IDTS[12].Zero = 0; IDTS[12].W=0; IDTS[12].MB3=3; IDTS[12].D=1; IDTS[12].Zero2 = 0; IDTS[12].DPL = 0; IDTS[12].P = 1; temp2 = temp2 & 0xFFFF0000; IDTS[12].Offset2 = temp2 >> 16; temp2 = (u32int) & GeneralProtectionException; IDTS[13].Offset1 = temp2 & 0xFFFF; // Wpisanie offsetu procedury obsługi wyjątku IDTS[13].Selector = 0x8; //Selektor segmentu jądra IDTS[13].Zero = 0; IDTS[13].W=0; IDTS[13].MB3=3; IDTS[13].D=1; IDTS[13].Zero2 = 0; IDTS[13].DPL = 0; IDTS[13].P = 1; temp2 = temp2 & 0xFFFF0000; IDTS[13].Offset2 = temp2 >> 16; temp2 = (u32int) & PageFaultExceptopn; IDTS[14].Offset1 = temp2 & 0xFFFF; // Wpisanie offsetu procedury obsługi wyjątku IDTS[14].Selector = 0x8; //Selektor segmentu jądra IDTS[14].Zero = 0; IDTS[14].W=0; IDTS[14].MB3=3; IDTS[14].D=1; IDTS[14].Zero2 = 0; IDTS[14].DPL = 0; IDTS[14].P = 1; temp2 = temp2 & 0xFFFF0000; IDTS[14].Offset2 = temp2 >> 16; ReturnCallStack /*IDTS[0].Offset1 = 1; // Wpisanie offsetu procedury obsługi wyjątku IDTS[0].Selector = 0; //Selektor segmentu jądra IDTS[0].Zero = 0; IDTS[0].W=0; IDTS[0].MB3=0; IDTS[0].D=0; IDTS[0].Zero2 = 0; IDTS[0].DPL = 0; IDTS[0].P = 0; IDTS[0].Offset2 = 0;*/ }<file_sep>/* *********************************************************************************************************** * mem.c * * Wersja:pre-alpha * * e-mail:<EMAIL> * * 2014 * *********************************************************************************************************** Jeden z plików wchodzących w skład jądra systemu, odpowiadający za allokację pamięci i obsługę pamięci wirtualnej. Jądro systemu pracuje w trybie chronionym, faktycznie nie wykorzystując segmentacji do rozdzielenia przestrzeni procesów,korzystając z płaskiego modelu pamięci( wszystkie segmenty używane zarówno przez system, jak i procesy użytkownika mają adres bazowy 0 i wielkość 4 294 967 295). Do segregacji pamięci procesów wykorzystywany jest mechanizm stronicowania, poprzez różne katalogi stron poszczególnych procesów. Pewne strony są wspólne dla całego systemu, są to strony z jądrem i niektóre strony procesów użytkownika. Strony jądra systemu nie podlegają przeniesieniu do pamięci SWAP. PDBR zawiera 1024 PDE ( elementów katalogu stron, bity 22-31 adresu logicznego).Element katalogu stron zawiera adres odpowiedniej tablicy stron, koniecznej do dalszego przetwarzania. Każdy PDE zawiera 1024 PTE Adres PDBR zawarty jest w rejestrze CR3 Adresy liniowe 0 - 10 485 760 (10 MB, 2560 stron) są zarezerwowane dla jądra, i wspólne dla każdego zadania w systemie. Są mapowane 1:1, tzn. np. adres liniowy 0x800 oznacza adres fizyczny 0x800 */ #include "data.h" volatile u32int RAMFree=0x2000000; //Całkowita ilość wolnego miejsca w RAM Tymczasowo 32 MB volatile u32int RAMSize=0x2000000; //Całkowita wielkość pamięci RAM Tymczasowo 32 MB volatile u32int SwapSize; //Wielkość pamęci SWAP volatile u32int FreeSwapSize; //Ilość wolnej pamięci wymiany volatile u32int LinearPDBase; /*Adres liniowy katalogu stron. Odnosi się do pocżatku przestrzeni adresowej,nie do segmentu danych, więc jeżeli chcemy operować na katalogu stron za pomocą wskaźników, w adres wskaźnika należy wpisać LinearPDBase- adres bazowy segmentu danych. */ u32int FramesN=0; //Ilość ramek w tablicy FramesN u32int ClosestFreeFrame=0; //Najbliższa wolna ramka względem ramki nr 0. u32int Frames[0x20000]; //Tablica zawierajaća informację o zajętości ramek. 1 bit opisuje 1 ramkę, czyli 4 KB. Jeden wpis opisuje 32 ramki, czyli 128 KB void LinearAddressToPDEPTE(u32int LinearAddress,u16int *PDE,u16int *PTE,u16int *Ofs) { /*Funkcja wyodrębnia z adresu liniowego numer wpisu w katalogu stron, numer wpisu w tablicy stron, oraz offset w stosunku do początku strony. PARAMETRY: LinearAddress - adres liniowy do przetworzenia ZWRACANE: *PDE - numer wpisu w katalogu stron *PTE - numer wpisu w tablicy stron *Ofs - offset */ *PDE = (LinearAddress & 0xFFE00000) >> 0x16; *PTE = (LinearAddress & 0x1FF000) >> 0xC; *Ofs = LinearAddress & 0xFFF; } void ChangeFrameBit(u32int FrameN,uchar Bit) { /*Procedura ustawia bit zajętości ramki o numerze FrameN,Bit - 0 lub 1 */ u32int temp; u32int temp2; u32int temp3; u32int temp4; u32int Address; /* Zmiana bitu : */ temp = FrameN / 32; temp2 = FrameN % 32; temp3 = Frames[temp]; if (Bit == 1) { temp3 = temp3 | (1 << temp2); } else { temp3 = temp3 & !(1 << temp2); } Frames[temp] = temp3; } uchar GetFrameBit(u32int FrameN) { /* Funkcja zwraca stan bitu zajętości ramki o numerze FrameN */ u32int temp; u32int temp2; u32int temp3; u32int temp4; u32int Address; /* Zmiana bitu : */ temp = FrameN / 32; temp2 = FrameN % 32; temp3 = Frames[temp]; temp3 = temp3 & (1 << temp2); if (temp3 == 0) { return 0; } else return 1; } void FindClosestFreeFrameBit() { /* Funkcja wyszukuje aktualnie najbliższej wolnej ramki, i zwraca jej numer w zmiennej ClosestFreeFrame */ u32int temp; u32int temp2; u32int temp3; u32int temp4; if (RAMFree != 0) { /* Poszukiwanie nowej wolnej ramki: */ for (temp4=ClosestFreeFrame; temp4 <= FramesN; temp4++) { temp = temp4 / 32; temp2 = temp4 % 32; temp3 = Frames[temp]; temp3 = temp3 & (1 << temp2); if (temp3==0) { ClosestFreeFrame = temp4; return 0; } } for (temp4=0; temp4 <= ClosestFreeFrame; temp4++) { temp = temp4 / 32; temp2 = temp4 % 32; temp3 = Frames[temp]; temp3 = temp3 & (1 << temp2); if (temp3==0) { ClosestFreeFrame = temp4; return 0; } } return 0; } else return 0; } u32int SetClosestFreeFrameBit() { /* Funkcja ustawia bit zajętości aktualnie najbliższej wolnej ramki, oraz poszukuje następnej aktualnie wolnej ramki. ZWRACANE: Adres fizyczny aktualnie wolnej ramki */ u32int temp; u32int temp2; u32int temp3; u32int temp4; u32int Address; /* Ustawienie bitu : */ temp = ClosestFreeFrame / 32; temp2 = ClosestFreeFrame % 32; temp3 = Frames[temp]; temp3 = temp3 | (1 << temp2); Frames[temp] = temp3; Address = ClosestFreeFrame * 0x1000; if (RAMFree != 0) { /* Poszukiwanie nowej wolnej ramki: */ for (temp4=ClosestFreeFrame; temp4 <= FramesN; temp4++) { temp = temp4 / 32; temp2 = temp4 % 32; temp3 = Frames[temp]; temp3 = temp3 & (1 << temp2); if (temp3==0) { ClosestFreeFrame = temp4; return Address; } } for (temp4=0; temp4 <= ClosestFreeFrame; temp4++) { temp = temp4 / 32; temp2 = temp4 % 32; temp3 = Frames[temp]; temp3 = temp3 & (1 << temp2); if (temp3==0) { ClosestFreeFrame = temp4; return Address; } } return Address; } else return Address; } uchar AllocPsyhicalMemory(u32int PDBR,u32int PTEB,u32int Psyhical,u32int Logical,u32int Size,struct _PDE *PDEA,struct _PTE *PTEA) { /* Funkcja allokuje pamięć, jednak w przeciwieństwie do zwykłej funkcji AllocMem umożliwia określenie adresu fizycznego pod którym znajdują się allokowane strony. W pamięci fizycznej allokuje ciagły obszar, jeżeli nie można zaallokować ciągłego obszaru to wtedy zgłasza błąd. PARAMETRY: PDBR - Adres fizyczny początku katalogu stron, inaczej rejestr CR3 PTEB - Adres fizyczny początku obszaru gdzie znajdują się tablice stron Psyhical - Początkowy adres fizyczny Logical - Początkowy adres logiczny, potrzebny do określenia katalogu stron i strony PDEA - atrybuty katalogów stron PTEA - atrybuty stron ZWRACANE : 0 - OK 1 - Nie można zaallokować obszaru, gdyż ramki zawarte pod podanym adresem są już zajęte, a nie można ich przenieść do pamięci SWAP */ u32int temp; u32int temp2; u32int temp3; u16int PDEn; u16int PTEn; u32int LinearAddress; u32int PDEAddr; u32int PTEAddr; u16int Offset; struct _PDE *PDE; struct _PTE *PTE; temp2 = Psyhical + Size / 4096; for (temp == Psyhical / 4096;temp <= temp2; temp++) { // Pętla sprawdzająca czy podany obszar pamięci fizycznej jest wolny. Psychical % 4096 - obliczenie numeru pierwszej ramki . (Psyhical+Size) % 4096 - numer ostatniej ramki if (GetFrameBit(temp) !=0) return 1; } LinearAddress = Logical; temp2 = Psyhical + Size / 4096; temp = 0; for (temp == Psyhical / 4096;temp <= temp2; temp++) { /* Pętla allokująca podany obszar. Tworzy odpowiednie struktury */ ChangeFrameBit(temp,1); LinearAddressToPDEPTE(LinearAddress,&PDEn,&PTEn,&Offset); // Obiczenie nr wpisu w katalogu stron, i tablicy stron PDEAddr = PDEn * 4 +PDBR; //Obliczenie adresu wpisu w katalogu stron /* Utworzenie wpisu w katalogu stron */ PDE = PDEAddr; PDE -> P = 1;//PDEA -> P; PDE -> RW = PDEA -> RW; PDE -> US = PDEA -> US; PDE -> PWT = PDEA -> PWT; PDE -> PCD = PDEA -> PCD; PDE -> A = PDEA -> A; PDE -> Zero = 0; PDE -> PageSize = PDEA -> PageSize; PDE -> G = PDEA -> G; PDE -> AVL = PDEA -> AVL; temp3 = PTEB+PDEn*4096; temp3 = temp3 >> 12; PDE -> Base = temp3; PTE = PTEB+PTEn*4; PTE -> P = 1;//PTEA -> P; PTE -> RW = PTEA -> RW; PTE -> US = PTEA -> US; PTE -> PWT = PTEA -> PWT; PTE -> PCD = PTEA -> PCD; PTE -> A = PTEA -> A; PTE -> D = PTEA -> D; PTE -> Zero = 0; PTE -> G = PTEA -> G; PTE -> AVL = PTEA -> AVL; temp3 = Psyhical + PTEn*4096; temp3 = temp3 >> 12; PTE -> Base = temp3; //Psyhical + PTEn*4096; LinearAddress = LinearAddress + 4096; } FindClosestFreeFrameBit(); return 0; } uchar AllocMemoryWithAttribs(u32int Task,u32int Size, struct _PDE *PDEAttribs,struct _PTE *PTEAttribs) { /* Funkcja allokuje pamięć dla podanego zadania, jeżeli niema odpowiedniej ilości wolnej pamięci wtedy następuje przeniesienie odpowiedniej ilości danych z pamięci RAM do swap. Dodatkowo umożliwia podanie parametrów allokowanej pamięci PARAMETRY: Task - numer zadania, dla którego allokujemy pamięć Size - wielkość allkowanej pamięci w bajtach PDEAttribs,PTEAttribs - atrybuty PDE i PTE ZWRACANE: 0 - pamięć została przydzielona 1 - ilość wolnej pamięci w systemie (RAM + SWAP) jest mniejsza niż porządana ilość 2 - Numer zadania jest więlszy niż ilość zadań w systemie */ u32int Pages; //Ilość stron(ramek) do allokacji u32int temp; u32int PDBR; //Adres katalogu stron zadania u32int PDEn,PTEn; struct _PDE *PDE; //Wskaźnik na aktualnie przetwarzany PDE struct _PTE *PTE; //Wskażnik na aktualnie przetwarzany PTE if (RAMSize+FreeSwapSize < Size) { return 1; } if (Task > TasksN-1) { return 2;} if (Size > RAMFree) { /* Jeżeli ilość aktualnie wolnej pamięci RAM jest mniejsza niż wymagana, trzeba część przenieść do pamęci SWAP * /* PRZENOSZENIE DO SWAP */ } if (Size == 0) return 0; asm("cli\n"); //Tymczasowo wyłączenie przerwań DisablePaging /*asm("movl %cr0,%eax\n" /* Tymczasowo wyłączenie stronicowania * "andl $0x7FFFFFFF,%eax\n" //Wyzerowanie bitu stronicowania "movl %eax,%cr0\n"); */ Pages = Size / 4096 -1; //Obliczenie ilości stron do zaalokowania PDBR = Tasks[Task].PDBR; PDEn = Tasks[Task].PDEsN; PTEn = Tasks[Task].PTEsN; for (temp =0; temp <= Pages ; temp++) { /*Pętla tworząca PDE i PTE */ if (PTEn == 1024) { /* Jak tablica stron (PDE) jest pełna, trzeba stworzyć nową tablicę stron */ PDE = (u32int) PDBR + PDEn*4; //Adres nowego PDE w PDBR PDE -> P = 1; PDE -> RW = PDEAttribs -> RW; PDE -> US = PDEAttribs -> US; PDE -> PWT = PDEAttribs -> PWT; PDE -> PCD = PDEAttribs -> PCD; PDE -> A = PDEAttribs -> A; PDE -> Zero = 0; PDE -> PageSize = PDEAttribs -> PageSize; PDE -> G = PDEAttribs -> G; PDE -> AVL = PDEAttribs -> AVL; PDE -> Base = SetClosestFreeFrameBit() >> 12; //Znalezienie aktualnie wolnej ramki dla tablicy stron */ PDEn++; PTEn = 1; } PDE = (u32int) PDBR+(PDEn-1)*4; //Adres aktualnie ostatniego PDE. w PDBR PTE = (PDE -> Base+(PTEn-1)*4) << 12; //Adres aktualnego PTE(aktualnej strony) PTE -> P = PTEAttribs -> P; PTE -> RW = PTEAttribs -> RW; PTE -> US = PTEAttribs -> US; PTE -> PWT = PTEAttribs -> PWT; PTE -> PCD = PTEAttribs -> PCD; PTE -> A = PTEAttribs -> A; PTE -> D = PTEAttribs -> D; PTE -> Zero = 0; PTE -> G = PTEAttribs -> G; PTE -> AVL = PTEAttribs -> AVL; PTE -> Base = SetClosestFreeFrameBit() >> 12; //Znalezienie aktualnie wolnej ramki dla strony PTEn++; } Tasks[Task].PDEsN = PDEn; Tasks[Task].PTEsN = PTEn; Tasks[Task].MemSize = Tasks[Task].MemSize + Size; PagingEnable asm("sti\n"); //Włączenie przerwań return 0; } uchar AllocMemory(u32int Task,u32int Size) { /*Funkcja allokuje pamięć dla podanego zadania, z domyślnymi atrybutami zapisanymi w Task. PDEDefault i PTEDefault. PARAMETRY: Task - numer zadania, dla którego allokujemy pamięć Size - wielkość allokowanej pamięci w bajtach ZWRACANE: Takie same jak w przypadku AllocMemoryWithAttribs */ uchar temp; temp = AllocMemoryWithAttribs(Task,Size,&Tasks[Task].PDEDefault,&Tasks[Task].PTEDefault); return temp; } <file_sep>/* *************************************************************************************** * bosch.h * * Wersja: pre-alpha * * e-mail:<EMAIL> * * 2014 * *************************************************************************************** Plik zawiera definicje makr ułatwiające korzystanie z debuggingu w emulatorze Bosch */ #define DEBUG 1 void main() { HALT }<file_sep>/* *************************************************************************************** * data.h * * Wersja: pre-alpha * * e-mail:<EMAIL> * * 2014 * *************************************************************************************** Plik nagłówkowy zawierający definicje podstawowych typów danych, makr i struktur wykorzystywanych w całym jądrze. */ /*Makra:*/ #if DEBUG == 1 /*Sprawdza czy zadeklarowane jest makro DEBUG i czy jego wartość wynosi. Jeżeli nie wtedy wspomaganie debuggowania jest nie aktywne. DEBUG zazwyczaj definiowane jest już w linii poleceń gcc (-D DEBUG=1), jednak oczywiście możliwe jest także zdefiniowanie w kodzie programu.*/ #define BOCHSDBG asm volatile ("xchg %bx,%bx\n #BOCHS DEBUG"); /*Powoduje zatrzymanie emulatora Bochs i przejście do debuggera */ #else #define BOCHSDBG #endif #define DisablePaging asm("pushl %eax \n movl %cr0,%eax\n andl $0x7FFFFFFF,%eax\n movl %eax,%cr0\n popl %eax"); // Makro wyłącza stronnicowanie #define PagingEnable asm("pushl %eax \n movl %cr0,%eax\n or $0x80000000,%eax \n movl %eax,%cr0 \n popl %eax"); // Makro włącza stronnicowanie #define HALT asm("cli\nhlt # BOCHS DEBUG"); /*Zawiesza komputer lub emulator */ #define SetCallStack(xxx) OldCallStack = CallStack; /*Makro zmienia wartość zmiennej CallStack(stosu wywołań procedrur systemowych), zachowując poprzednią wartość.Musi znajdować się na początku funkcji. */ \ CallStack = xxx; \ #define ReturnCallStack CallStack = OldCallStack; /*Makro przywraca wartość zmiennej CallStack(stosu wywołań procedrur systemowych) po zakończeniu pracy funkcjii. Musi znajdować się na końcu kodu funkcji. */ #define PIC_EOI 0x20 //Rozkaz wysyłany do PIC informujący o zakończeniu obsługi przerywania sprzętowego #define GDTSMAX 256 //Maksyamalna ilość wpisów w tablicy GDT. Musi być większa niż 1, gdyż pierwszy wpis to tzw. Null Descriptor #define IDTSMAX 256 //Maksyamalna ilość wpisów w tablicy IDT. Maksymalna ilość przerwań obsługiwana przez jądro. #define TASKMAX 0xA //Wielkość tablicy zadań #define ClockFrequency 10 // Częstotliwość zegara systemowego. Zgear ten odpowiada za przełączanie zadań i odmierzanie czasu rzeczywistego #define SizeOfTaskEntry i // Wielkość wpisu w tablicy Tasks #define KernelSS 0x18 //Selektor segmentu stosu dla kodu o poziomie uprzywilejowania 0 ( jądra) #define KernelCS 0x8 //Selektor segmentu kodu dla poziomu uprzywilejowania 0 #define Prv1CS 0x31 //Selektor segmentu kodu dla poziomu uprzywilejowania 1 #define Prv2CS 0x3A //Selektor segmentu kodu dla poziomu uprzywilejowania 2 #define Prv3CS 0x43 //Selektor segmentu kodu dla poziomu uprzywilejowania 3 #define Prv3DS 0x13 //Selektor segmentu danych dla całego systemu, posiada poziom uprzywilejowania 3 #define KernelSpaceEndAddress 10485760 //Wielkość pamięci zarezerwowanej dla jądra (jej końcowy adres, bo zaczyna się od 0, (10 MB, 2560 stron)). Są mapowane 1:1, tzn. np. adres liniowy 0x800 oznacza adres fizyczny 0x800 /* Deklaracje podstawowych typów danych : */ typedef unsigned short u16int; /* u16int - 16 bitowa ca³kowita bez znaku */ typedef signed short int s16int; /* 16 bitowa ca³kowita ze znakiem */ typedef signed char schar; // 8 bitowa ze znakiem typedef unsigned char uchar; /* 8 bitowa ze bez znaku */ typedef unsigned int u32int; /*32 bitowa ca³kowita bez znaku */ typedef signed int s32int; /*32 bitowa ca³kowita ze znakiem*/ /*Definicje struktur: */ struct _Frames { /* Struktura opisująca ramki, konieczna do obsługi pamięci wirtualnej */ u32int Base; //Adres bazowy ramki uchar Free; //1 - ramka wolna - 0 ramka zajęta i stronę w ramce trzeba przenieść do pamięci Swap }; struct _GDTS { /* Struktura definiuj¹ca wpis w tablicy segmentów GDT */ u16int Size1; //Limit segmentu bity (15..0),je¿eli Size1 i Size2 = 0 wtedy segment jest wolny u16int Base1; // Baza segmentu bity (15..0) uchar Base2; u16int A:1; u16int RW:1; u16int CE:1; u16int T:1; u16int S:1; u16int DPL:2; u16int P:1; u16int Size2:4; u16int AVL:1; u16int Zero:1; u16int D:1; u16int G:1; uchar Base3; }; struct _IDTS { /*Struktura wpisu w tablicy IDT */ u16int Offset1; /* Bity 15..0 offsetu procedury obs³ugi przerywania w segmencie */ u16int Selector; /* 16 bitowy selektor segmentu z procedur¹ obs³ugi przerywania */ uchar Zero; //Zawsze musi być 0!!! u16int W:1; //0 - deskryptor dotyczy furtki przerywania, 1- pułapki u16int MB3:2; //Musi być 3 !!! u16int D:1; //Tryb pracy procesora przy obsłudze przerywania lub pułapki ( 0- 16 bitowy procesorów 80286 1- 32 bitowy 80386 lub lepszych) u16int Zero2:1; //Musi być 0 u16int DPL:2; //Poziom uprzywilejowania u16int P:1; //Bit określa czy segment w ktróym zawarty jest program obsługi przerywania jest obecny w pamięci czy też nie u16int Offset2; /* Bity 31..16 offsetu */ }; struct _GDTDescr { /*Struktura psedudodeskryptora GDT */ u16int Size; /* Wielkoœæ GDT w bajtach. Wzór do obliczenia: iloœæ wpisów*8-1 */ u16int AddrL; /* M³odsze 16 bitów adresu fizycznego tablicy GDT */ uchar AddrH; /* Starsze 16 bitów adresu fizycznego tablicy GDT */ }; struct _IDTDescr { /*Struktura psedudodeskryptora IDT */ u16int Size; /* Wielkość IDT w bajtach. Wzór do obliczenia: iloœæ wpisów*8-1 */ u16int AddrL; /* M³odsze 16 bitów adresu fizycznego tablicy IDT */ uchar AddrH; /* Starsze 16 bitów adresu fizycznego tablicy IDT */ }; struct TSSSeg { /* Struktura służąca do operowania na segmentach stanu zadania,nie jest całkowicie kompatybilna z sprzętowym TSS w procesorach(została zamieniona kolejność rejestrów ogólnego przeznaczenia), ponieważ w systemie przełączanie zadań odbywa się na bardziej na drodze programowej, jednak struktura ta musi być utrzymywana ze względu na to że jest potrzebna podczas zmiany poziomu uprzywilejowania aktualnie wykonywanego kodu. Podczas zmiany poziomu uprzywilejowania pod uwagę brane są tylko pola od ESP0 do SS2 i SS3, zawartość reszty może być dowolna. Przełączanie zadań bez zmiany poziomu uprzywilejowania będzie odbywać się za poomocą rozkazów stosu pusha, popa, push i pop i trzeba było dostosować strukturę do rozkazu pusha*/ u32int Back; //Selektor TSS poprzedniego zadania u32int ESP0; //Wierchołek stosu zadania w 0 poziomie uprzywilejowania u32int SS0; //Selektor stosu zadania w 0 poziomie uprzywilejowania u32int ESP1; //Wierchołek stosu zadania w 1 poziomie uprzywilejowania u32int SS1; //Selektor stosu zadania w 1 poziomie uprzywilejowania u32int ESP2; //Wierchołek stosu zadania w 2 poziomie uprzywilejowania u32int SS2; //Selektor stosu zadania w 2 poziomie uprzywilejowania u32int CR3; u32int ES; u32int FS; //10 u32int EDI; u32int ESI; u32int EBP; u32int DS; //Ta wartość jest ignorowana. W całym systemie wartość DS jest taka sama u32int EBX; u32int EDX; u32int ECX; u32int EAX; //18 u32int EIP; //19, bajt 72 u32int CS; u32int EFLAGS; u32int ESP; u32int SS; u32int GS; u32int LDT; //W systemie nie wykorzystywane,25 pozycja, bajt 100 u16int TRAP; //Bit pracy krokowej przeznaczony dla debuggerów.Jeżeli wynosi 1, wtedy po przełączeniu zadania wywoływany jest wyjątek nr 1 //27 u16int IOMAP; //Adres względny tablicy zezwoleń we/wy //29 }; struct _Regs { /* Struktura służąca do przechowywania zawartości rejestórw w przypadku wystąpenia wyjątku celem wyświetlenia ich zawartości */ u32int ES; u32int FS; u32int EDI; u32int ESI; u32int EBP; u32int DS; //Ta wartość jest ignorowana. W całym systemie wartość DS jest taka sama u32int EBX; u32int EDX; u32int ECX; u32int EAX; //Pozycja nr 10 u32int EIP; //Offset instrukcji która wywołała wyjątek, pozycja nr 11 u32int CS; u32int EFLAGS; u32int ESP; //Pozycja nr 14 u32int SS; u32int GS; u16int TRAP; //Bit pracy krokowej przeznaczony dla debuggerów.Jeżeli wynosi 1, wtedy po przełączeniu zadania wywoływany jest wyjątek nr 1 //27 u16int IOMAP; //Adres względny tablicy zezwoleń we/wy //29 u32int CR0; u32int CR1; u32int CR2; u32int CR3; u32int CR4; u32int ErrorCode; //Kod błędu zawierający dodatkowe informacje }; struct _PDE { /*Strukrura opisująca wpis w katalogu stron */ u16int P:1; //Bit ten określa czy tablica stron jest dostępna u16int RW:1; //Jeżeli bit jest ustawiony, zapis do tej grupy stron jest możliy tylko gdy kod ma poziom uprzywilejowania superwisor( bit U/S=0) i gdy bit WP w cr0 wynosi 0. W przeciwnym wpdaku zapis do tych stron jest możliwy przez program o uprzywilejowaniu user u16int US:1; //Bit określa poziom uprzywilejowania stron w tej tablicy, 0 - poziom najwyższy 1 - poziom użytkownika u16int PWT:1; //Alogrytm pracy pamięci podręcznej u16int PCD:1; u16int A:1; //Bit ten jest ustawiany przez procesor jeżeli doszło do odwołania do tablicy stron wksazywanej przez to PDE. u16int Zero:1; //Zawsze 0 u16int PageSize:1; //0 - storny o rozmiarze 4 KB,1 - strony o rozmiarze 4 MB( dla stornicowania 32 bitowego) lub @MB ( dla stronicowania z rozszerzonym adresie fizycznym) u16int G:1; //Bit ma znaczenie wtedy gdy jest ustawiony bit PGE w CR4, jeżeli bit wynosi 1 wtedy wpis PDE istniejący w tablicy TLB nie zostanie usunięty u16int AVL:3; // 7 - wpis jest prawidłowy, a katalog stron dosŧpny u32int Base:20; // 20 starszych bitów strony w której znajduje się tablica stron }; struct _PTE { /*Struktura opisująca stronę pamięci */ u16int P:1; //Bit ten określa czy strona jest dostępna u16int RW:1; //Jeżeli bit jest ustawiony, zapis do tej strony jest możliy tylko gdy kod ma poziom uprzywilejowania superwisor( bit U/S=0) i gdy bit WP w cr0 wynosi 0. W przeciwnym wpdaku zapis do strony jest możliwy przez program o uprzywilejowaniu user u16int US:1; //Bit określa poziom uprzywilejowania strony, 0 - poziom najwyższy 1 - poziom użytkownika u16int PWT:1; //Alogrytm pracy pamięci podręcznej u16int PCD:1; u16int A:1; //Bit ten jest ustawiany przez procesor jeżeli doszło do odwołania do stron wksazywanej przez to PTE. u16int D:1; //Bit określa rodzaj odwołania do strony, 0 - operacja odczytu 1 - operacja zapisu u16int Zero:1; //Zawsze 0 u16int G:1; //Bit ma znaczenie wtedy gdy jest ustawiony bit PGE w CR4, jeżeli bit wynosi 1 wtedy wpis PDE istniejący w tablicy TLB nie zostanie usunięty u16int AVL:3; u32int Base:20; // 20 starszych bitów adresu początku ramki }PTE; struct _Tasks { /* Struktura przechowuje informacje na temat procesów */ u32int PID; //Numer ID procesu u32int EntryPoint; //Punkt wejścia do procesu (gównego wątku procesu) u16int CodeSegment; //Selektor segmentu kodu głównego wątku procesu u16int DataSegment; //Selektor segmentu danych głównego wątku procesu u16int StackSegment; //Selektor segmentu stosu głównego wątku procesu uchar State; //Stan procesu. 0 - proces pracuje normalnie,1 - proces w trakcie tworzenia 2- proces zawieszony 3 - proces zombie uchar TickCount; //Zmienna zawiera ilość wykonanych kwantów czasu procesora . Jeżeli przekroczy ustaloną wartość wtedy zadanie zostanie przełączone uchar MaxTick; //Liczba kwantów czasu procesora po przekroczeniu której następuje przełączenie zadania. uchar PrvLevel; //Domyślny poziom uprzywilejowania struct TSSSeg TSS; //"Segment" stanu zadania, TSS struct TSSSeg *TSSNext; //Adres bazowy segmentu stanu następnego zadania struct _PDE PDEDefault; //Domyślne parametry dla tablic stron struct _PTE PTEDefault; //Domyślne parametry dla stron u32int Next; //Index następnego zadania u32int PDBR; // Fizyczny adres katalogu stron,inaczej 20 najstarszych bitów rejestru CR3 u16int PDEsN; // Ilość wpisów w katalogu stron (liczone od 1) u16int PTEsN; //Ilość wpisów w akutalnie ostatnim PDE (liczone od 1) u32int MemSize; //Całkowita wielkość pamięci przydzielona zadaniu (całkowity dostępny adres liniowy) }; //UWAGA!!! : PRZY KAŻDEJ ZMIANIE TEJ STRUKTURY, NALEŻY WYLICZYĆ JEJ WIELKOŚĆ I ZMIENIĆ STAŁĄ SizeOfTaskEntry !!! UWAGA !!! /*extern:*/ /*struktury:*/ extern struct _GDTS GDTS[GDTSMAX]; //Tablica GDT extern struct _IDTS IDTS[IDTSMAX]; //Tablica IDT extern struct _GDTDescr GDTDescr; //pseudodeskryptor GDT extern struct _IDTDescr IDTDescr; //pseudodeskryptor IDT extern struct TSSSeg *ActTaskTSS; //Wskaźnik do segmentu stanu aktualnie wykonywanego zadania extern volatile struct TSSSeg KernelTSS; //Segment stanu zadania 0 extern volatile struct _PDE KernelPDE __attribute__((section( ".KernelPDESect" )aligned(0x2000))); //__attribute__((section (".KernelPDESect"))); //Wpis z katalogiem stron użytkowanym przez jądro, tymczasowo przez proces init i cały system extern volatile struct _PTE KernelPTEs[0x200]; //__attribute__((section (".KernelPTESect"))); //Tablica z stronami zajmowanymi przez system, tymczasowo przez proces init i cały system.*/ /*zmienne globalne:*/ /*Zmienne globalne:*/ extern u16int GDTC; //Ilość wpisów w tablicy GDT extern u32int Frames[0x20000]; //Tablica zawierajaća informację o zajętości ramek. 1 bit opisuje 1 ramkę, czyli 4 KB. Jeden wpis opisuje 32 ramki, czyli 128 KB extern u32int Pages[0x20000]; //Tablica zawierająca informację o stronach przeniesionych do pamięci SWAP extern struct _Tasks Tasks[0xA]; // Tablica zawierająca podstawowe informacje na temat procesów. Wpis nr 0 nie jest procesem -> są to informacje na temat jądra systemu, extern u32int FramesN; //Ilość ramek w tablicy FramesN extern u32int ClosestFreeFrame; //Najbliższa wolna ramka względem ramki nr 0. extern volatile u32int RAMSize; //Całkowita wielkość pamięci RAM extern volatile u32int RAMFree; //Całkowita ilość wolnego miejsca w RAM extern volatile u32int FreeSwapSize; //Ilość wolnego miejsca w pamięci wirtualnej extern volatile u16int KernelSegment; // w Trybie rzeczywistym zawiera segment w którym znajduje się jądro systemu, naotmiast w trybie chronionym jego selektor extern volatile u16int KernelSegmentInRM; //Segment jądra w trybie rzeczywistym extern volatile u16int KernelBase; //Adres fizyczny jądra, KernelSegmentInRM*0x10 extern uchar KernelState; // Stan pracy jądra. 0 - preinit -po wczytaniu a przed zainicjowaniem, 16 bitowy tryb rzeczywisty extern u16int OldCallStack; //Poprzednia wartość zmiennej CallStack extern u16int CallStack; //Stos wywołań procedur systemowych. Zawiera numer aktualnie wykonywanej procedury systemowej. extern volatile u32int TasksN; //Aktualna ilość procesów. extern volatile u32int ActTaskN; //Numer aktualnie wykonywanego zadania w tablicy procesoów extern volatile u32int SwapSize; //Wielkość pamęci SWAP extern volatile uchar ActTaskPrvLevel; // Poziom uprzywilejowania aktualnie wykonywanego zadania. 0 - poziom najwyższy (jądra), 3 - najniższy extern volatile u32int ActTaskTickCount; //Licznik kwantów czasu aktualnego zadania extern volatile u32int ActTaskMaxTick; //Ilość kwantów czasu aktualnego zadania extern uchar TextColor; extern uchar CurX; /*Pozycja kursora na ekranie */ extern uchar CurY; /*Zmienne przechowujące wartości tymczasowe:*/ extern volatile u32int SystemClockEAX; //Zmienna tymczasowo przechowuje wartość rejestru EAX podczas przełączania zadania extern volatile u32int SystemClockESP; //Zmienna tymczasowo przechowuje zawartość rejestru ESP podczas przełączania zadania /*procedury:*/ extern void ChangeFrameBit(u32int FrameN,uchar Bit); /*Procedura ustawia bit zajętości ramki o numerze FrameN,Bit - 0 lub 1 */ extern uchar AllocPages(u32int Task,u32int LinearBaseAddress,struct _PDE *PDEAttributes,struct _PTE *PTEAttributes,u16int PagesN); extern void kprintf(uchar text[],...); /* Standardowa procedura printf z biblioteki stdio.Działa zarówno w trybie rzeczywistym jak i chronionym */ extern void inline EmptyInterrupt(); extern void SystemClock(); /*DO USUNIĘCIA:*/ extern u32int SetClosestFreeFrameBit(); extern volatile struct _PDE KernelPDEA; extern volatile struct _PTE KernelPTEA; extern volatile u16int SystemClockSS;<file_sep>ifeq ($(DEBUG),0) ECHOT = echo "WARNING:!!! WARNING:!!! WARNING:!!! WARNING:!!!\nTo make with debug, please run make DEBUG=1 !!!\n --------------------------------------------------\n " CC = gcc -m32 -O0 -fno-builtin -w # -w bez wyświetlania ostrzeżeń else ECHOT = echo "WARNING:!!! WARNING:!!! WARNING:!!! WARNING:!!!\nTo make without debug, please run make DEBUG=0 !!!\n --------------------------------------------------\n " CC = gcc -m32 -g -O0 -D DEBUG=1 -fno-builtin -w # -w bez wyświetlania ostrzeżeń endif LD = ld -melf_i386 LDdbg = ld -melf_i386 kernel.elf: kernel.c grub.s makefile kernel.ld init.c ./include/bdds.c ./include/mem.c ./include/temp.c ./include/data.h ./include/exceptions.c ./include/tasks.c $(ECHOT) $(CC) ./include/exceptions.c -S -o ./include/exceptions.s $(CC) ./include/exceptions.c -c -o ./include/exceptions.o -Xassembler -a=./include/exceptions.lst $(CC) ./include/bdds.c -S -o ./include/bdds.s $(CC) ./include/bdds.c -c -o ./include/bdds.o -Xassembler -a=./include/bdds.lst $(CC) ./include/mem.c -S -o ./include/mem.s $(CC) ./include/mem.c -c -o ./include/mem.o -Xassembler -a=./include/mem.lst $(CC) ./include/tasks.c -S -o ./include/tasks.s $(CC) ./include/tasks.c -c -o ./include/tasks.o -Xassembler -a=./include/tasks.lst $(CC) init.c -S -o init.s $(CC) init.c -c -o init.o -Xassembler -a=init.lst $(CC) kernel.c -S -o kernel.s $(CC) kernel.c -c -o kernel.o -Xassembler -a=./kernelo.lst nasm grub.s -f elf -o grub.o $(LD) -T kernel.ld -o kernel.elf $(LDdbg) -T kernel.ld -o kerneldbg.o ndisasm -b 32 kernel.elf > kernel.lst clean: rm -f kernel.elf kernel.s kernel.o ./boot/floppy.bin ./include/init.s ./include/bdds.s ./include/init.o ./include/bdds.o ./include/tasks.o ./include/tasks.s /boot/floppy.bin: ./boot/floppy.s makefile nasm ./boot/floppy.s -f bin -o ./boot/floppy.bin tofdd: kernel.elf /boot/floppy.bin makefile -sudo umount ./vfd sudo mount -o loop -t msdos ./a.img ./vfd sudo cp kernel.elf ./vfd/ sudo cp ./boot/menu.cfg ./vfd/boot/menu.cfg -sudo umount ./vfd sudo dd if=./a.img of=/dev/fd0 bs=512 gdb: kernel.elf /boot/floppy.bin makefile -sudo umount ./vfd sudo mount -o loop -t msdos ./a.img ./vfd sudo cp kernel.elf ./vfd/ sudo cp ./boot/menu.cfg ./vfd/boot/menu.cfg -sudo umount ./vfd konsole -workdir /home/wojtek/Dokumenty/programowanie/system/i386 -e bochsgdb -qf bochsrcgdb > xxx.txt gdb -tui bochs: kernel.elf /boot/floppy.bin makefile - sudo umount ./vfd -sudo mount -o loop -t msdos ./a.img ./vfd sudo cp kernel.elf ./vfd/ sudo cp ./boot/menu.cfg ./vfd/boot/menu.cfg -sudo umount ./vfd bochs -qf bochsrc bochsdbg: kernel.elf /boot/floppy.bin makefile - sudo umount ./vfd -sudo mount -o loop -t msdos ./a.img ./vfd sudo cp kernel.elf ./vfd/ sudo cp ./boot/menu.cfg ./vfd/boot/menu.cfg -sudo umount ./vfd bochsdbg -qf bochsrcdbg kdbg: kernel.elf /boot/floppy.bin makefile -sudo umount ./vfd sudo mount -o loop -t msdos ./a.img ./vfd sudo cp kernel.elf ./vfd/ sudo cp ./boot/menu.cfg ./vfd/boot/menu.cfg -sudo umount ./vfd konsole -workdir /home/wojtek/Dokumenty/programowanie/system/i386 -e bochsgdb -qf bochsrcgdb > xxx.txt kdbg -r localhost:1234 kernel.elf <file_sep>/* *************************************************************************************** * kernel.c * * Wersja: pre-alpha * * e-mail:<EMAIL> * * 2014 * *************************************************************************************** Główny plik źródłowy jądra. Scala niektóre pliki z podfolderu include oraz zawiera podstawowe struktury i typy danych systemu. Zawiera całe API jądra dosŧępne dla progamisty. */ #include "./include/data.h" #include <stdarg.h> /*Deklaracje danych jądra. To tutaj zostanie przydzielona pamięć dla nich*/ /*struktury:*/ struct _GDTS GDTS[GDTSMAX]; //Tablica GDT struct _IDTS IDTS[IDTSMAX]; //Tablica IDT struct _GDTDescr GDTDescr; //pseudodeskryptor GDT struct _IDTDescr IDTDescr; //pseudodeskryptor IDT struct _Tasks Tasks[TASKMAX]; // Tablica zawierająca podstawowe informacje na temat procesów. Wpis nr 0 nie jest procesem -> są to informacje na temat jądra systemu, struct TSSSeg *ActTaskTSS; volatile struct _PDE KernelPDEA; volatile struct _PTE KernelPTEA; /*volatile struct _PDE KernelPDE; //Wpis z katalogiem stron użytkowanym przez jądro, tymczasowo przez proces init i cały system volatile struct _PTE KernelPTEs[0x11]; //Tablica z stronami zajmowanymi przez system, tymczasowo przez proces init i cały system.*/ volatile struct _PDE KernelPDE __attribute__((section( ".KernelPDESect" )aligned(0x2000))); volatile struct _PTE KernelPTEs[0x200] __attribute__((section( ".KernelPTESect" )aligned(0x2000))); volatile struct TSSSeg KernelTSS; /*zmienne globalne:*/ /*Zmienne globalne:*/ volatile u32int TasksN=0; u16int GDTC; //Ilość wpisów w tablicy GDT volatile u16int KernelSegmentInRM; //Segment jądra w trybie rzeczywistym volatile u16int KernelBase; //Adres fizyczny jądra, KernelSegmentInRM*0x10 volatile uchar ActTaskPrvLevel; // Poziom uprzywilejowania aktualnie wykonywanego zadania. 0 - poziom najwyższy (jądra), 3 - najniższy uchar KernelState=0; // Stan pracy jądra. 0 - preinit -po wczytaniu a przed zainicjowaniem, 16 bitowy tryb rzeczywisty u16int OldCallStack=0; //Poprzednia wartość zmiennej CallStack u16int CallStack=0; //Stos wywołań procedur systemowych. Zawiera numer aktualnie wykonywanej procedury systemowej. volatile u32int ActTaskN; //Numer aktualnie wykonywanego zadania w tablicy procesoów volatile u32int TasksN; //Aktualna ilość procesów. volatile u32int ActTaskTickCount; //Licznik kwantów czasu aktualnego zadania volatile u32int ActTaskMaxTick; //Ilość kwantów czasu aktualnego zadania /*Zmienne przechowujące wartości tymczasowe:*/ volatile u32int SystemClockEAX; //Zmienna tymczasowo przechowuje wartość rejestru EAX podczas przełączania zadania volatile u32int SystemClockESP; //Zmienna tymczasowo przechowuje zawartość rejestru ESP podczas przełączania zadania inline void outb(u16int port,uchar value) { /* Odpowiednik assemblerowego rozkazu outb. Procedura wysyła wartość value do portu port */ asm volatile ( "outb %0, %1" : : "a"(value), "Nd"(port) ); } inline uchar inb(u16int port) { /* Odpowiednik assemblerowego rozkazu inb. Procedura pobiera wartość z portu port */ uchar ret; asm volatile ( "inb %1, %0" : "=a"(ret) : "Nd"(port) ); return ret; } void DelayLoop(u16int x) { /* Pętla opóźniająca, w istocie zwykła pętla for nie robiąca nic poza zliczaniem. Może być stoswana do opóźnień przy operacjach I/O. X - ilość przebiegów pętli */ u16int temp; for (temp=0; temp != x; temp++) { } } void inline EmptyInterrupt() { /* Pusta procedura obsługi przerywania, nie robi nic poza wyjściem z przerywania. Służy do obsługi przeyrwań sprzętowych nie zablokowanych przez zamaskowanie przerwyań w PIC. Na początku wszytskie przerywania są skierowane na tą procedurę. */ asm("leave\n" "iret\n"); } uchar EditGDTEntry(uchar Index,u32int Size,u32int Base,uchar A,uchar RW,uchar CE,uchar T,uchar S,uchar DPL,uchar P,uchar AVL,uchar D,uchar G) { /* Funkcja edytuje wpis w tablicy GDT. Parametry : index - numer wpisu; Pozostałe parametry zgodne ze znaczeniem parametrów opisanych w strukturze GDTS. Zwracane: 0 - funkcja wykonana poprawnie; 1 - Index > max numer wpisu */ u32int temp; if (Index > GDTSMAX - 1) { return 1; } temp = Size; GDTS[Index].Size1 = temp & 0xFFFF; GDTS[Index].Base1 = Base & 0xFFFF; temp = Base; temp = temp & 0xFF0000; temp = temp >> 16; GDTS[Index].Base2 = temp; GDTS[Index].A = A; GDTS[Index].RW = RW; GDTS[Index].CE = CE; GDTS[Index].T = T; GDTS[Index].S = S; GDTS[Index].DPL = DPL; GDTS[Index].P = P; temp = Size; temp = temp & 0xF0000; temp = temp >> 16; GDTS[Index].Size2 = temp; GDTS[Index].AVL = AVL; GDTS[Index].Zero = 0; GDTS[Index].D = D; GDTS[Index].G = G; temp = Base; temp = temp & 0xFF000000; temp = temp >> 24; return 0; } void BOCHSDBGputc(uchar c) { /* Procedura wyświetla znak w konsoli BOCHS, za pomocą portu 0xE9. Przydatne do debuggowania. C - znak do wyświetlenia */ #if DEBUG == 1 /*Sprawdza czy zadeklarowane jest makro DEBUG i czy jego wartość wynosi. Jeżeli nie wtedy wspomaganie debuggowania jest nie aktywne. DEBUG zazwyczaj definiowane jest już w linii poleceń gcc (-D DEBUG=1), jednak oczywiście możliwe jest także zdefiniowanie w kodzie programu.*/ outb(0xE9,c); #else #endif } void BOCHSDBGprintf(uchar text[],...) {/* Procedura wyświetla tekst w konsoli bochs za pomocą portu 0xE9. Przydatna do debugowania */ #if DEBUG == 1 /*Sprawdza czy zadeklarowane jest makro DEBUG i czy jego wartość wynosi. Jeżeli nie wtedy wspomaganie debuggowania jest nie aktywne. DEBUG zazwyczaj definiowane jest już w linii poleceń gcc (-D DEBUG=1), jednak oczywiście możliwe jest także zdefiniowanie w kodzie programu.*/ uchar IntToStr(u32int value,uchar str[]) { //Funkcja konwertuje integer ze znakiem lub bez na string.Obcina początkowe zera PARAMETRY: value - wartość do przekonwertowania; sign - 0 bez znaku 1 ze znakiem ZWRACANE: Długość liczby; w *str napis z liczbą. uchar temp; u32int temp2=1000000000; u32int value2=value; uchar len=0; uchar c; uchar z=0; // Jeżeli z=0 znaczy że podczas konwersjii nie wystąpiła jeszcze cyfra >0 , a zera są obcinane. for (temp=0; temp <=9; temp++) { c=(value2 / temp2); value2= value2 % temp2; if (c > 0 | z == 1) { z=1; str[len]=c+48; len++; } temp2=temp2 /10; } if (z == 0) { str[0]='0'; return 1; } else return len; } uchar IntToHex(u32int value,uchar Hex[]) { //Funkcja konwertuje integer na hex. Nie dodaje 0x i obcina początkowe 0.PARAMETRY: value - wartość do przekonwertowania. ZWRACANE: Długość liczby; w hex liczba w systemie szesnastkowym uchar temp; u32int temp2=0x10000000; u32int value2=value; uchar len=0; uchar c; uchar z=0; // Jeżeli z=0 znaczy że podczas konwersjii nie wystąpiła jeszcze cyfra >0 , a zera są obcinane. for (temp=0; temp <=7; temp++) { c=(value2 / temp2); value2= value2 % temp2; if (c > 0 | z == 1) { z=1; switch (c) { case 10: Hex[len]='A'; break; case 11: Hex[len]='B'; break; case 12: Hex[len]='C'; break; case 13: Hex[len]='D'; break; case 14: Hex[len]='E'; break; case 15: Hex[len]='F'; break; default: Hex[len]=c+48; break; } len++; } temp2=temp2 /16; } if (z == 0) { Hex[0]='0'; return 1; } else return len; } va_list parg; u16int temp,temp2; uchar ArgStr[11]; uchar *ArgStrP; uchar strlen; uchar paramscount=0; u32int ArgInt; va_start(parg,text); temp=0; temp2=0; strlen=0; ArgInt = 0; for (temp=0;text[temp] != '\0' & temp <= 65535;temp++) { switch (text[temp]) { case '\n': SetCurPos(0,CurY+1); break; case '\r': SetCurPos(0,CurY); break; default: if (text[temp] == '%') { switch (text[temp+1]) { case 'x': ArgInt = va_arg( parg,u32int); strlen = IntToHex(ArgInt,ArgStr); BOCHSDBGputc('0'); BOCHSDBGputc('x'); for (temp2=0;temp2 < strlen;temp2++) { BOCHSDBGputc(ArgStr[temp2]); } break; case 'u': ArgInt = va_arg( parg,u32int); strlen=IntToStr(ArgInt,ArgStr); for (temp2=0;temp2 < strlen;temp2++) { BOCHSDBGputc(ArgStr[temp2]); } break; case 'c': ArgStrP = va_arg( parg,uchar*); for (temp2=0;ArgStrP[temp2] != '\0';temp2++) BOCHSDBGputc(ArgStrP[temp2]); break; default: BOCHSDBGputc('%'); BOCHSDBGputc(text[temp+1]); break; } temp++; } else { BOCHSDBGputc(text[temp]); } break; } } va_end(parg); #else #endif } /*DO USUNIĘCIA:*/ volatile u16int SystemClockSS;<file_sep>/* *********************************************************************************************************** * Bdds32.c * * Wersja:pre-alpha * * e-mail:<EMAIL> * * 2014 * *********************************************************************************************************** Plik aktualnie tymczasowo dołączany do głównego pliku jądra kernel.c, zawierający podstawowe procedury obsługujce podstawowe urządzenia systemowe (ekran, klawiaturę, FDD, PIC,DMA) w 32 bitowym trybie chronionym. Zalążek sterownika Basic Device Drivers.*/ /*Ekran:*/ void printpm(text)char text[]; { /* Procedura wyświetla tekst podany w parametrze text.Działa w trybie chronionym */ char c; static u16int count=0; static uchar x=0; static uchar y=0; u16int temp; GDTS[4].Size1=2000; GDTS[4].Base1=0x8000; GDTS[4].Base2=0xB; GDTS[4].A=0; GDTS[4].RW=1; GDTS[4].CE=0; GDTS[4].T=0; GDTS[4].S=1; GDTS[4].DPL=0; GDTS[4].P=1; GDTS[4].Size2=0; GDTS[4].AVL=0; GDTS[4].Zero=0; GDTS[4].D=1; GDTS[4].G=0; for (temp=0; text[temp] != 0 ; temp++) { c=text[temp]; if (c == "\n" ){ y++; if (y == 25) y=0; } else if (c == "\r") x=0; else { count=80*2*y+2*x; asm( "movw $0x20,%%ax\n" "movw %%ax,%%es\n" //"movw $[cont],%%si\n" "movb %[chr],%%es:(%%si)\n" //"movb $66,%%es:(0)\n" "inc %%si\n" "movb $0x7,%%es:(1)\n" : : [cont] "S"(count), [chr] "r"(c) : "%ax" ); x++; } } } <file_sep>/* *************************************************************************************** * bosch.h * * Wersja: pre-alpha * * e-mail:<EMAIL> * * 2014 * *************************************************************************************** Plik zawiera definicje makr ułatwiające korzystanie z debuggingu w emulatorze Bosch */ #if DEBUG == 1 /*Sprawdza czy zadeklarowane jest makro DEBUG i czy jego wartość wynosi. Jeżeli nie wtedy wspomaganie debuggowania jest nie aktywne. DEBUG zazwyczaj definiowane jest już w linii poleceń gcc (-D DEBUG=1), jednak oczywiście możliwe jest także zdefiniowanie w kodzie programu.*/ #define HALT asm("cli\nhlt"); /*iii*/ #define BOCHSDBG asm("xchg %bx,%bx ; BOCHS DEBUG") ; /*Powoduje zatrzymanie emulatora Bochs i przejście do debuggera */ #else #define BOCHSDBG #endif
f37bc2f773a63ed77b807417465da18ce86fd94e
[ "C", "Makefile" ]
13
C
wojtek2/system
20c0a578a3c9d3e25fedd68e444fa519efa585ae
81ec36b8cd69d83325578532b59ad78904b34bce
refs/heads/master
<file_sep># League of Legends Twitter Bot (in progress but functional) Posts whether or not one of my friends won or lost in a jokingly mean manner. Uses both the riot and the twitter api for this function. It is still in progress because I have not figured out when to update the program as riot's API seems to update irregularly. All work was done by me except for the posting program, made by a man named Nikhil as shown in that part of the program. <file_sep>import json import urllib.parse import urllib.request import sys import TBpost_tweet import time riot_apikey = 'x' #using the riot base url, creates a url for each of my friends which I will post for base_match_url_john = 'https://na1.api.riotgames.com/lol/match/v3/matchlists/by-account/229679480/recent' base_url_john = base_match_url_john + '?' + urllib.parse.urlencode([('api_key', riot_apikey)]) base_match_url_john2 = 'https://na1.api.riotgames.com/lol/match/v3/matchlists/by-account/43475381/recent' base_url_john2 = base_match_url_john2 + '?' + urllib.parse.urlencode([('api_key', riot_apikey)]) base_match_url_chiang = 'https://na1.api.riotgames.com/lol/match/v3/matchlists/by-account/48663455/recent' base_url_chiang = base_match_url_chiang + '?' + urllib.parse.urlencode([('api_key', riot_apikey)]) ''' Exit the program if there is an error with getting the API information. ''' def riot_games_error(): print('Unable to get summoner match list data') sys.exit() def get_json(url: str): ''' turns a given url into a python-readable dictionary using the json library a function given by my ICS 32 Professor, <NAME>, for one of our programming assignments. ''' try: response = urllib.request.urlopen(url) json_text = response.read().decode(encoding = 'utf-8') return json.loads(json_text) except: riot_games_error() finally: if response != None: response.close() def get_match(matchlist_json): ''' Takes the matchlist json of one of the links above and returns the json of the most recent match in the list. ''' specific_match_url = 'https://na1.api.riotgames.com/lol/match/v3/matches/' first_match = matchlist_json['matches'][0] match_url = specific_match_url + str(first_match['gameId']) + '?' + urllib.parse.urlencode([('api_key', riot_apikey)]) return get_json(match_url) def get_win_lose(matchlist_json): ''' Also takes the matchlist json and returns whether or not the person in check won or not. This required a lot of work as I had to find which team the player is on and use that information to find out whether or no they won and return the boolean. ''' first_match = matchlist_json['matches'][0] first_match_championid = first_match['champion'] match_json = get_match(matchlist_json) for player in match_json['participants']: if player['championId'] == first_match_championid: teamId = player['teamId'] break for team in match_json['teams']: if teamId == team['teamId']: return team['win'] def get_participantId(matchlist_json): ''' Takes a matchlist json and reutnr the ID of the participant. This will be used to grab various stats such as kill, deaths, and assists ''' first_match = matchlist_json['matches'][0] first_match_championid = first_match['champion'] match_json = get_match(matchlist_json) for player in match_json['participants']: if player['championId'] == first_match_championid: pId = player['participantId'] break return pId def getDeaths(matchlist_json): ''' Takes the matchlist json and uses it to call multiple functions that eventually returns the player's deaths. ''' match_json = get_match(matchlist_json) partId = get_participantId(matchlist_json) player = match_json['participants'][partId - 1] deaths = player['stats']['deaths'] return deaths def post_tweet(name: str, win_or_loss: str, deaths): ''' Takes whether or not the person won as well as their deaths and posts a rather discouraging tweet on their perfomance. ''' if win_or_loss == "Win": TBpost_tweet.post('Wow, ' +name + ' actually won a game. However, he died ' + str(deaths) + ' times.') else: TBpost_tweet.post('Lmao '+ name+ ' lost. He died ' + str(deaths) + ' times. Feels bad.') def game_is_recent(matchlist_json): ''' This function takes the matchlist json and checks whether a post has already been made. Very difficult as Riot's API seems to update irregularly and I do not want to post the same tweet over and over again. ''' game = matchlist_json['matches'][0] timeOfGame = game['timestamp'] currtime = int(time.time()) * 1000 tenMintoMills = 600000 if (currtime - timeOfGame) <= tenMintoMills: return True return False def execute(): john_matchlist_json = get_json(base_url_john) if game_is_recent(john_matchlist_json): john_winOrLose = get_win_lose(john_matchlist_json) john_deaths = getDeaths(john_matchlist_json) post_tweet('John', john_winOrLose, john_deaths) john2_matchlist_json = get_json(base_url_john2) if game_is_recent(john2_matchlist_json): john2_winOrLose = get_win_lose(john2_matchlist_json) john2_deaths = getDeaths(john2_matchlist_json) post_tweet('John', john2_winOrLose, john2_deaths) chiang_matchlist_json = get_json(base_url_chiang) if game_is_recent(chiang_matchlist_json): chiang_winOrLose = get_win_lose(chiang_matchlist_json) chiang_deaths = getDeaths(chiang_matchlist_json) post_tweet('Chiang', chiang_winOrLose, chiang_deaths) <file_sep>''' Created on Jun 29, 2017 @author: chadd ''' import TBriot_api import time from datetime import datetime if __name__ == '__main__': counter = 0 print('Program starting...') print() #checks for new games every 5 minutes and tells the user how many times it has been executed and the last execution for #debugging purposes. while True: time.sleep(300) TBriot_api.execute() counter += 1 print('Executed ' + str(counter) + ' times.') print('Last api call was on ' + str(datetime.now())) print() print() <file_sep> ''' TAKEN FROM NIKHIL'S BLOG: http://nodotcom.org/python-twitter-tutorial.html A very helpful and simple tutorial on how to post using tweepy. Check out his blog and other such things here: http://nodotcom.org/nikhil-gupta.html ''' import tweepy import os import sys sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) def get_api(config): auth = tweepy.OAuthHandler(config['consumer_key'], config['consumer_secret']) auth.set_access_token(config['access_token'], config['access_token_secret']) return tweepy.API(auth) def post(tweet): config = { "consumer_key" : "x", "consumer_secret" : "x", "access_token" : "x", "access_token_secret" : "x" } api = get_api(config) status = api.update_status(status=tweet)
387b80093034a45466d3dc35b286293b04584ddb
[ "Markdown", "Python" ]
4
Markdown
charlevr/league_twitter_bot
921c5f4895e197f93eae6bc4dfc22918e07dccf4
562e8ee8b228b639af32edab68e47c496d05624e
refs/heads/main
<file_sep>use crate::errors::Error; use crate::traits::FromBytes; use crate::types::header::Header; use crate::types::istanbul::{IstanbulAggregatedSeal, IstanbulExtra, IstanbulExtraVanity}; // Retrieves the block number within an epoch. The return value will be 1-based. // There is a special case if the number == 0. It is basically the last block of the 0th epoch, // and should have a value of epoch_size pub fn get_number_within_epoch(number: u64, epoch_size: u64) -> u64 { let number = number % epoch_size; if number == 0 { epoch_size } else { number } } pub fn get_epoch_number(number: u64, epoch_size: u64) -> u64 { let epoch_number = number / epoch_size; if is_last_block_of_epoch(number, epoch_size) { epoch_number } else { epoch_number + 1 } } pub fn get_epoch_first_block_number(epoch_number: u64, epoch_size: u64) -> Option<u64> { if epoch_number == 0 { // no first block for epoch 0 return None; } Some(((epoch_number - 1) * epoch_size) + 1) } pub fn get_epoch_last_block_number(epoch_number: u64, epoch_size: u64) -> u64 { if epoch_number == 0 { return 0; } // Epoch 0 is just the genesis bock, so epoch 1 starts at block 1 and ends at block epochSize // And from then on, it's epochSize more for each epoch epoch_number * epoch_size } pub fn istanbul_filtered_header(header: &Header, keep_seal: bool) -> Result<Header, Error> { let mut new_header = header.clone(); let mut extra = IstanbulExtra::from_rlp(&new_header.extra)?; if !keep_seal { extra.seal = Vec::new(); } extra.aggregated_seal = IstanbulAggregatedSeal::new(); let payload = extra.to_rlp(IstanbulExtraVanity::from_bytes(&new_header.extra)?); new_header.extra = payload; Ok(new_header) } pub fn is_last_block_of_epoch(number: u64, epoch_size: u64) -> bool { get_number_within_epoch(number, epoch_size) == epoch_size } pub fn min_quorum_size(total_validators: usize) -> usize { // non-float equivalent of: // ((2.0*(total_validators as f64) / 3.0) as f64).ceil() as usize ((2 * total_validators) - 1 + 3) / 3 } #[cfg(test)] mod tests { use super::*; #[test] fn validates_quorum_size_math() { for (validator_set_size, expected_min_quorum_size) in vec![ (1 as usize, 1 as usize), (2, 2), (3, 2), (4, 3), (5, 4), (6, 4), (7, 5), ] .iter() { assert_eq!( min_quorum_size(*validator_set_size), *expected_min_quorum_size ); } } #[test] fn validates_epoch_math() { assert_eq!( vec![ get_epoch_number(0, 3), get_epoch_number(3, 3), get_epoch_number(4, 3) ], vec![0, 1, 2] ); assert_eq!( vec![ get_epoch_first_block_number(0, 3), get_epoch_first_block_number(9, 3) ], vec![None, Some(25)] ); assert_eq!( vec![ get_epoch_last_block_number(0, 3), get_epoch_last_block_number(9, 3) ], vec![0, 27] ); } } <file_sep>use crate::contract::serialization::must_deserialize; use crate::contract::types::ibc::Height; use cosmwasm_std::{to_vec, Env, StdError, StdResult, Storage}; pub const SUBJECT_PREFIX: &'static str = "subject/"; pub const SUBSTITUTE_PREFIX: &'static str = "substitute/"; pub const EMPTY_PREFIX: &'static str = ""; // processed_height_key returns the key under which the processed processed height will be stored in the client store pub fn processed_height_key(prefix: &'static str, height: &Height) -> Vec<u8> { // consensusStates/ path is defined in ICS 24 format!( "{}consensusStates/{}-{}/processedHeight", prefix, height.revision_number, height.revision_height ) .as_bytes() .to_owned() } // processed_time_key returns the key under which the processed time will be stored in the client store pub fn processed_time_key(prefix: &'static str, height: &Height) -> Vec<u8> { // consensusStates/ path is defined in ICS 24 format!( "{}consensusStates/{}-{}/processedTime", prefix, height.revision_number, height.revision_height ) .as_bytes() .to_owned() } // consensus_state_key returns the key under which the consensys state will be stored in the client store pub fn consensus_state_key(prefix: &'static str, height: &Height) -> Vec<u8> { // consensusStates/ path is defined in ICS 24 format!( "{}consensusStates/{}-{}", prefix, height.revision_number, height.revision_height ) .as_bytes() .to_owned() } // set_processed_height stores the height at which a header was processed and the corresponding consensus state was created. // This is useful when validating whether a packet has reached the specified block delay period in the light client's // verification functions fn set_processed_height( storage: &mut dyn Storage, prefix: &'static str, consensus_height: &Height, processed_height: &Height, ) -> StdResult<()> { let key = processed_height_key(prefix, consensus_height); storage.set(&key, &to_vec(processed_height)?); Ok(()) } // get_processed_time gets the height at which this chain received and processed a celo header. // This is used to validate that a received packet has passed the block delay period. pub fn get_processed_height( storage: &dyn Storage, prefix: &'static str, height: &Height, ) -> StdResult<Height> { let key = processed_height_key(prefix, height); must_deserialize(&storage.get(&key)) } // set_processed_time stores the time at which a header was processed and the corresponding consensus state was created. // This is useful when validating whether a packet has reached the specified delay period in the // light client's verification functions fn set_processed_time( storage: &mut dyn Storage, prefix: &'static str, height: &Height, time: &u64, ) -> StdResult<()> { let key = processed_time_key(prefix, height); storage.set(&key, &to_vec(time)?); Ok(()) } // get_processed_time gets the time (in nanoseconds) at which this chain recieved and processed a celo header. // This is used to validate that a recieved packet has passed the delay period pub fn get_processed_time( storage: &dyn Storage, prefix: &'static str, height: &Height, ) -> StdResult<u64> { let key = processed_time_key(prefix, height); must_deserialize(&storage.get(&key)) } pub fn set_consensus_meta( env: &Env, storage: &mut dyn Storage, prefix: &'static str, height: &Height, ) -> StdResult<()> { set_processed_time(storage, prefix, height, &env.block.time)?; set_processed_height(storage, prefix, height, &get_self_height(env.block.height))?; Ok(()) } pub fn get_consensus_state( storage: &dyn Storage, prefix: &'static str, height: &Height, ) -> StdResult<Vec<u8>> { let key = consensus_state_key(prefix, height); match storage.get(&key) { Some(vec) => Ok(vec), None => Err(StdError::not_found("consensus state not found")), } } pub fn set_consensus_state( storage: &mut dyn Storage, prefix: &'static str, height: &Height, bytes: &Vec<u8>, ) -> StdResult<()> { let key = consensus_state_key(prefix, height); storage.set(&key, &to_vec(bytes)?); Ok(()) } pub fn get_self_height(block_height: u64) -> Height { Height{ revision_number: 0, revision_height: block_height, } } <file_sep>use crate::bls::verify_aggregated_seal; use crate::errors::{Error, Kind}; use crate::istanbul::is_last_block_of_epoch; use crate::traits::StateConfig; use crate::types::header::{Address, Header}; use crate::types::istanbul::IstanbulExtra; use crate::types::state::{Snapshot, Validator}; use num::cast::ToPrimitive; use num_bigint::BigInt as Integer; use num_traits::Zero; use std::collections::HashMap; /// State takes care of managing the IBFT consensus state pub struct State<'a> { snapshot: Snapshot, config: &'a dyn StateConfig, } impl<'a> State<'a> { pub fn new(snapshot: Snapshot, config: &'a dyn StateConfig) -> Self { State { snapshot, config } } pub fn snapshot(&self) -> &Snapshot { &self.snapshot } pub fn add_validators(&mut self, validators: Vec<Validator>) -> bool { let mut new_address_map: HashMap<Address, bool> = HashMap::new(); for validator in validators.iter() { new_address_map.insert(validator.address, true); } // Verify that the validators to add is not already in the valset for v in self.snapshot.validators.iter() { if new_address_map.contains_key(&v.address) { return false; } } self.snapshot.validators.extend(validators); return true; } pub fn remove_validators(&mut self, removed_validators: &Integer) -> bool { if removed_validators.bits() == 0 { return true; } if removed_validators.bits() > self.snapshot.validators.len() as u64 { return false; } let filtered_validators: Vec<Validator> = self .snapshot .validators .iter() .enumerate() .filter(|(i, _)| removed_validators.bit(*i as u64) == false) .map(|(_, v)| v.to_owned()) .collect(); self.snapshot.validators = filtered_validators; return true; } pub fn verify_header(&self, header: &Header, current_timestamp: u64) -> Result<(), Error> { // assert header height is newer than any we know if !(header.number.to_u64().unwrap() > self.snapshot.number) { return Err(Kind::HeaderVerificationError { msg: "header height should be greater than the last one stored in state", } .into()); } if self.config.verify_header_timestamp() { // assert header timestamp is past current timestamp if !(header.time > self.snapshot.timestamp) { return Err(Kind::HeaderVerificationError { msg: "header timestamp should be greater than the last one stored in state", } .into()); } // don't waste time checking blocks from the future if header.time > current_timestamp + self.config.allowed_clock_skew() { return Err(Kind::HeaderVerificationError { msg: "header timestamp is set too far in the future", } .into()); } } self.verify_header_seal(&header) } pub fn verify_header_seal(&self, header: &Header) -> Result<(), Error> { let header_hash = header.hash()?; let extra = IstanbulExtra::from_rlp(&header.extra)?; verify_aggregated_seal( header_hash, &self.snapshot.validators, &extra.aggregated_seal, ) } pub fn insert_header(&mut self, header: &Header, current_timestamp: u64) -> Result<(), Error> { let block_num = header.number.to_u64().unwrap(); if is_last_block_of_epoch(block_num, self.config.epoch_size()) { // The validator set is about to be updated with epoch header self.store_epoch_header(header, current_timestamp) } else { // Validator set is not being updated self.store_non_epoch_header(header, current_timestamp) } } fn store_non_epoch_header( &mut self, header: &Header, current_timestamp: u64, ) -> Result<(), Error> { // genesis block is valid dead end if self.config.verify_non_epoch_headers() && !header.number.is_zero() { self.verify_header(&header, current_timestamp)? } let extra = IstanbulExtra::from_rlp(&header.extra)?; let snapshot = Snapshot { // The validator state stays unchanged (ONLY updated with epoch header) validators: self.snapshot.validators.clone(), // Update the header related fields number: header.number.to_u64().unwrap(), timestamp: header.time, hash: header.hash()?, aggregated_seal: extra.aggregated_seal.clone(), }; self.update_state_snapshot(snapshot) } fn store_epoch_header(&mut self, header: &Header, current_timestamp: u64) -> Result<(), Error> { // genesis block is valid dead end if self.config.verify_epoch_headers() && !header.number.is_zero() { self.verify_header(&header, current_timestamp)? } let header_hash = header.hash()?; let extra = IstanbulExtra::from_rlp(&header.extra)?; // convert istanbul validators into a Validator struct let mut validators: Vec<Validator> = Vec::new(); if extra.added_validators.len() != extra.added_validators_public_keys.len() { return Err(Kind::InvalidValidatorSetDiff { msg: "error in combining addresses and public keys", } .into()); } for i in 0..extra.added_validators.len() { validators.push(Validator { address: extra.added_validators[i].clone(), public_key: extra.added_validators_public_keys[i].clone(), }) } // apply the header's changeset let result_remove = self.remove_validators(&extra.removed_validators); if !result_remove { return Err(Kind::InvalidValidatorSetDiff { msg: "error in removing the header's removed_validators", } .into()); } let result_add = self.add_validators(validators); if !result_add { return Err(Kind::InvalidValidatorSetDiff { msg: "error in adding the header's added_validators", } .into()); } let snapshot = Snapshot { number: header.number.to_u64().unwrap(), timestamp: header.time, validators: self.snapshot.validators.clone(), hash: header_hash, aggregated_seal: extra.aggregated_seal, }; self.update_state_snapshot(snapshot) } fn update_state_snapshot(&mut self, snapshot: Snapshot) -> Result<(), Error> { // NOTE: right now we store only the last state entry but we could add // a feature to store X past entries for querying / debugging // update local state self.snapshot = snapshot; Ok(()) } } #[cfg(test)] mod tests { use super::*; use crate::traits::{DefaultFrom, FromBytes, FromRlp}; use crate::types::header::{Hash, ADDRESS_LENGTH}; use crate::types::istanbul::{IstanbulAggregatedSeal, SerializedPublicKey}; use crate::types::state::Config; use secp256k1::{rand::rngs::OsRng, PublicKey, Secp256k1, SecretKey}; use sha3::{Digest, Keccak256}; use std::{cmp, cmp::Ordering}; macro_rules! string_vec { ($($x:expr),*) => (vec![$($x.to_string()),*]); } struct TestValidatorSet { validators: Vec<String>, validator_set_diffs: Vec<ValidatorSetDiff>, results: Vec<String>, } struct ValidatorSetDiff { added_validators: Vec<String>, removed_validators: Vec<String>, } struct AccountPool { pub accounts: HashMap<String, (SecretKey, PublicKey)>, } fn state_config() -> Config { Config { epoch_size: 123, allowed_clock_skew: 123, verify_epoch_headers: true, verify_non_epoch_headers: true, verify_header_timestamp: true, } } impl AccountPool { fn new() -> Self { Self { accounts: HashMap::new(), } } fn address(&mut self, account: String) -> Address { if account == "" { return Address::default(); } if !self.accounts.contains_key(&account) { self.accounts.insert(account.clone(), generate_key()); } pubkey_to_address(self.accounts.get(&account).unwrap().1) } } #[test] fn test_encode_state_snapshot() { let snapshot = Snapshot { validators: vec![ Validator { address: Address::default(), public_key: SerializedPublicKey::default(), }, Validator { address: Address::default(), public_key: SerializedPublicKey::default(), }, ], timestamp: 123456, number: 456, hash: Hash::default(), aggregated_seal: IstanbulAggregatedSeal::new(), }; let encoded = rlp::encode(&snapshot); let decoded = Snapshot::from_rlp(&encoded).unwrap(); assert_eq!(snapshot, decoded); } #[test] fn test_add_remove() { let snapshot = Snapshot::new(); let config = state_config(); let mut state = State::new(snapshot, &config); let mut result = state.add_validators(vec![Validator { address: bytes_to_address(&vec![0x3 as u8]), public_key: SerializedPublicKey::default(), }]); assert_eq!(result, true); result = state.add_validators(vec![ Validator { address: bytes_to_address(&vec![0x2 as u8]), public_key: SerializedPublicKey::default(), }, Validator { address: bytes_to_address(&vec![0x1 as u8]), public_key: SerializedPublicKey::default(), }, ]); assert_eq!(result, true); assert_eq!(state.snapshot.validators.len(), 3); // verify ordering let current_addresses: Vec<Address> = state .snapshot .validators .iter() .map(|val| val.address) .collect(); let expecected_addresses: Vec<Address> = vec![ bytes_to_address(&vec![0x3 as u8]), bytes_to_address(&vec![0x2 as u8]), bytes_to_address(&vec![0x1 as u8]), ]; assert_eq!(current_addresses, expecected_addresses); // remove first validator result = state.remove_validators(&Integer::from(1)); assert_eq!(result, true); assert_eq!(state.snapshot.validators.len(), 2); // remove second validator result = state.remove_validators(&Integer::from(2)); assert_eq!(result, true); assert_eq!(state.snapshot.validators.len(), 1); // remove third validator result = state.remove_validators(&Integer::from(1)); assert_eq!(result, true); assert_eq!(state.snapshot.validators.len(), 0); } #[test] fn applies_validator_set_changes() { let tests = vec![ // Single validator, empty val set diff TestValidatorSet { validators: string_vec!["A"], validator_set_diffs: vec![ValidatorSetDiff { added_validators: Vec::new(), removed_validators: Vec::new(), }], results: string_vec!["A"], }, // Single validator, add two new validators TestValidatorSet { validators: string_vec!["A"], validator_set_diffs: vec![ValidatorSetDiff { added_validators: string_vec!["B", "C"], removed_validators: Vec::new(), }], results: string_vec!["A", "B", "C"], }, // Two validator, remove two validators TestValidatorSet { validators: string_vec!["A", "B"], validator_set_diffs: vec![ValidatorSetDiff { added_validators: Vec::new(), removed_validators: string_vec!["A", "B"], }], results: string_vec![], }, // Three validator, add two validators and remove two validators TestValidatorSet { validators: string_vec!["A", "B", "C"], validator_set_diffs: vec![ValidatorSetDiff { added_validators: string_vec!["D", "E"], removed_validators: string_vec!["B", "C"], }], results: string_vec!["A", "D", "E"], }, // Three validator, add two validators and remove two validators. Second header will add 1 validators and remove 2 validators. TestValidatorSet { validators: string_vec!["A", "B", "C"], validator_set_diffs: vec![ ValidatorSetDiff { added_validators: string_vec!["D", "E"], removed_validators: string_vec!["B", "C"], }, ValidatorSetDiff { added_validators: string_vec!["F"], removed_validators: string_vec!["A", "D"], }, ], results: string_vec!["F", "E"], }, ]; for test in tests { let snapshot = Snapshot::new(); let config = state_config(); let mut accounts = AccountPool::new(); let mut state = State::new(snapshot, &config); let validators = convert_val_names_to_validators(&mut accounts, test.validators); state.add_validators(validators.clone()); for diff in test.validator_set_diffs { let added_validators = convert_val_names_to_validators(&mut accounts, diff.added_validators); let removed_validators = convert_val_names_to_removed_validators( &mut accounts, &state.snapshot.validators, diff.removed_validators, ); state.remove_validators(&removed_validators); state.add_validators(added_validators); } let results = convert_val_names_to_validators(&mut accounts, test.results); assert_eq!(compare(state.snapshot.validators, results), Ordering::Equal); } } pub fn compare(a: Vec<Validator>, b: Vec<Validator>) -> cmp::Ordering { let mut sorted_a = a.clone(); let mut sorted_b = b.clone(); sorted_a.sort_by(|a, b| b.address.cmp(&a.address)); sorted_b.sort_by(|a, b| b.address.cmp(&a.address)); sorted_a .iter() .zip(sorted_b) .map(|(x, y)| x.address.cmp(&y.address)) .find(|&ord| ord != cmp::Ordering::Equal) .unwrap_or(a.len().cmp(&b.len())) } fn pubkey_to_address(p: PublicKey) -> Address { let pub_bytes = p.serialize_uncompressed(); let digest = &Keccak256::digest(&pub_bytes[1..])[12..]; Address::from_bytes(digest).unwrap().to_owned() } fn bytes_to_address(bytes: &[u8]) -> Address { let mut v = vec![0x0; ADDRESS_LENGTH - bytes.len()]; v.extend_from_slice(bytes); Address::from_bytes(&v).unwrap().to_owned() } fn generate_key() -> (SecretKey, PublicKey) { let mut rng = OsRng::new().expect("OsRng"); let secp = Secp256k1::new(); secp.generate_keypair(&mut rng) } fn convert_val_names_to_validators( accounts: &mut AccountPool, val_names: Vec<String>, ) -> Vec<Validator> { val_names .iter() .map(|name| Validator { address: accounts.address(name.to_string()), public_key: SerializedPublicKey::default(), }) .collect() } fn convert_val_names_to_removed_validators( accounts: &mut AccountPool, old_validators: &[Validator], val_names: Vec<String>, ) -> Integer { let mut bitmap = Integer::from(0); for v in val_names { for j in 0..old_validators.len() { if &accounts.address(v.to_string()) == &old_validators.get(j).unwrap().address { bitmap.set_bit(j as u64, true); } } } bitmap } } <file_sep>use crate::errors::{Error, Kind}; use crate::istanbul::istanbul_filtered_header; use crate::serialization::rlp::{ big_int_to_rlp_compat_bytes, rlp_list_field_from_bytes, rlp_to_big_int, }; use crate::slice_as_array_ref; use crate::traits::{DefaultFrom, FromBytes, FromRlp, ToRlp}; use crate::types::istanbul::ISTANBUL_EXTRA_VANITY_LENGTH; use num_bigint::BigInt as Integer; use rlp::{Decodable, DecoderError, Encodable, Rlp, RlpStream}; use sha3::{Digest, Keccak256}; /// HASH_LENGTH represents the number of bytes used in a header hash pub const HASH_LENGTH: usize = 32; /// ADDRESS_LENGTH represents the number of bytes used in a header Ethereum account address pub const ADDRESS_LENGTH: usize = 20; /// BLOOM_BYTE_LENGTH represents the number of bytes used in a header log bloom pub const BLOOM_BYTE_LENGTH: usize = 256; /// Hash is the output of the cryptographic digest function pub type Hash = [u8; HASH_LENGTH]; /// Address represents the 20 byte address of an Ethereum account pub type Address = [u8; ADDRESS_LENGTH]; /// Bloom represents a 2048 bit bloom filter pub type Bloom = [u8; BLOOM_BYTE_LENGTH]; /// Header contains block metadata in Celo Blockchain #[derive(Serialize, Deserialize, Clone, PartialEq, Debug)] #[serde(rename_all = "camelCase")] pub struct Header { #[serde(with = "crate::serialization::bytes::hexstring")] pub parent_hash: Hash, #[serde(with = "crate::serialization::bytes::hexstring")] #[serde(rename = "miner")] pub coinbase: Address, #[serde(with = "crate::serialization::bytes::hexstring")] #[serde(rename = "stateRoot")] pub root: Hash, #[serde(with = "crate::serialization::bytes::hexstring")] #[serde(rename = "transactionsRoot")] pub tx_hash: Hash, #[serde(with = "crate::serialization::bytes::hexstring")] #[serde(rename = "receiptsRoot")] pub receipt_hash: Hash, #[serde(with = "crate::serialization::bytes::hexstring")] #[serde(rename = "logsBloom")] pub bloom: Bloom, #[serde(with = "crate::serialization::bytes::hexbigint")] pub number: Integer, #[serde(with = "crate::serialization::bytes::hexnum")] pub gas_used: u64, #[serde(rename = "timestamp")] #[serde(with = "crate::serialization::bytes::hexnum")] pub time: u64, #[serde(with = "crate::serialization::bytes::hexstring")] #[serde(rename = "extraData")] pub extra: Vec<u8>, } impl Header { pub fn new() -> Self { Self { parent_hash: Hash::default(), coinbase: Address::default(), root: Hash::default(), tx_hash: Hash::default(), receipt_hash: Hash::default(), bloom: Bloom::default(), number: Integer::default(), gas_used: u64::default(), time: u64::default(), extra: Vec::default(), } } pub fn hash(&self) -> Result<Hash, Error> { if self.extra.len() >= ISTANBUL_EXTRA_VANITY_LENGTH { let istanbul_header = istanbul_filtered_header(&self, true); if istanbul_header.is_ok() { return rlp_hash(&istanbul_header?); } } rlp_hash(self) } } impl FromRlp for Header { fn from_rlp(bytes: &[u8]) -> Result<Self, Error> { rlp::decode(&bytes).map_err(|e| Kind::RlpDecodeError.context(e).into()) } } impl ToRlp for Header { fn to_rlp(&self) -> Vec<u8> { rlp::encode(self) } } impl Encodable for Header { fn rlp_append(&self, s: &mut RlpStream) { s.begin_list(10); // parent_hash s.append(&self.parent_hash.as_ref()); // coinbase s.append(&self.coinbase.as_ref()); // root s.append(&self.root.as_ref()); // tx_hash s.append(&self.tx_hash.as_ref()); // receipt_hash s.append(&self.receipt_hash.as_ref()); // bloom s.append(&self.bloom.as_ref()); // number s.append(&big_int_to_rlp_compat_bytes(&self.number)); // gas_used s.append(&self.gas_used); // time s.append(&self.time); // extra s.append(&self.extra); } } impl Decodable for Header { fn decode(rlp: &Rlp) -> Result<Self, DecoderError> { Ok(Header { parent_hash: rlp_list_field_from_bytes(rlp, 0)?, coinbase: rlp_list_field_from_bytes(rlp, 1)?, root: rlp_list_field_from_bytes(rlp, 2)?, tx_hash: rlp_list_field_from_bytes(rlp, 3)?, receipt_hash: rlp_list_field_from_bytes(rlp, 4)?, bloom: rlp_list_field_from_bytes(rlp, 5)?, number: rlp_to_big_int(rlp, 6)?, gas_used: rlp.val_at(7)?, time: rlp.val_at(8)?, extra: rlp.val_at(9)?, }) } } impl DefaultFrom for Bloom { fn default() -> Self { [0; BLOOM_BYTE_LENGTH] } } impl FromBytes for Bloom { fn from_bytes(data: &[u8]) -> Result<&Bloom, Error> { slice_as_array_ref!(&data[..BLOOM_BYTE_LENGTH], BLOOM_BYTE_LENGTH) } } impl FromBytes for Address { fn from_bytes(data: &[u8]) -> Result<&Address, Error> { slice_as_array_ref!(&data[..ADDRESS_LENGTH], ADDRESS_LENGTH) } } fn rlp_hash(header: &Header) -> Result<Hash, Error> { let digest = Keccak256::digest(&rlp::encode(header)); Ok(slice_as_array_ref!(&digest[..HASH_LENGTH], HASH_LENGTH)?.to_owned()) } #[cfg(test)] mod tests { use super::*; const HEADER_WITH_EMPTY_EXTRA: &str = "f901a6a07285abd5b24742f184ad676e31f6054663b3529bc35ea2fcad8a3e0f642a46f7948888f1f195afa192cfee860698584c030f4c9db1a0ecc60e00b3fe5ce9f6e1a10e5469764daf51f1fe93c22ec3f9a7583a80357217a0d35d334d87c0cc0a202e3756bf81fae08b1575f286c7ee7a3f8df4f0f3afc55da056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421b901000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001825208845c47775c80"; const IST_EXTRA: &str = "0000000000000000000000000000000000000000000000000000000000000000f89af8549444add0ec310f115a0e603b2d7db9f067778eaf8a94294fc7e8f22b3bcdcf955dd7ff3ba2ed833f8212946beaaed781d2d2ab6350f5c4566a2c6eaac407a6948be76812f765c24641ec63dc2852b378aba2b440b8410000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000c0"; #[test] fn encodes_header_to_rlp() { let bytes = hex::decode(&HEADER_WITH_EMPTY_EXTRA).unwrap(); let header = Header::from_rlp(&bytes).unwrap(); let encoded_bytes = header.to_rlp(); assert_eq!(encoded_bytes, bytes); } #[test] fn decodes_header_from_rlp() { let expected = vec![Header { parent_hash: to_hash( "7285abd5b24742f184ad676e31f6054663b3529bc35ea2fcad8a3e0f642a46f7", ), coinbase: to_hash("8888f1f195afa192cfee860698584c030f4c9db1"), root: to_hash("ecc60e00b3fe5ce9f6e1a10e5469764daf51f1fe93c22ec3f9a7583a80357217"), tx_hash: to_hash("d35d334d87c0cc0a202e3756bf81fae08b1575f286c7ee7a3f8df4f0f3afc55d"), receipt_hash: to_hash( "56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421", ), bloom: Bloom::default(), number: Integer::from(1), gas_used: 0x5208, time: 0x5c47775c, extra: Vec::default(), }]; for (bytes, expected_ist) in vec![hex::decode(&HEADER_WITH_EMPTY_EXTRA).unwrap()] .iter() .zip(expected) { let parsed = Header::from_rlp(&bytes).unwrap(); assert_eq!(parsed, expected_ist); } } #[test] fn serializes_and_deserializes_to_json() { for bytes in vec![hex::decode(&HEADER_WITH_EMPTY_EXTRA).unwrap()].iter() { let parsed = Header::from_rlp(&bytes).unwrap(); let json_string = serde_json::to_string(&parsed).unwrap(); let deserialized_from_json: Header = serde_json::from_str(&json_string).unwrap(); assert_eq!(parsed, deserialized_from_json); } } #[test] fn generates_valid_header_hash() { for (extra_bytes, hash_str) in vec![( IST_EXTRA, "5c012c65d46edfbfca86a426da5111c51114b75577fec9b82161d3e05d83b723", )] .iter() { let expected_hash: Hash = Hash::from_bytes(&hex::decode(hash_str).unwrap()) .unwrap() .to_owned(); let mut header = Header::new(); header.extra = hex::decode(&extra_bytes).unwrap(); // for istanbul consensus assert_eq!(header.hash().unwrap(), expected_hash); // append useless information to extra-data header.extra.extend(vec![1, 2, 3]); assert_eq!(header.hash().unwrap(), rlp_hash(&header).unwrap()); } } pub fn to_hash<T>(data: &str) -> T where T: FromBytes + Clone, { T::from_bytes(&hex::decode(data).unwrap()) .unwrap() .to_owned() } } <file_sep>//! This library contains a portion of Celo Blockchain logic and structures, that is primarily //! used by Celo Light client contract deployed on Cosmos Network. //! //! In particular, the library provides the LightestSync method to quickly, securely and cheaply //! synchronize IBFT consensus state with Celo chain. mod types; mod serialization; mod state; mod istanbul; mod bls; mod traits; mod macros; mod errors; #[macro_use] extern crate serde; extern crate rlp; extern crate num_bigint; extern crate sha3; extern crate bls_crypto; extern crate algebra; extern crate anomaly; extern crate thiserror; pub use types::{ header::Header, header::Address, header::Hash, istanbul::SerializedPublicKey, istanbul::IstanbulExtra, state::Validator, state::Snapshot, state::Config }; pub use istanbul::{ get_epoch_number, get_epoch_first_block_number, get_epoch_last_block_number, }; pub use state::State; pub use errors::{Error, Kind}; pub use traits::{ FromBytes, DefaultFrom, ToRlp, FromRlp }; pub use bls::verify_aggregated_seal; #[cfg(feature = "wasm-contract")] pub mod contract; #[cfg(all(feature = "wasm-contract", target_arch = "wasm32"))] cosmwasm_std::create_entry_points!(contract); <file_sep>use crate::contract::util::to_generic_err; use cosmwasm_std::StdError; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use std::cmp::Ordering; // This file defines core IBC structures required by the light client contract. // // It would be great if we could reuse types from other library (ie. `ibc-rs`), but: // * Go serializes []byte as base64 string (additional step required: base64::decode(data) -> Vec<u8>) // * Deriving JsonSchema via prost isn't possible (JsonSchema's required by cosmwasm) // // Therefore the selected structures have been copied and modified as needed. // Some types are not being serialized/deserialized by contract, therefore are used as-is. pub type Sequence = ibc::ics04_channel::packet::Sequence; pub type ChannelId = ibc::ics24_host::identifier::ChannelId; pub type ClientId = ibc::ics24_host::identifier::ClientId; pub type ConnectionId = ibc::ics24_host::identifier::ConnectionId; pub type PortId = ibc::ics24_host::identifier::PortId; pub type Path = ibc::ics24_host::Path; pub type ClientUpgradePath = ibc::ics24_host::ClientUpgradePath; // Origin: ibc.core.connection.v1 (compiled proto) #[derive(Serialize, Deserialize, JsonSchema, Clone, PartialEq, Debug)] pub struct ConnectionEnd { client_id: String, versions: Vec<Version>, state: i32, counterparty: Counterparty, delay_period: u64, } // Origin: ibc.core.connection.v1 (compiled proto) #[derive(Serialize, Deserialize, JsonSchema, Clone, PartialEq, Debug)] pub struct Counterparty { pub client_id: String, pub connection_id: String, pub prefix: MerklePrefix, } // Origin: ibc.core.connection.v1 (compiled proto) #[derive(Serialize, Deserialize, JsonSchema, Clone, PartialEq, Debug)] pub struct Version { pub identifier: String, pub features: Vec<String>, } // Origin: ibc.core.channel.v1 (compiled proto) #[derive(Serialize, Deserialize, JsonSchema, Clone, PartialEq, Debug)] pub struct Channel { pub state: i32, pub ordering: i32, pub counterparty: Counterparty, pub connection_hops: Vec<String>, pub version: String, } // Origin: ibc.core.commitment.v1 (compiled proto) #[derive(Serialize, Deserialize, JsonSchema, Clone, PartialEq, Debug)] pub struct MerklePrefix { pub key_prefix: String, // Go serializes []byte to base64 encoded string } // Origin: ibc.core.commitment.v1 (compiled proto) #[derive(Serialize, Deserialize, JsonSchema, Clone, PartialEq, Debug)] pub struct MerkleRoot { pub hash: String, // Go serializes []byte to base64 encoded string } // Origin: ibc.core.commitment.v1 (compiled proto) #[derive(Serialize, Deserialize, JsonSchema, Clone, PartialEq, Debug)] pub struct MerklePath { pub key_path: Vec<String>, } // Origin: ibc.core.commitment.v1 (compiled proto mixed with ics23 crate) #[derive(Serialize, Deserialize, Clone, PartialEq, Debug)] pub struct MerkleProof { pub proofs: Vec<ics23::CommitmentProof>, } // Origin: ibc-rs/modules/src/ics02_client/height.rs (added JsonSchema and serde defaults) #[derive(Serialize, Deserialize, JsonSchema, Clone, PartialEq, Debug, Eq, Copy)] pub struct Height { #[serde(default)] pub revision_number: u64, #[serde(default)] pub revision_height: u64, } impl PartialOrd for Height { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } } impl Ord for Height { fn cmp(&self, other: &Self) -> Ordering { if self.revision_number < other.revision_number { Ordering::Less } else if self.revision_number > other.revision_number { Ordering::Greater } else if self.revision_height < other.revision_height { Ordering::Less } else if self.revision_height > other.revision_height { Ordering::Greater } else { Ordering::Equal } } } impl std::fmt::Display for Height { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> { write!( f, "revision: {}, height: {}", self.revision_number, self.revision_height ) } } // Origin: cosmos-sdk/x/ibc/core/23-commitment/types/merkle.go (ported) pub fn apply_prefix(prefix: &MerklePrefix, mut path: Vec<String>) -> Result<MerklePath, StdError> { if prefix.key_prefix.len() == 0 { return Err(to_generic_err("empty prefix")); } let prefix_from_base64 = base64::decode(&prefix.key_prefix).map_err(|e| to_generic_err(e))?; let decoded_prefix = std::str::from_utf8(&prefix_from_base64).map_err(|e| to_generic_err(e))?; let mut result: Vec<String> = vec![decoded_prefix.to_string()]; result.append(&mut path); Ok(MerklePath { key_path: result }) } // Origin: cosmos-sdk/x/ibc/core/23-commitment/types/merkle.go (ported) pub fn verify_membership( proof: &MerkleProof, specs: &[ics23::ProofSpec], root: &Vec<u8>, keys: &MerklePath, mut value: Vec<u8>, index: usize, ) -> Result<bool, StdError> { let mut subroot = value.clone(); for (i, commitment_proof) in proof.proofs.iter().skip(index).enumerate() { if let Some(ex) = get_exist_proof(commitment_proof) { subroot = ics23::calculate_existence_root(&ex).map_err(|e| to_generic_err(e))?; let key = match keys.key_path.get(keys.key_path.len() - 1 - i) { Some(key) => key, None => return Err(StdError::generic_err("could not retrieve key bytes")), }; if !ics23::verify_membership( &commitment_proof, &specs[i], &subroot, key.as_bytes(), &value, ) { return Err(StdError::generic_err(format!( "membership proof failed to verify membership of value: {:?} in subroot: {:?}", value, subroot ))); } value = subroot.clone(); } else { return Err(StdError::generic_err( "expected proof type: ics23::ExistenceProof", )); } } if !root.iter().eq(subroot.iter()) { return Err(StdError::generic_err(format!( "proof did not commit to expected root: {:?}, got: {:?}", root, subroot ))); } Ok(true) } fn get_exist_proof<'a>(proof: &'a ics23::CommitmentProof) -> Option<&'a ics23::ExistenceProof> { match &proof.proof { Some(ics23::commitment_proof::Proof::Exist(ex)) => Some(ex), _ => None, } } <file_sep>use crate::contract::types::ibc::{Channel, ConnectionEnd, Height, MerklePrefix}; use crate::contract::types::wasm::{ ClientState, ConsensusState, CosmosClientState, CosmosConsensusState, Misbehaviour, Status, WasmHeader, }; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, JsonSchema)] #[serde(rename_all = "lowercase")] pub enum HandleMsg { InitializeState { consensus_state: ConsensusState, me: ClientState, }, CheckHeaderAndUpdateState { header: WasmHeader, consensus_state: ConsensusState, me: ClientState, }, VerifyUpgradeAndUpdateState { me: ClientState, new_client_state: ClientState, new_consensus_state: ConsensusState, client_upgrade_proof: String, // Go serializes []byte to base64 encoded string consensus_state_upgrade_proof: String, // Go serializes []byte to base64 encoded string last_height_consensus_state: ConsensusState, }, CheckMisbehaviourAndUpdateState { me: ClientState, misbehaviour: Misbehaviour, consensus_state_1: ConsensusState, consensus_state_2: ConsensusState, }, CheckSubstituteAndUpdateState { me: ClientState, substitute_client_state: ClientState, subject_consensus_state: ConsensusState, initial_height: Height, }, ZeroCustomFields { me: ClientState, }, } #[derive(Serialize, Deserialize, Clone, PartialEq, Debug, JsonSchema)] pub struct ClientStateCallResponse { pub me: ClientState, pub result: ClientStateCallResponseResult, pub new_client_state: ClientState, pub new_consensus_state: ConsensusState, } #[derive(Serialize, Deserialize, Clone, PartialEq, Debug, JsonSchema)] pub struct ClientStateCallResponseResult { pub is_valid: bool, pub err_msg: String, } #[derive(Serialize, Deserialize, Clone, PartialEq, Debug, JsonSchema)] pub struct InitializeStateResult { pub result: ClientStateCallResponseResult, pub me: ClientState, } #[derive(Serialize, Deserialize, Clone, PartialEq, Debug, JsonSchema)] pub struct CheckHeaderAndUpdateStateResult { pub new_client_state: ClientState, pub new_consensus_state: ConsensusState, pub result: ClientStateCallResponseResult, } #[derive(Serialize, Deserialize, Clone, PartialEq, Debug, JsonSchema)] pub struct VerifyUpgradeAndUpdateStateResult { pub result: ClientStateCallResponseResult, pub new_client_state: ClientState, pub new_consensus_state: ConsensusState, } #[derive(Serialize, Deserialize, Clone, PartialEq, Debug, JsonSchema)] pub struct CheckMisbehaviourAndUpdateStateResult { pub result: ClientStateCallResponseResult, pub new_client_state: ClientState, } #[derive(Serialize, Deserialize, Clone, PartialEq, Debug, JsonSchema)] pub struct VerifyClientConsensusStateResult { pub result: ClientStateCallResponseResult, } #[derive(Serialize, Deserialize, Clone, PartialEq, Debug, JsonSchema)] pub struct VerifyClientStateResult { pub result: ClientStateCallResponseResult, } #[derive(Serialize, Deserialize, Clone, PartialEq, Debug, JsonSchema)] pub struct VerifyConnectionStateResult { pub result: ClientStateCallResponseResult, } #[derive(Serialize, Deserialize, Clone, PartialEq, Debug, JsonSchema)] pub struct VerifyChannelStateResult { pub result: ClientStateCallResponseResult, } #[derive(Serialize, Deserialize, Clone, PartialEq, Debug, JsonSchema)] pub struct VerifyPacketCommitmentResult { pub result: ClientStateCallResponseResult, } #[derive(Serialize, Deserialize, Clone, PartialEq, Debug, JsonSchema)] pub struct VerifyPacketAcknowledgementResult { pub result: ClientStateCallResponseResult, } #[derive(Serialize, Deserialize, Clone, PartialEq, Debug, JsonSchema)] pub struct VerifyPacketReceiptAbsenceResult { pub result: ClientStateCallResponseResult, } #[derive(Serialize, Deserialize, Clone, PartialEq, Debug, JsonSchema)] pub struct CheckSubstituteAndUpdateStateResult { pub result: ClientStateCallResponseResult, pub new_client_state: ClientState, } #[derive(Serialize, Deserialize, Clone, PartialEq, Debug, JsonSchema)] pub struct ZeroCustomFieldsResult { pub me: ClientState, } #[derive(Serialize, Deserialize, Clone, PartialEq, Debug, JsonSchema)] pub struct StatusResult { pub status: Status, } #[derive(Serialize, Deserialize, JsonSchema)] #[serde(rename_all = "lowercase")] pub enum QueryMsg { VerifyClientState { me: ClientState, height: Height, commitment_prefix: MerklePrefix, counterparty_client_identifier: String, proof: String, // Go serializes []byte to base64 encoded string counterparty_client_state: CosmosClientState, consensus_state: ConsensusState, }, VerifyClientConsensusState { me: ClientState, height: Height, consensus_height: Height, commitment_prefix: MerklePrefix, counterparty_client_identifier: String, proof: String, // Go serializes []byte to base64 encoded string counterparty_consensus_state: CosmosConsensusState, consensus_state: ConsensusState, }, VerifyConnectionState { me: ClientState, height: Height, commitment_prefix: MerklePrefix, proof: String, // Go serializes []byte to base64 encoded string connection_id: String, connection_end: ConnectionEnd, consensus_state: ConsensusState, }, VerifyChannelState { me: ClientState, height: Height, commitment_prefix: MerklePrefix, proof: String, // Go serializes []byte to base64 encoded string port_id: String, channel_id: String, channel: Channel, consensus_state: ConsensusState, }, VerifyPacketCommitment { me: ClientState, height: Height, commitment_prefix: MerklePrefix, proof: String, // Go serializes []byte to base64 encoded string port_id: String, channel_id: String, delay_time_period: u64, delay_block_period: u64, sequence: u64, commitment_bytes: String, // Go serializes []byte to base64 encoded string consensus_state: ConsensusState, }, VerifyPacketAcknowledgement { me: ClientState, height: Height, commitment_prefix: MerklePrefix, proof: String, // Go serializes []byte to base64 encoded string port_id: String, channel_id: String, delay_time_period: u64, delay_block_period: u64, sequence: u64, acknowledgement: String, // Go serializes []byte to base64 encoded string consensus_state: ConsensusState, }, VerifyPacketReceiptAbsence { me: ClientState, height: Height, commitment_prefix: MerklePrefix, proof: String, // Go serializes []byte to base64 encoded string port_id: String, channel_id: String, delay_time_period: u64, delay_block_period: u64, sequence: u64, consensus_state: ConsensusState, }, VerifyNextSequenceRecv { me: ClientState, height: Height, commitment_prefix: MerklePrefix, proof: String, // Go serializes []byte to base64 encoded string port_id: String, channel_id: String, delay_time_period: u64, delay_block_period: u64, next_sequence_recv: u64, consensus_state: ConsensusState, }, Status { me: ClientState, consensus_state: ConsensusState, }, ProcessedTime { height: Height }, } #[derive(Serialize, Deserialize, Clone, PartialEq, Debug, JsonSchema)] pub struct ProcessedTimeResponse { pub time: u64, } impl ClientStateCallResponseResult { pub fn success() -> Self { Self { is_valid: true, err_msg: "".to_owned(), } } } <file_sep>use celo_light_client::Header; use hyper::client::{Client, HttpConnector}; use hyper::http::Request; use hyper::Body; use serde::de::DeserializeOwned; use serde_json::json; pub struct Relayer { client: Client<HttpConnector, Body>, uri: String, } impl Relayer { pub fn new(uri: String) -> Self { Self { client: Client::new(), uri, } } pub async fn get_block_header_by_number(&self, hex_num: &str) -> Result<Header, Box<dyn std::error::Error>> { let req = json!({ "jsonrpc": "2.0", "method": "eth_getBlockByNumber", "params": [hex_num, true], "id": 1, }); return self.fetch(req).await; } async fn fetch<'de, T: DeserializeOwned>(&self, body: serde_json::Value) -> Result<T, Box<dyn std::error::Error>> { let req = Request::builder() .method("POST") .uri(&self.uri) .header("Content-Type", "application/json") .body(Body::from(body.to_string())) .expect("request builder"); #[derive(Deserialize)] struct Container<T> { result: T, } let response = (&self.client).request(req).await?; let buf = hyper::body::to_bytes(response).await?; let container: Container<T> = serde_json::from_slice(&buf)?; Ok(container.result) } } <file_sep>mod serialization; mod store; pub mod types; mod util; use prost::Message; use crate::contract::{ serialization::{from_base64, from_base64_json_slice, from_base64_rlp}, store::{ get_consensus_state, get_processed_height, get_processed_time, get_self_height, set_consensus_meta, set_consensus_state, EMPTY_PREFIX, SUBJECT_PREFIX, SUBSTITUTE_PREFIX, }, types::ibc::{ apply_prefix, verify_membership, Channel, ChannelId, ClientId, ClientUpgradePath, ConnectionEnd, ConnectionId, Height, MerklePath, MerklePrefix, MerkleProof, MerkleRoot, Path as IcsPath, PortId, Sequence, }, types::msg::{ CheckHeaderAndUpdateStateResult, CheckMisbehaviourAndUpdateStateResult, CheckSubstituteAndUpdateStateResult, ClientStateCallResponseResult, HandleMsg, InitializeStateResult, ProcessedTimeResponse, QueryMsg, StatusResult, VerifyChannelStateResult, VerifyClientConsensusStateResult, VerifyClientStateResult, VerifyConnectionStateResult, VerifyPacketAcknowledgementResult, VerifyPacketCommitmentResult, VerifyPacketReceiptAbsenceResult, VerifyUpgradeAndUpdateStateResult, ZeroCustomFieldsResult }, types::state::{LightClientState, LightConsensusState}, types::wasm::{ ClientState, ConsensusState, CosmosClientState, CosmosConsensusState, Misbehaviour, PartialConsensusState, Status, WasmHeader, }, util::{to_generic_err, u64_to_big_endian, wrap_response, to_binary}, }; use crate::{state::State, traits::FromRlp, traits::ToRlp, types::header::Header}; use cosmwasm_std::{attr, to_vec, Binary}; use cosmwasm_std::{Deps, DepsMut, Env, MessageInfo}; use cosmwasm_std::{HandleResponse, InitResponse, StdError, StdResult}; use std::str::FromStr; // # A few notes on certain design decisions // ## Serialization // RLP is being used in a few methods, why can't we use JSON everywhere? // // CosmWasm doesn't accept floating point operations (see: `cosmwasm/packages/vm/src/middleware/deterministic.rs`) // and that's for a good reason. Even if you're not using floating point arithmetic explicilty, // some other library might do it behind the scenes. That's exactly what happens with serde json. // // For example to deserialize Celo `Header` type, a set of fields needs to be translated from // String to Int/BigInt (serialized message comes from celo-geth daemon). The following line would // implicitly use floating point arithmetic: // ``` // Source: src/serialization/bytes.rs // let s: &str = Deserialize::deserialize(deserializer)?; // ``` // // How can I check if my wasm binary uses floating points? // * gaia will fail to upload wasm code (validation will fail) // * run: `wasm2wat target/wasm32-unknown-unknown/release/celo_light_client.wasm | grep f64` // // Taken all the possible options I think the easiest way is to use RLP for the structs that fail // to serialize/deserialize via JSON (ie. Header, LightConsensusState) // // ## IBC // ### Proof // ICS-23 specifies the generic proof structure (ie. ExistenceProof). Without the other side of the // bridge (CosmosLC on CeloBlockchain) we can't say for sure what the proof structure is going to // be (TendermintProof, MerkleProof etc.) for sure. // // I've used MerkleProof + MerklePrefix as a placeholder to be revisited once we have the other side of the bridge // implemented // // ### Counterparty Consensus State // Essentially this is Cosmos/Tendermint consensus state coming from the other side of the bridge. For now it's almost empty datastructure, // use as a placeholder. // // ### Serialization // I assumed that proof and counterparty_consensus_state are encoded with JsonMarshaller. // It's likely that amino / protobuf binary encoding will be used... // // ### Vocabulary (hint for the reader) // CeloLC on CosmosNetwork: // * proof - proof that CosmosConsensusState is stored on the TendermintLC in CeloBlockchain // * counterparty_consensus_state - CosmosConsensusState // // Tendermint LC on Celo Blockchain: // * proof - proof that CeloConsensusState is stored on CeloLC in CosmosNetwork // * counterparty_consensus_state - CeloConsensusState pub(crate) fn init( _deps: DepsMut, _env: Env, _info: MessageInfo, _msg: HandleMsg, ) -> Result<InitResponse, StdError> { // The 10-wasm Init method is split into two calls, where the second (via handle()) // call expects ClientState included in the return. // // Therefore it's better to execute whole logic in the second call. Ok(InitResponse::default()) } pub(crate) fn handle( deps: DepsMut, env: Env, info: MessageInfo, msg: HandleMsg, ) -> Result<HandleResponse, StdError> { match msg { HandleMsg::InitializeState { consensus_state, me, } => init_contract(deps, env, info, consensus_state, me), HandleMsg::CheckHeaderAndUpdateState { header, consensus_state, me, } => check_header_and_update_state(deps, env, me, consensus_state, header), HandleMsg::CheckMisbehaviourAndUpdateState { me, misbehaviour, consensus_state_1, consensus_state_2, } => check_misbehaviour( deps, env, me, misbehaviour, consensus_state_1, consensus_state_2, ), HandleMsg::VerifyUpgradeAndUpdateState { me, new_client_state, new_consensus_state, client_upgrade_proof, consensus_state_upgrade_proof, last_height_consensus_state, } => verify_upgrade_and_update_state( deps, env, me, new_client_state, new_consensus_state, client_upgrade_proof, consensus_state_upgrade_proof, last_height_consensus_state, ), HandleMsg::CheckSubstituteAndUpdateState { me, substitute_client_state, subject_consensus_state, initial_height, } => check_substitute_client_state( deps, env, me, substitute_client_state, subject_consensus_state, initial_height, ), HandleMsg::ZeroCustomFields { me, } => zero_custom_fields( deps, env, me, ), } } pub(crate) fn query(deps: Deps, env: Env, msg: QueryMsg) -> StdResult<Binary> { match msg { QueryMsg::VerifyClientState { me, height, commitment_prefix, counterparty_client_identifier, proof, counterparty_client_state, consensus_state, } => verify_client_state( deps, env, me, height, commitment_prefix, counterparty_client_identifier, proof, counterparty_client_state, consensus_state, ).map(to_binary), QueryMsg::VerifyClientConsensusState { me, height, consensus_height, commitment_prefix, counterparty_client_identifier, proof, counterparty_consensus_state, consensus_state, } => verify_client_consensus_state( deps, env, me, height, consensus_height, commitment_prefix, counterparty_client_identifier, proof, counterparty_consensus_state, consensus_state, ).map(to_binary), QueryMsg::VerifyConnectionState { me, height, commitment_prefix, proof, connection_id, connection_end, consensus_state, } => verify_connection_state( deps, env, me, height, commitment_prefix, proof, connection_id, connection_end, consensus_state, ).map(to_binary), QueryMsg::VerifyChannelState { me, height, commitment_prefix, proof, port_id, channel_id, channel, consensus_state, } => verify_channel_state( deps, env, me, height, commitment_prefix, proof, port_id, channel_id, channel, consensus_state, ).map(to_binary), QueryMsg::VerifyPacketCommitment { me, height, commitment_prefix, proof, port_id, channel_id, delay_time_period, delay_block_period, sequence, commitment_bytes, consensus_state, } => verify_packet_commitment( deps, env, me, height, commitment_prefix, proof, port_id, channel_id, delay_time_period, delay_block_period, sequence, commitment_bytes, consensus_state, ).map(to_binary), QueryMsg::VerifyPacketAcknowledgement { me, height, commitment_prefix, proof, port_id, channel_id, delay_time_period, delay_block_period, sequence, acknowledgement, consensus_state, } => verify_packet_acknowledgment( deps, env, me, height, commitment_prefix, proof, port_id, channel_id, delay_time_period, delay_block_period, sequence, acknowledgement, consensus_state, ).map(to_binary), QueryMsg::VerifyPacketReceiptAbsence { me, height, commitment_prefix, proof, port_id, channel_id, delay_time_period, delay_block_period, sequence, consensus_state, } => verify_packet_receipt_absence( deps, env, me, height, commitment_prefix, proof, port_id, channel_id, delay_time_period, delay_block_period, sequence, consensus_state, ).map(to_binary), QueryMsg::VerifyNextSequenceRecv { me, height, commitment_prefix, proof, port_id, channel_id, delay_time_period, delay_block_period, next_sequence_recv, consensus_state, } => verify_next_sequence_recv( deps, env, me, height, commitment_prefix, proof, port_id, channel_id, delay_time_period, delay_block_period, next_sequence_recv, consensus_state, ).map(to_binary), QueryMsg::ProcessedTime { height } => { let processed_time = get_processed_time(deps.storage, EMPTY_PREFIX, &height)?; Ok(cosmwasm_std::to_binary(&ProcessedTimeResponse { time: processed_time, })?) }, QueryMsg::Status { me, consensus_state, } => status(deps, env, me, consensus_state).map(to_binary), } } fn init_contract( deps: DepsMut, env: Env, _info: MessageInfo, consensus_state: ConsensusState, me: ClientState, ) -> Result<HandleResponse, StdError> { // Unmarshal initial state entry (ie. validator set, epoch_size etc.) let light_consensus_state: LightConsensusState = from_base64_rlp(&consensus_state.data, "msg.initial_state_entry")?; // Verify initial state match light_consensus_state.verify() { Err(e) => { return Err(StdError::generic_err(format!( "Initial state verification failed. Error: {}", e ))) } _ => {} } // Set metadata for initial consensus state set_consensus_meta(&env, deps.storage, EMPTY_PREFIX, &me.latest_height.unwrap())?; // Update the state let response_data = Binary(to_vec(&InitializeStateResult { me, result: ClientStateCallResponseResult::success(), })?); Ok(HandleResponse { messages: vec![], attributes: vec![ attr("action", "init_block"), attr("last_consensus_state_height", light_consensus_state.number), ], data: Some(response_data), }) } fn check_header_and_update_state( deps: DepsMut, env: Env, me: ClientState, consensus_state: ConsensusState, wasm_header: WasmHeader, ) -> Result<HandleResponse, StdError> { let current_timestamp: u64 = env.block.time; // Unmarshal header let header: Header = from_base64_rlp(&wasm_header.data, "msg.header")?; // Unmarshal state entry let light_consensus_state: LightConsensusState = from_base64_rlp(&consensus_state.data, "msg.light_consensus_state")?; // Unmarshal state config let light_client_state: LightClientState = from_base64_rlp(&me.data, "msg.light_client_state")?; // Ingest new header let mut state: State = State::new(light_consensus_state, &light_client_state); match state.insert_header(&header, current_timestamp) { Err(e) => { return Err(StdError::generic_err(format!( "Unable to ingest header. Error: {}", e ))) } _ => {} } // Update the state let new_client_state = me.clone(); let new_consensus_state = ConsensusState { code_id: consensus_state.code_id, data: base64::encode(state.snapshot().to_rlp().as_slice()), timestamp: header.time, root: MerkleRoot { hash: base64::encode(header.root.to_vec().as_slice()), }, r#type: consensus_state.r#type, }; // set metadata for this consensus state set_consensus_meta(&env, deps.storage, EMPTY_PREFIX, &wasm_header.height)?; let response_data = Binary(to_vec(&CheckHeaderAndUpdateStateResult { new_client_state, new_consensus_state, result: ClientStateCallResponseResult::success(), })?); Ok(HandleResponse { messages: vec![], attributes: vec![ attr("action", "update_block"), attr("last_consensus_state_height", state.snapshot().number), ], data: Some(response_data), }) } pub fn verify_upgrade_and_update_state( deps: DepsMut, env: Env, me: ClientState, new_client_state: ClientState, new_consensus_state: ConsensusState, client_upgrade_proof: String, consensus_state_upgrade_proof: String, last_height_consensus_state: ConsensusState, ) -> Result<HandleResponse, StdError> { let specs = vec![ics23::iavl_spec(), ics23::tendermint_spec()]; // Sanity check if !(new_client_state.latest_height > me.latest_height) { return Err(StdError::generic_err(format!( "upgraded client height {:?} must be at greater than current client height {:?}", new_client_state.latest_height, me.latest_height ))); } // Unmarshal proofs let proof_client: MerkleProof = from_base64_json_slice(&client_upgrade_proof, "msg.client_proof")?; let proof_consensus: MerkleProof = from_base64_json_slice(&consensus_state_upgrade_proof, "msg.consensus_proof")?; // Unmarshal root let root: Vec<u8> = from_base64( &last_height_consensus_state.root.hash, "msg.last_height_consensus_state.root", )?; // Check consensus state expiration let current_timestamp: u64 = env.block.time; let light_client_state: LightClientState = from_base64_rlp(&me.data, "msg.light_client_state")?; if is_expired( current_timestamp, last_height_consensus_state.timestamp, &light_client_state, ) { return Err(StdError::generic_err("cannot upgrade an expired client")); } // Verify client proof let value: Vec<u8> = to_vec(&new_client_state)?; let upgrade_client_path = construct_upgrade_merkle_path( &light_client_state.upgrade_path, ClientUpgradePath::UpgradedClientState(me.latest_height.unwrap().revision_number), ); if !verify_membership( &proof_consensus, &specs, &root, &upgrade_client_path, value, 0, )? { return Err(StdError::generic_err( "proof membership verification failed (invalid proof)", )); } // Verify consensus proof let value: Vec<u8> = to_vec(&new_consensus_state)?; let upgrade_consensus_state_path = construct_upgrade_merkle_path( &light_client_state.upgrade_path, ClientUpgradePath::UpgradedClientConsensusState(me.latest_height.unwrap().revision_number), ); if !verify_membership( &proof_client, &specs, &root, &upgrade_consensus_state_path, value, 0, )? { return Err(StdError::generic_err( "proof membership verification failed (invalid proof)", )); } // set metadata for this consensus state set_consensus_meta( &env, deps.storage, EMPTY_PREFIX, &new_client_state.latest_height.unwrap(), )?; // Build up the response wrap_response( &VerifyUpgradeAndUpdateStateResult { result: ClientStateCallResponseResult::success(), // NOTE: The contents of client or consensus state // are subject to change (once we have end-to-end test flow) new_client_state, new_consensus_state, }, "verify_client_state", ) } pub fn check_misbehaviour( _deps: DepsMut, _env: Env, me: ClientState, misbehaviour: Misbehaviour, consensus_state1: ConsensusState, consensus_state2: ConsensusState, ) -> Result<HandleResponse, StdError> { // The header heights are expected to be the same if misbehaviour.header_1.height != misbehaviour.header_2.height { return Err(StdError::generic_err(format!( "Misbehaviour header heights differ, {} != {}", misbehaviour.header_1.height, misbehaviour.header_2.height ))); } // If client is already frozen at earlier height than misbehaviour, return with error if me.frozen && me.frozen_height.is_some() && me.frozen_height.unwrap() <= misbehaviour.header_1.height { return Err(StdError::generic_err(format!( "Client is already frozen at earlier height {} than misbehaviour height {}", me.frozen_height.unwrap(), misbehaviour.header_1.height ))); } // Unmarshal header let header_1: Header = from_base64_rlp(&misbehaviour.header_1.data, "msg.header")?; let header_2: Header = from_base64_rlp(&misbehaviour.header_2.data, "msg.header")?; // The header state root should differ if header_1.root == header_2.root { return Err(StdError::generic_err( "Header's state roots should differ, but are the same", )); } // Check the validity of the two conflicting headers against their respective // trusted consensus states check_misbehaviour_header(1, &me, &consensus_state1, &header_1)?; check_misbehaviour_header(2, &me, &consensus_state2, &header_2)?; // Store the new state let mut new_client_state = me.clone(); new_client_state.frozen = true; new_client_state.frozen_height = Some(misbehaviour.header_1.height); let response_data = Binary(to_vec(&CheckMisbehaviourAndUpdateStateResult { new_client_state, result: ClientStateCallResponseResult::success(), })?); Ok(HandleResponse { messages: vec![], attributes: vec![ attr("action", "verify_misbehaviour"), attr("height", misbehaviour.header_1.height), ], data: Some(response_data), }) } // zero_custom_fields returns a ClientState that is a copy of the current ClientState // with all client customizable fields zeroed out pub fn zero_custom_fields( _deps: DepsMut, _env: Env, me: ClientState, ) -> Result<HandleResponse, StdError> { let new_client_state = ClientState { code_id: me.code_id, frozen: false, frozen_height: None, latest_height: None, r#type: me.r#type, // No custom fields in light client state data: me.data.clone(), }; // Build up the response wrap_response( &ZeroCustomFieldsResult { me: new_client_state, }, "zero_custom_fields", ) } pub fn check_misbehaviour_header( num: u16, me: &ClientState, consensus_state: &ConsensusState, header: &Header, ) -> Result<(), StdError> { // Unmarshal state entry let light_consensus_state: LightConsensusState = from_base64_rlp(&consensus_state.data, "msg.light_consensus_state")?; // Unmarshal state config let light_client_state: LightClientState = from_base64_rlp(&me.data, "msg.light_client_state")?; // Verify header let state: State = State::new(light_consensus_state, &light_client_state); match state.verify_header_seal(&header) { Err(e) => { return Err(StdError::generic_err(format!( "Failed to verify header num: {} against it's consensus state. Error: {}", num, e ))) } _ => return Ok(()), } } pub fn verify_client_state( _deps: Deps, _env: Env, _me: ClientState, _height: Height, commitment_prefix: MerklePrefix, counterparty_client_identifier: String, proof: String, counterparty_client_state: CosmosClientState, proving_consensus_state: ConsensusState, ) -> Result<HandleResponse, StdError> { // Unmarshal proof let proof: MerkleProof = from_base64_json_slice(&proof, "msg.proof")?; let specs = vec![ics23::iavl_spec(), ics23::tendermint_spec()]; // Get root from proving (celo) consensus state let root: Vec<u8> = from_base64( &proving_consensus_state.root.hash, "msg.proving_consensus_state.root", )?; // Build path (proof is used to validate the existance of value under that path) let client_prefixed_path = IcsPath::ClientState( ClientId::from_str(&counterparty_client_identifier).map_err(to_generic_err)?, ) .to_string(); // Verify proof against key-value pair let path = apply_prefix(&commitment_prefix, vec![client_prefixed_path])?; let value: Vec<u8> = to_vec(&counterparty_client_state)?; if !verify_membership(&proof, &specs, &root, &path, value, 0)? { return Err(StdError::generic_err( "proof membership verification failed (invalid proof)", )); } // Build up the response wrap_response( &VerifyClientStateResult { result: ClientStateCallResponseResult::success(), }, "verify_client_state", ) } pub fn verify_client_consensus_state( _deps: Deps, _env: Env, _me: ClientState, _height: Height, consensus_height: Height, commitment_prefix: MerklePrefix, counterparty_client_identifier: String, proof: String, counterparty_consensus_state: CosmosConsensusState, proving_consensus_state: ConsensusState, ) -> Result<HandleResponse, StdError> { // Unmarshal proof let proof: MerkleProof = from_base64_json_slice(&proof, "msg.proof")?; let specs = vec![ics23::iavl_spec(), ics23::tendermint_spec()]; // Get root from proving (celo) consensus state let root: Vec<u8> = from_base64( &proving_consensus_state.root.hash, "msg.proving_consensus_state.root", )?; // Build path (proof is used to validate the existance of value under that path) let client_prefixed_path = IcsPath::ClientConsensusState { client_id: ClientId::from_str(&counterparty_client_identifier).map_err(to_generic_err)?, epoch: consensus_height.revision_number, height: consensus_height.revision_height, } .to_string(); // Verify proof against key-value pair let path = apply_prefix(&commitment_prefix, vec![client_prefixed_path])?; let value: Vec<u8> = to_vec(&counterparty_consensus_state)?; if !verify_membership(&proof, &specs, &root, &path, value, 0)? { return Err(StdError::generic_err( "proof membership verification failed (invalid proof)", )); } // Build up the response wrap_response( &VerifyClientConsensusStateResult { result: ClientStateCallResponseResult::success(), }, "verify_client_state", ) } pub fn verify_connection_state( _deps: Deps, _env: Env, _me: ClientState, _height: Height, commitment_prefix: MerklePrefix, proof: String, connection_id: String, connection_end: ConnectionEnd, consensus_state: ConsensusState, ) -> Result<HandleResponse, StdError> { // Unmarshal proof let proof: MerkleProof = from_base64_json_slice(&proof, "msg.proof")?; let specs = vec![ics23::iavl_spec(), ics23::tendermint_spec()]; // Get root from proving (celo) consensus state let root: Vec<u8> = from_base64( &consensus_state.root.hash, "msg.proving_consensus_state.root", )?; // Build path (proof is used to validate the existance of value under that path) let connection_path = IcsPath::Connections(ConnectionId::from_str(&connection_id).map_err(to_generic_err)?) .to_string(); // Verify proof against key-value pair let path = apply_prefix(&commitment_prefix, vec![connection_path])?; let value: Vec<u8> = to_vec(&connection_end)?; if !verify_membership(&proof, &specs, &root, &path, value, 0)? { return Err(StdError::generic_err( "proof membership verification failed (invalid proof)", )); } // Build up the response wrap_response( &VerifyConnectionStateResult { result: ClientStateCallResponseResult::success(), }, "verify_connection_state", ) } pub fn verify_channel_state( _deps: Deps, _env: Env, _me: ClientState, _height: Height, commitment_prefix: MerklePrefix, proof: String, port_id: String, channel_id: String, channel: Channel, consensus_state: ConsensusState, ) -> Result<HandleResponse, StdError> { // Unmarshal proof let proof: MerkleProof = from_base64_json_slice(&proof, "msg.proof")?; let specs = vec![ics23::iavl_spec(), ics23::tendermint_spec()]; // Get root from proving (celo) consensus state let root: Vec<u8> = from_base64( &consensus_state.root.hash, "msg.proving_consensus_state.root", )?; // Build path (proof is used to validate the existance of value under that path) let channel_path = IcsPath::ChannelEnds( PortId::from_str(&port_id).map_err(to_generic_err)?, ChannelId::from_str(&channel_id).map_err(to_generic_err)?, ) .to_string(); // Verify proof against key-value pair let path = apply_prefix(&commitment_prefix, vec![channel_path])?; let value: Vec<u8> = to_vec(&channel)?; if !verify_membership(&proof, &specs, &root, &path, value, 0)? { return Err(StdError::generic_err( "proof membership verification failed (invalid proof)", )); } // Build up the response wrap_response( &VerifyChannelStateResult { result: ClientStateCallResponseResult::success(), }, "verify_channel_state", ) } pub fn verify_packet_commitment( deps: Deps, env: Env, _me: ClientState, height: Height, commitment_prefix: MerklePrefix, proof: String, port_id: String, channel_id: String, delay_time_period: u64, delay_block_period: u64, sequence: u64, commitment_bytes: String, consensus_state: ConsensusState, ) -> Result<HandleResponse, StdError> { // Unmarshal proof let proof: MerkleProof = from_base64_json_slice(&proof, "msg.proof")?; let specs = vec![ics23::iavl_spec(), ics23::tendermint_spec()]; // Get root from proving (celo) consensus state let root: Vec<u8> = from_base64(&consensus_state.root.hash, "msg.consensus_state.root")?; // Check delay period has passed verify_delay_period_passed( deps, height, env.block.height, env.block.time, delay_time_period, delay_block_period, )?; // Build path (proof is used to validate the existance of value under that path) let commitment_path = IcsPath::Commitments { port_id: PortId::from_str(&port_id).map_err(to_generic_err)?, channel_id: ChannelId::from_str(&channel_id).map_err(to_generic_err)?, sequence: Sequence::from(sequence), } .to_string(); // Verify proof against key-value pair let path = apply_prefix(&commitment_prefix, vec![commitment_path])?; let value: Vec<u8> = from_base64(&commitment_bytes, "msg.commitment_bytes")?; if !verify_membership(&proof, &specs, &root, &path, value, 0)? { return Err(StdError::generic_err( "proof membership verification failed (invalid proof)", )); } // Build up the response wrap_response( &VerifyPacketCommitmentResult { result: ClientStateCallResponseResult::success(), }, "verify_packet_commitment", ) } pub fn verify_packet_acknowledgment( deps: Deps, env: Env, _me: ClientState, height: Height, commitment_prefix: MerklePrefix, proof: String, port_id: String, channel_id: String, delay_time_period: u64, delay_block_period: u64, sequence: u64, acknowledgement: String, consensus_state: ConsensusState, ) -> Result<HandleResponse, StdError> { // Unmarshal proof let proof: MerkleProof = from_base64_json_slice(&proof, "msg.proof")?; let specs = vec![ics23::iavl_spec(), ics23::tendermint_spec()]; // Get root from proving (celo) consensus state let root: Vec<u8> = from_base64(&consensus_state.root.hash, "msg.consensus_state.root")?; // Check delay period has passed verify_delay_period_passed( deps, height, env.block.height, env.block.time, delay_time_period, delay_block_period, )?; // Build path (proof is used to validate the existance of value under that path) let ack_path = IcsPath::Acks { port_id: PortId::from_str(&port_id).map_err(to_generic_err)?, channel_id: ChannelId::from_str(&channel_id).map_err(to_generic_err)?, sequence: Sequence::from(sequence), } .to_string(); // Verify proof against key-value pair let path = apply_prefix(&commitment_prefix, vec![ack_path])?; let value: Vec<u8> = from_base64(&acknowledgement, "msg.acknowledgement")?; if !verify_membership(&proof, &specs, &root, &path, value, 0)? { return Err(StdError::generic_err( "proof membership verification failed (invalid proof)", )); } // Build up the response wrap_response( &VerifyPacketAcknowledgementResult { result: ClientStateCallResponseResult::success(), }, "verify_packet_acknowledgment", ) } pub fn verify_packet_receipt_absence( deps: Deps, env: Env, _me: ClientState, height: Height, commitment_prefix: MerklePrefix, proof: String, port_id: String, channel_id: String, delay_time_period: u64, delay_block_period: u64, sequence: u64, consensus_state: ConsensusState, ) -> Result<HandleResponse, StdError> { // Unmarshal proof let proof: MerkleProof = from_base64_json_slice(&proof, "msg.proof")?; let specs = vec![ics23::iavl_spec(), ics23::tendermint_spec()]; // Get root from proving (celo) consensus state let root: Vec<u8> = from_base64(&consensus_state.root.hash, "msg.consensus_state.root")?; // Check delay period has passed verify_delay_period_passed( deps, height, env.block.height, env.block.time, delay_time_period, delay_block_period, )?; // Build path (proof is used to validate the existance of value under that path) let reciept_path = IcsPath::Receipts { port_id: PortId::from_str(&port_id).map_err(to_generic_err)?, channel_id: ChannelId::from_str(&channel_id).map_err(to_generic_err)?, sequence: Sequence::from(sequence), } .to_string(); // Apply prefix let path = apply_prefix(&commitment_prefix, vec![reciept_path])?; // Verify single proof against key-value pair let key: &[u8] = path.key_path.last().unwrap().as_bytes(); // Reference: cosmos-sdk/x/ibc/core/23-commitment/types/merkle.go // TODO: ics23-rs library doesn't seem to offer subroot calculation for non_exist if !ics23::verify_non_membership(&proof.proofs[0], &specs[0], &root, key) { return Err(StdError::generic_err( "proof non membership verification failed (invalid proof)", )); } // Build up the response wrap_response( &VerifyPacketReceiptAbsenceResult { result: ClientStateCallResponseResult::success(), }, "verify_packet_receipt_absence", ) } pub fn verify_next_sequence_recv( deps: Deps, env: Env, _me: ClientState, height: Height, commitment_prefix: MerklePrefix, proof: String, port_id: String, channel_id: String, delay_time_period: u64, delay_block_period: u64, next_sequence_recv: u64, consensus_state: ConsensusState, ) -> Result<HandleResponse, StdError> { // Unmarshal proof let proof: MerkleProof = from_base64_json_slice(&proof, "msg.proof")?; let specs = vec![ics23::iavl_spec(), ics23::tendermint_spec()]; // Get root from proving (celo) consensus state let root: Vec<u8> = from_base64(&consensus_state.root.hash, "msg.consensus_state.root")?; // Check delay period has passed verify_delay_period_passed( deps, height, env.block.height, env.block.time, delay_time_period, delay_block_period, )?; // Build path (proof is used to validate the existance of value under that path) let next_sequence_recv_path = IcsPath::SeqRecvs( PortId::from_str(&port_id).map_err(to_generic_err)?, ChannelId::from_str(&channel_id).map_err(to_generic_err)?, ) .to_string(); // Verify proof against key-value pair let path = apply_prefix(&commitment_prefix, vec![next_sequence_recv_path])?; let value: Vec<u8> = u64_to_big_endian(next_sequence_recv); if !verify_membership(&proof, &specs, &root, &path, value, 0)? { return Err(StdError::generic_err( "proof membership verification failed (invalid proof)", )); } // Build up the response wrap_response( &VerifyPacketAcknowledgementResult { result: ClientStateCallResponseResult::success(), }, "verify_next_sequence_recv", ) } pub fn check_substitute_client_state( deps: DepsMut, env: Env, me: ClientState, substitute_client_state: ClientState, subject_consensus_state: ConsensusState, initial_height: Height, ) -> Result<HandleResponse, StdError> { if substitute_client_state.latest_height.unwrap() != initial_height { return Err(StdError::generic_err(format!( "substitute client revision number must equal initial height revision number ({} != {})", me.latest_height.unwrap(), initial_height ))); } let light_subject_client_state: LightClientState = from_base64_rlp(&me.data, "msg.light_subject_client_state")?; let light_substitute_client_state: LightClientState = from_base64_rlp( &substitute_client_state.data, "msg.light_substitute_client_state", )?; if light_substitute_client_state != light_subject_client_state { return Err(StdError::generic_err( "subject client state does not match substitute client state", )); } let current_timestamp: u64 = env.block.time; let mut new_client_state = me.clone(); if me.frozen && me.frozen_height.is_some() { if light_subject_client_state.allow_update_after_misbehavior { return Err(StdError::generic_err( "client is not allowed to be unfrozen", )); } new_client_state.frozen = false; new_client_state.frozen_height = None; } else if is_expired( current_timestamp, subject_consensus_state.timestamp, &light_subject_client_state, ) { if !light_subject_client_state.allow_update_after_expiry { return Err(StdError::generic_err( "client is not allowed to be unexpired", )); } } // Copy consensus states and processed time from substitute to subject // starting from initial height and ending on the latest height (inclusive) let latest_height = substitute_client_state.latest_height.unwrap(); for i in initial_height.revision_height..latest_height.revision_height + 1 { let height = Height { revision_height: i, revision_number: latest_height.revision_number, }; let cs_bytes = get_consensus_state(deps.storage, SUBSTITUTE_PREFIX, &height); if cs_bytes.is_ok() { set_consensus_state(deps.storage, SUBJECT_PREFIX, &height, &cs_bytes.unwrap())?; } set_consensus_meta(&env, deps.storage, SUBJECT_PREFIX, &height)?; } new_client_state.latest_height = substitute_client_state.latest_height; let latest_consensus_state_bytes = get_consensus_state(deps.storage, SUBJECT_PREFIX, &me.latest_height.unwrap())?; let latest_consensus_state = PartialConsensusState::decode(latest_consensus_state_bytes.as_slice()).unwrap(); let latest_light_consensus_state: LightConsensusState = LightConsensusState::from_rlp(&latest_consensus_state.data).map_err(to_generic_err)?; if is_expired( current_timestamp, latest_light_consensus_state.timestamp, &light_subject_client_state, ) { return Err(StdError::generic_err("updated subject client is expired")); } wrap_response( &CheckSubstituteAndUpdateStateResult { result: ClientStateCallResponseResult::success(), new_client_state, }, "check_substitute_and_update_state", ) } fn status( _deps: Deps, env: Env, me: ClientState, consensus_state: ConsensusState, ) -> Result<HandleResponse, StdError> { let current_timestamp: u64 = env.block.time; let mut status = Status::Active; // Unmarshal state config let light_client_state: LightClientState = from_base64_rlp(&me.data, "msg.light_client_state")?; if me.frozen { status = Status::Frozen; } else { // Unmarshal state entry let light_consensus_state: LightConsensusState = from_base64_rlp(&consensus_state.data, "msg.light_consensus_state")?; if is_expired( current_timestamp, light_consensus_state.timestamp, &light_client_state, ) { status = Status::Exipred; } } // Build up the response wrap_response(&StatusResult { status }, "status") } // verify_delay_period_passed will ensure that at least delayPeriod amount of time has passed since consensus state was submitted // before allowing verification to continue fn verify_delay_period_passed( deps: Deps, proof_height: Height, current_height: u64, current_timestamp: u64, delay_time_period: u64, delay_block_period: u64, ) -> Result<(), StdError> { let processed_time = get_processed_time(deps.storage, EMPTY_PREFIX, &proof_height)?; let valid_time = processed_time + delay_time_period; if current_timestamp < valid_time { return Err(StdError::generic_err(format!( "cannot verify packet until time: {}, current time: {}", valid_time, current_timestamp ))); } let processed_height: Height = get_processed_height(deps.storage, EMPTY_PREFIX, &proof_height)?; let valid_height = Height { revision_number: processed_height.revision_number, revision_height: processed_height.revision_height + delay_block_period, }; let current_height = get_self_height(current_height); if current_height < valid_height { return Err(StdError::generic_err(format!( "cannot verify packet until height: {}, current height: {}", valid_height, current_height ))); } Ok(()) } fn construct_upgrade_merkle_path( upgrade_path: &Vec<String>, client_upgrade_path: ibc::ics24_host::ClientUpgradePath, ) -> MerklePath { let appended_key = ibc::ics24_host::Path::Upgrade(client_upgrade_path).to_string(); let mut result: Vec<String> = upgrade_path.clone(); result.push(appended_key); MerklePath { key_path: result } } fn is_expired( current_timestamp: u64, latest_timestamp: u64, light_client_state: &LightClientState, ) -> bool { current_timestamp > latest_timestamp + light_client_state.trusting_period } #[cfg(test)] mod tests { use super::*; use crate::contract::types::ibc::MerklePrefix; use cosmwasm_std::testing::{mock_dependencies, mock_env}; use ics23::{ calculate_existence_root, CommitmentProof, ExistenceProof, HashOp, InnerOp, LeafOp, LengthOp, }; #[test] fn test_verify_client_consensus_state() { let mut deps = mock_dependencies(&[]); let env = mock_env(); let client_state = get_example_client_state(0, 5); let height = new_height(0, 5); let consensus_height = new_height(0, 5); let commitment_prefix = MerklePrefix { key_prefix: base64::encode("prefix"), }; let counterparty_client_identifier = String::from("07-tendermint-0"); // The counterparty_consensus_state + commitment_proof comes from the other side of the // bridge, while root "is local" (comes from proving consensus state). // // In the unittest we update provingConsensusState with "remote root", so that validation // always succeeds (as long as verify_membership works properly) let counterparty_consensus_state = CosmosConsensusState { root: MerkleRoot { hash: String::from("base64_encoded_hash"), }, }; let (commitment_proof, root) = get_example_proof( b"clients/07-tendermint-0/consensusStates/0-5".to_vec(), // key (based on consensus_height) to_vec(&counterparty_consensus_state).unwrap(), // value ); let proving_consensus_state = get_example_consenus_state(root, height); let response = verify_client_consensus_state( deps.as_mut(), env, client_state, height, consensus_height, commitment_prefix, counterparty_client_identifier, base64::encode(to_vec(&commitment_proof).unwrap()), counterparty_consensus_state, proving_consensus_state, ); assert_eq!(response.is_err(), false); } fn get_example_client_state(revision_number: u64, revision_height: u64) -> ClientState { ClientState { data: String::from(""), code_id: String::from(""), frozen: false, frozen_height: None, latest_height: Some(Height { revision_number, revision_height, }), r#type: String::from("client_state"), } } fn get_example_consenus_state(root: Vec<u8>, height: Height) -> ConsensusState { // In real life scenario this consensus state would be fetched // at the given Height. This makes the CS dependant on the arg. let mut light_cs = LightConsensusState::new(); light_cs.number = height.revision_height + height.revision_number; ConsensusState { data: base64::encode(light_cs.to_rlp()), code_id: String::from(""), timestamp: 123, root: MerkleRoot { hash: base64::encode(root), }, r#type: String::from("consensus_state"), } } fn get_example_proof(key: Vec<u8>, value: Vec<u8>) -> (MerkleProof, Vec<u8>) { let leaf = LeafOp { hash: HashOp::Sha256.into(), prehash_key: 0, prehash_value: HashOp::Sha256.into(), length: LengthOp::VarProto.into(), prefix: vec![0_u8], }; let valid_inner = InnerOp { hash: HashOp::Sha256.into(), prefix: hex::decode("deadbeef00cafe00").unwrap(), suffix: vec![], }; let proof = ExistenceProof { key, value, leaf: Some(leaf.clone()), path: vec![valid_inner.clone()], }; let root = calculate_existence_root(&proof).unwrap(); let commitment_proof = CommitmentProof { proof: Some(ics23::commitment_proof::Proof::Exist(proof)), }; ( MerkleProof { proofs: vec![commitment_proof], }, root, ) } fn new_height(revision_number: u64, revision_height: u64) -> Height { Height { revision_number, revision_height, } } } <file_sep>use crate::bls::verify_aggregated_seal; use crate::errors::{Error, Kind}; use crate::serialization::rlp::{rlp_field_from_bytes, rlp_list_field_from_bytes}; use crate::traits::{FromRlp, StateConfig, ToRlp}; use crate::types::header::{Address, Hash}; use crate::types::istanbul::{IstanbulAggregatedSeal, SerializedPublicKey}; use rlp::{Decodable, DecoderError, Encodable, Rlp, RlpStream}; use rlp_derive::{RlpDecodable, RlpEncodable}; /// Validator identifies block producer by public key and address #[derive(Serialize, Deserialize, Clone, PartialEq, Debug)] pub struct Validator { #[serde(with = "crate::serialization::bytes::hexstring")] pub address: Address, #[serde(with = "crate::serialization::bytes::hexstring")] pub public_key: SerializedPublicKey, } impl Encodable for Validator { fn rlp_append(&self, s: &mut RlpStream) { s.begin_list(2); s.append(&self.address.as_ref()); s.append(&self.public_key.as_ref()); } } impl Decodable for Validator { fn decode(rlp: &Rlp) -> Result<Self, DecoderError> { Ok(Validator { address: rlp_field_from_bytes(&rlp.at(0)?)?, public_key: rlp_field_from_bytes(&rlp.at(1)?)?, }) } } impl ToRlp for Vec<Validator> { fn to_rlp(&self) -> Vec<u8> { rlp::encode_list(&self) } } impl FromRlp for Vec<Validator> { fn from_rlp(bytes: &[u8]) -> Result<Self, Error> { Ok(rlp::decode_list(&bytes)) } } /// Config contains state related configuration flags #[derive(Serialize, Deserialize, RlpEncodable, RlpDecodable, Clone, PartialEq, Eq, Debug)] pub struct Config { pub epoch_size: u64, pub allowed_clock_skew: u64, pub verify_epoch_headers: bool, pub verify_non_epoch_headers: bool, pub verify_header_timestamp: bool, } impl ToRlp for Config { fn to_rlp(&self) -> Vec<u8> { rlp::encode(self) } } impl FromRlp for Config { fn from_rlp(bytes: &[u8]) -> Result<Self, Error> { rlp::decode(&bytes).map_err(|e| Kind::RlpDecodeError.context(e).into()) } } impl StateConfig for Config { fn epoch_size(&self) -> u64 { self.epoch_size } fn allowed_clock_skew(&self) -> u64 { self.allowed_clock_skew } fn verify_epoch_headers(&self) -> bool { self.verify_epoch_headers } fn verify_non_epoch_headers(&self) -> bool { self.verify_non_epoch_headers } fn verify_header_timestamp(&self) -> bool { self.verify_header_timestamp } } /// Snapshot represents an IBFT consensus state at specified block height #[derive(Serialize, Deserialize, Clone, PartialEq, Debug)] pub struct Snapshot { /// Block number at which the snapshot was created pub number: u64, /// Block creation time pub timestamp: u64, /// Snapshot of current validator set pub validators: Vec<Validator>, // Hash and aggregated seal are required to validate the header against the validator set /// Block hash pub hash: Hash, /// Block aggregated seal pub aggregated_seal: IstanbulAggregatedSeal, } impl Encodable for Snapshot { fn rlp_append(&self, s: &mut RlpStream) { s.begin_list(5); s.append(&self.number); s.append(&self.timestamp); s.begin_list(self.validators.len()); for validator in self.validators.iter() { s.append(validator); } s.append(&self.hash.as_ref()); s.append(&self.aggregated_seal); } } impl Decodable for Snapshot { fn decode(rlp: &Rlp) -> Result<Self, DecoderError> { let validators: Result<Vec<Validator>, DecoderError> = rlp.at(2)?.iter().map(|r| r.as_val()).collect(); Ok(Snapshot { validators: validators?, number: rlp.val_at(0)?, timestamp: rlp.val_at(1)?, hash: rlp_list_field_from_bytes(rlp, 3)?, aggregated_seal: rlp.val_at(4)?, }) } } impl Snapshot { pub fn new() -> Self { Self { number: 0, timestamp: 0, validators: Vec::new(), hash: Hash::default(), aggregated_seal: IstanbulAggregatedSeal::new(), } } pub fn verify(&self) -> Result<(), Error> { verify_aggregated_seal(self.hash, &self.validators, &self.aggregated_seal) } } impl ToRlp for Snapshot { fn to_rlp(&self) -> Vec<u8> { rlp::encode(self) } } impl FromRlp for Snapshot { fn from_rlp(bytes: &[u8]) -> Result<Self, Error> { rlp::decode(&bytes).map_err(|e| Kind::RlpDecodeError.context(e).into()) } } <file_sep>pub(crate) mod hexstring { use hex::FromHex; use serde::{de::Error, Deserialize, Deserializer, Serializer}; /// Deserialize string into T pub(crate) fn deserialize<'de, D, T>(deserializer: D) -> Result<T, D::Error> where D: Deserializer<'de>, T: hex::FromHex, <T as FromHex>::Error: std::fmt::Display, { let s: &str = Deserialize::deserialize(deserializer)?; if s.len() <= 2 || !s.starts_with("0x") { return T::from_hex(Vec::new()).map_err(D::Error::custom); } T::from_hex(&s[2..]).map_err(D::Error::custom) } /// Serialize from T into string pub(crate) fn serialize<S, T>(value: &T, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, T: AsRef<[u8]>, { let hex_string = hex::encode(value.as_ref()); if hex_string.len() == 0 { return serializer.serialize_str(""); } serializer.serialize_str(&(String::from("0x") + &hex_string)) } } pub(crate) mod hexnum { use num; use serde::{de::Error, Deserialize, Deserializer, Serialize, Serializer}; /// Deserialize string into T pub(crate) fn deserialize<'de, D, T>(deserializer: D) -> Result<T, D::Error> where D: Deserializer<'de>, T: num::traits::Num, <T as num::Num>::FromStrRadixErr: std::fmt::Display, { let s: &str = Deserialize::deserialize(deserializer)?; if s.len() <= 2 || !s.starts_with("0x") { return Err(D::Error::custom(format!( "hex string should start with '0x', got: {}", s ))); } T::from_str_radix(&s[2..], 16).map_err(D::Error::custom) } /// Serialize from T into string pub(crate) fn serialize<S, T>(value: &T, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, T: std::fmt::LowerHex, { format!("0x{:x}", value).serialize(serializer) } } pub(crate) mod hexbigint { use num::Num; use num_bigint::BigInt as Integer; use serde::{de::Error, Deserialize, Deserializer, Serialize, Serializer}; /// Deserialize string into T pub(crate) fn deserialize<'de, D>(deserializer: D) -> Result<Integer, D::Error> where D: Deserializer<'de>, { let s: &str = Deserialize::deserialize(deserializer)?; if s.len() <= 2 || !s.starts_with("0x") { return Err(D::Error::custom(format!( "hex string should start with '0x', got: {}", s ))); } Integer::from_str_radix(&s[2..], 16).map_err(D::Error::custom) } /// Serialize from T into string pub(crate) fn serialize<S, T>(value: &T, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, T: std::fmt::LowerHex, { format!("0x{:x}", value).serialize(serializer) } } pub(crate) mod hexvec { use crate::traits::FromBytes; use serde::{de::Error, Deserialize, Deserializer, Serialize, Serializer}; /// Deserialize vector into Vec<T> pub(crate) fn deserialize<'de, D, T>(deserializer: D) -> Result<Vec<T>, D::Error> where D: Deserializer<'de>, T: FromBytes + Clone, { let items: Vec<String> = Deserialize::deserialize(deserializer)?; let mut out: Vec<T> = Vec::new(); for item in items { if item.len() <= 2 || !item.starts_with("0x") { return Err(D::Error::custom(format!( "hex string should start with '0x', got: {}", item ))); } match hex::decode(&item[2..]) { Ok(decoded) => match T::from_bytes(&decoded) { Ok(concrete) => out.push(concrete.to_owned()), Err(e) => { return Err(D::Error::custom(format!( "failed to call from_bytes, got: {}", e ))) } }, Err(e) => { return Err(D::Error::custom(format!( "failed to decode hex data, got: {}", e ))) } } } Ok(out) } /// Serialize from &[T] into vector of strings pub(crate) fn serialize<S, T>(value: &[T], serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, T: AsRef<[u8]>, { value .iter() .map(|v| format!("0x{}", hex::encode(v))) .collect::<Vec<String>>() .serialize(serializer) } } <file_sep>pub mod wasm; pub mod msg; pub mod ibc; pub mod state; <file_sep>[![Build Status][travis-badge]][travis] [travis-badge]: https://travis-ci.org/ChorusOne/celo-light-client.svg?branch=main [travis]: https://travis-ci.org/ChorusOne/celo-light-client/ # Celo Light Client The library provides a [lightest-sync](https://docs.celo.org/celo-codebase/protocol/consensus/ultralight-sync) mode, that enables a quick, secure, and cheap way to synchronize IBFT consensus state with a Celo Blockchain node. The codebase is split into two parts: * `library` - a subset of Celo Blockchain building blocks, such as data structures (ie. Header, IBFT) or functionalities (ie. serialization, consensus state management) * `contract` - an (optional) [IBC](https://docs.cosmos.network/master/ibc/overview.html) compatible light client contract, intended to be run on Cosmos Blockchain as WASM binary **ultralight-sync explained** In the nutshell, the validator set for the current epoch is computed by downloading the last header of each previous epoch and applying the validator set diff. The latest block header is then verified by checking that at least two-thirds of the validator set for the current epoch signed the block header. Ultralight mode download approximately 30,000 times fewer headers than light nodes in order to sync the latest block (assuming 3-second block periods and 1-day epochs). ### Example An example program that utilizes `lightest-sync` library is placed in the `examples/lightest-sync`. It uses [celo-blockchain node](https://github.com/celo-org/celo-blockchain) to fetch epoch headers, built up the validator set, and verify the latest available header. You may spawn up example program via: ``` $ docker-compose up --abort-on-container-exit ``` ### Light Client The CosmWasm contract is gated by `wasm-contract` feature: ``` $ rustup target add wasm32-unknown-unknown $ cargo build --release --features wasm-contract --target wasm32-unknown-unknown ``` To compile optimized binary run: ``` $ make wasm-optimized $ stat target/wasm32-unknown-unknown/release/celo.wasm ``` ### Demo [![asciicast](https://asciinema.org/a/411776.svg)](https://asciinema.org/a/411776) <file_sep>mod relayer; #[macro_use] extern crate serde_derive; #[macro_use] extern crate clap; extern crate celo_light_client; use celo_light_client::*; use relayer::*; use clap::{App, Arg}; use num::cast::ToPrimitive; extern crate log; use log::{info, error}; use std::time::{SystemTime, UNIX_EPOCH}; #[tokio::main] async fn main(){ env_logger::init(); // setup CLI let matches = App::new("lightest-sync-example") .version("1.0") .author("<NAME> <<EMAIL>>") .about("Demonstrates lightest-sync library usage for Celo blockchain") .arg( Arg::with_name("fast") .short("f") .long("fast") .takes_value(false) .help("Skips the seal verification for the epoch headers (to build up current validator set faster)") ) .arg( Arg::with_name("epoch-size") .short("e") .long("epoch-size") .takes_value(true) .default_value("17280") .help("The epoch-size of Celo blockchain") ) .arg( Arg::with_name("db") .short("d") .long("db") .takes_value(true) .default_value("./local.db") .help("The path to local database") ) .arg( Arg::with_name("addr") .short("a") .long("addr") .takes_value(true) .default_value("http://127.0.0.1:8545") .help("Removes the local database") ) .get_matches(); let validate_all_headers = match matches.occurrences_of("fast") { 1 => false, _ => true, }; let first_epoch = 0; let epoch_size = value_t!(matches.value_of("epoch-size"), u64).unwrap(); let addr = matches.value_of("addr").unwrap(); // setup relayer info!("Setting up relayer"); let relayer: Relayer = Relayer::new(addr.to_string()); // setup state container info!("Setting up storage"); let state_config = Config { epoch_size, allowed_clock_skew: 5, verify_epoch_headers: validate_all_headers, verify_non_epoch_headers: validate_all_headers, verify_header_timestamp: true, }; let snapshot = Snapshot::new(); let mut state = State::new(snapshot, &state_config); info!("Fetching latest block header from: {}", addr); let current_block_header: Header = relayer.get_block_header_by_number("latest").await.unwrap(); let current_epoch_number: u64 = get_epoch_number(current_block_header.number.to_u64().unwrap(), epoch_size); info!( "Syncing epoch headers from {} to epoch num: {} (last header num: {}, epoch size: {})", first_epoch, current_epoch_number, current_block_header.number, epoch_size ); // build up state from the genesis block to the latest for epoch in first_epoch..current_epoch_number { let current_timestamp = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs(); let epoch_block_num = get_epoch_last_block_number(epoch, epoch_size); let epoch_block_number_hex = format!("0x{:x}", epoch_block_num); let header = relayer.get_block_header_by_number(&epoch_block_number_hex).await; if header.is_ok() { match state.insert_header(&header.unwrap(), current_timestamp) { Ok(_) => info!("[{}/{}] Inserted epoch header: {}", epoch + 1, current_epoch_number, epoch_block_number_hex), Err(e) => error!("Failed to insert epoch header {}: {}", epoch_block_number_hex, e) } } else { error!("Failed to fetch block header num: {}", epoch_block_number_hex); } } let current_timestamp = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs(); match state.verify_header(&current_block_header, current_timestamp) { Ok(_) => info!("Succesfully validated latest header against local state: {}", current_block_header.number), Err(e) => error!("Failed to validate latest header against local state: {}", e) } } <file_sep>use crate::traits::FromRlp; use cosmwasm_std::{from_slice, StdError, StdResult}; use serde::de::DeserializeOwned; use std::any::type_name; pub fn from_base64<S: Into<String>>( base64_data: &String, target_type: S, ) -> Result<Vec<u8>, StdError> { match base64::decode(base64_data) { Ok(bytes) => Ok(bytes), Err(e) => { return Err(StdError::parse_err( target_type, format!("Unable to base64 decode data. Error: {}", e), )) } } } pub fn from_base64_rlp<T, S>(base64_data: &String, target_type: S) -> Result<T, StdError> where T: FromRlp, S: Into<String> + Clone, { let bytes = from_base64(&base64_data, target_type.clone())?; Ok(T::from_rlp(bytes.as_slice()).map_err(|e| { StdError::parse_err( target_type, format!("Unable to rlp decode from base64 data. Error: {}", e), ) })?) } pub fn from_base64_json_slice<T, S>(base64_data: &String, target_type: S) -> Result<T, StdError> where T: DeserializeOwned, S: Into<String> + Clone, { let bytes = from_base64(base64_data, target_type.clone())?; let t: T = from_slice(&bytes).map_err(|e| { StdError::parse_err( target_type, format!("Unable to json decode data. Error: {}", e), ) })?; Ok(t) } pub fn must_deserialize<T: DeserializeOwned>(value: &Option<Vec<u8>>) -> StdResult<T> { match value { Some(vec) => from_slice(&vec), None => Err(StdError::not_found(type_name::<T>())), } } <file_sep>[package] name = "celo_light_client" version = "0.1.0" authors = ["<NAME> <<EMAIL>>"] edition = "2018" [dependencies] cfg-if = "0.1" serde = { version = "1.0", default-features = false, features = ["derive"] } hex = { version = "0.4", default-features = false } num = { version = "0.3", default-features = false } rlp = { version = "0.4.6", default-features = false, features = ["std"] } rlp-derive = { version = "0.1.0", default-features = false } sha3 = { version = "0.9.1", default-features = false } num-bigint = { version = "0.4", default-features = false } num-traits = { version = "0.2.14", default-features = false } anomaly = { version = "0.2.0", default-features = false } thiserror = { version = "1.0.23", default-features = false } algebra = { git = "https://github.com/celo-org/zexe", default-features = false } # why fork? - cosmwasm / wasm crashes on floating point operations. # PR: https://github.com/celo-org/celo-bls-snark-rs/pull/209 bls-crypto = { git = "https://github.com/mkaczanowski/celo-bls-snark-rs", branch = "float_free_hash_length_fn", default-features = true } # cosmwasm contract deps cosmwasm-std = { version = "0.13.2", optional = true } cosmwasm-derive = { version = "0.13.2", optional = true } cosmwasm-storage = { version = "0.13.2", optional = true } schemars = { version = "0.7", optional = true } clear_on_drop = { version = "0.2.3", features = ["no_cc"], optional = true } base64 = { version = "0.13.0", optional = true } byteorder = { version = "1.4.3", optional = true } prost-derive = { version = "0.7.0", optional = true } prost = { version = "0.7.0", optional = true } # why fork? - ics23 proofs structs are not json serializable by default. # The forked library adds serde json serialization. ics23 = { git = "https://github.com/ChorusOne/ics23", branch = "json_serialization", optional = true } # why fork? - ibc-rs depends on the tonic library that doesn't compile to WASM. # The library itself is only used to generate prost client/server definitions, # so the forked repo simply disabled that feature ibc = { git = "https://github.com/ChorusOne/ibc-rs", branch = "no_tonic", default-features = true , optional = true } [lib] crate-type = ["cdylib", "rlib"] [dev-dependencies] serde_json = "1.0" serde_derive = "1.0" serde = "1.0" secp256k1 = { version = "0.19.0", features = ["bitcoin_hashes", "rand"] } env_logger = "0.8.2" hyper = "0.13.9" rand = "0.6" rand_core = "0.4" tokio = { version = "0.2", features = ["full"] } sled = "0.34.6" log = "0.4" clap = "2.33.3" cosmwasm-vm = { version = "0.7.2", default-features = false } [profile.release] #opt-level = 'z' #opt-level = 3 opt-level = 2 debug = false rpath = false lto = true debug-assertions = false codegen-units = 1 panic = 'abort' incremental = false overflow-checks = true [features] default = ["cranelift", "wasm-contract"] wasm-contract = ["cosmwasm-std", "cosmwasm-derive", "cosmwasm-storage", "schemars", "clear_on_drop", "base64", "ics23", "ibc", "byteorder", "prost", "prost-derive"] # for quicker tests, cargo test --lib # for more explicit tests, cargo test --features=backtraces backtraces = ["cosmwasm-std/backtraces", "cosmwasm-vm/backtraces"] cranelift = ["cosmwasm-vm/default-cranelift"] singlepass = ["cosmwasm-vm/default-singlepass"] [[example]] name = "lightest-sync" path = "examples/lightest-sync/main.rs" <file_sep>use byteorder::{BigEndian, ByteOrder}; use cosmwasm_std::{attr, to_vec, Binary}; use cosmwasm_std::{HandleResponse, StdError, StdResult}; use serde::Serialize; use std::fmt::Display; pub fn u64_to_big_endian(value: u64) -> Vec<u8> { let mut buf = [0; 8]; BigEndian::write_u64(&mut buf, value); buf.to_vec() } pub fn wrap_response<T>(result: T, action: &'static str) -> Result<HandleResponse, StdError> where T: Serialize, { let response_data = Binary(to_vec(&result)?); Ok(HandleResponse { messages: vec![], attributes: vec![attr("action", action)], data: Some(response_data), }) } pub fn to_generic_err<T>(err: T) -> StdError where T: Display, { StdError::GenericErr { msg: err.to_string(), } } // TODO: temporary remap, once ICS is settled this should be removed pub fn to_binary(t: HandleResponse) -> Binary { t.data.unwrap() } <file_sep>use anomaly::{BoxError, Context}; use thiserror::Error; /// The main error type verification methods will return. /// See [`Kind`] for the different kind of errors. pub type Error = anomaly::Error<Kind>; /// All error kinds related to the light client. #[derive(Clone, Debug, Error)] pub enum Kind { #[error("invalid data length while converting slice to fixed-size array type ({current} != {expected}")] InvalidDataLength { current: usize, expected: usize }, #[error("rlp decode error")] RlpDecodeError, #[error("invalid validator set diff: {msg}")] InvalidValidatorSetDiff { msg: &'static str }, #[error("attempted to insert invalid data to chain")] InvalidChainInsertion, #[error("aggregated seal does not aggregate enough seals, num_seals: {current}, minimum quorum size: {expected}")] MissingSeals { current: usize, expected: usize }, #[error("BLS verify error")] BlsVerifyError, #[error("BLS invalid signature")] BlsInvalidSignature, #[error("BLS invalid public key")] BlsInvalidPublicKey, #[error("header verification failed: {msg}")] HeaderVerificationError { msg: &'static str }, #[error("unkown error occurred")] Unknown, } impl Kind { /// Add additional context. pub fn context(self, source: impl Into<BoxError>) -> Context<Kind> { Context::new(self, Some(source.into())) } } <file_sep>use crate::traits::FromBytes; use num_bigint::{BigInt as Integer, Sign}; use num_traits::Zero; use rlp::{DecoderError, Rlp}; pub fn rlp_list_field_from_bytes<T>(rlp: &Rlp, index: usize) -> Result<T, DecoderError> where T: FromBytes + Clone, { rlp.at(index)? .decoder() .decode_value(|data| match T::from_bytes(data) { Ok(field) => Ok(field.to_owned()), Err(_) => Err(DecoderError::Custom("invalid length data")), }) } pub fn rlp_field_from_bytes<T>(rlp: &Rlp) -> Result<T, DecoderError> where T: FromBytes + Clone, { rlp.decoder() .decode_value(|data| match T::from_bytes(data) { Ok(field) => Ok(field.to_owned()), Err(_) => Err(DecoderError::Custom("invalid length data")), }) } pub fn rlp_to_big_int(rlp: &Rlp, index: usize) -> Result<Integer, DecoderError> { rlp.at(index)? .decoder() .decode_value(|bytes| Ok(Integer::from_bytes_be(Sign::Plus, bytes))) } pub fn big_int_to_rlp_compat_bytes(val: &Integer) -> Vec<u8> { // BigInt library returns vec![0] for zero value where // the celo blockchain expects empty vector if val.is_zero() { Vec::new() } else { val.to_bytes_be().1 } } #[cfg(test)] mod tests { use super::*; use num_traits::Num; #[test] fn parses_big_int() { let expected_bytes: Vec<u8> = vec![236, 160, 242, 246, 191, 251, 255, 120]; let rlp_list = bytes_to_rlp_list(&expected_bytes); let r = Rlp::new(&rlp_list); assert_eq!( "17050895330821537656", rlp_to_big_int(&r, 0).unwrap().to_str_radix(10), ); assert_eq!( big_int_to_rlp_compat_bytes(&Integer::from_str_radix("0", 10).unwrap()), Vec::<u8>::new(), ); assert_eq!( big_int_to_rlp_compat_bytes( &Integer::from_str_radix("17050895330821537656", 10).unwrap() ), expected_bytes, ); } fn bytes_to_rlp_list(bytes: &[u8]) -> Vec<u8> { let mut r = rlp::RlpStream::new(); r.begin_list(1); r.append(&bytes); r.out() } } <file_sep>pub(crate) mod header; pub(crate) mod istanbul; pub(crate) mod state; <file_sep>use crate::errors::Error; // "Deafult" trait is implemented for a few selected fixed-array types. Taken we can't implement // the trait outside of a crate, we created a new one that mimics the stdlib. pub trait DefaultFrom { fn default() -> Self; } pub trait FromBytes { fn from_bytes(data: &[u8]) -> Result<&Self, Error>; } pub trait ToRlp { fn to_rlp(&self) -> Vec<u8>; } pub trait FromRlp { fn from_rlp(bytes: &[u8]) -> Result<Self, Error> where Self: std::marker::Sized; } pub trait StateConfig { /// Epoch size expressed in number of blocks fn epoch_size(&self) -> u64; /// Defines how far block timestamp can go in the future fn allowed_clock_skew(&self) -> u64; /// Whether to validate (BLS signature) epoch headers. It should always be set to true. fn verify_epoch_headers(&self) -> bool; /// Whether to validate (BLS signature) non epoch headers. Since non-epoch don't affect /// validator set, it's acceptable to disable validation fn verify_non_epoch_headers(&self) -> bool; /// Whether to verify headers time against current time. It's recommended to keep it true fn verify_header_timestamp(&self) -> bool; } <file_sep>use crate::contract::types::ibc::{Height, MerkleRoot}; use serde::{Deserialize, Serialize}; use schemars::JsonSchema; use prost_derive::Message; // Without the other side of the bridge (Tendermint LC on Celo) // we don't know how the consensus or client state will look like. // // NOTE: This is just a placeholder #[derive(Serialize, Deserialize, JsonSchema)] pub struct CosmosConsensusState { pub root: MerkleRoot, } // NOTE: This is just a placeholder #[derive(Serialize, Deserialize, Clone, PartialEq, Debug, JsonSchema)] pub struct CosmosClientState { pub latest_height: Height, } #[derive(Serialize, Deserialize, Clone, PartialEq, Debug, JsonSchema)] pub struct ConsensusState { pub code_id: String, // Go serializes []byte to base64 encoded string pub data: String, // Go serializes []byte to base64 encoded string pub timestamp: u64, pub root: MerkleRoot, pub r#type: String, } #[derive(Message, Serialize, Deserialize, Clone, PartialEq)] pub struct PartialConsensusState { #[prost(bytes = "vec", tag = "1")] pub code_id: Vec<u8>, #[prost(bytes = "vec", tag = "2")] pub data: Vec<u8>, } #[derive(Serialize, Deserialize, Clone, PartialEq, Debug, JsonSchema)] pub struct ClientState { pub data: String, // Go serializes []byte to base64 encoded string pub code_id: String, // Go serializes []byte to base64 encoded string #[serde(default)] pub frozen: bool, pub frozen_height: Option<Height>, pub latest_height: Option<Height>, pub r#type: String, } #[derive(Serialize, Deserialize, Clone, PartialEq, Debug, JsonSchema)] pub struct WasmHeader { pub data: String, // Go serializes []byte to base64 encoded string pub height: Height, pub r#type: String, } #[derive(Serialize, Deserialize, Clone, PartialEq, Debug, JsonSchema)] pub struct Misbehaviour { pub code_id: String, // Go serializes []byte to base64 encoded string pub client_id: String, pub header_1: WasmHeader, pub header_2: WasmHeader, } #[derive(Serialize, Deserialize, Clone, PartialEq, Debug, JsonSchema)] pub enum Status { Active, Frozen, Exipred, Unknown } <file_sep>use crate::errors::{Error, Kind}; use crate::traits::{FromRlp, ToRlp, StateConfig}; use crate::types::state::Snapshot; use rlp_derive::{RlpEncodable, RlpDecodable}; pub type LightConsensusState = Snapshot; #[derive(Serialize, Deserialize, RlpDecodable, RlpEncodable, Clone, PartialEq, Debug)] pub struct LightClientState { pub epoch_size: u64, pub allowed_clock_skew: u64, pub trusting_period: u64, pub upgrade_path: Vec<String>, pub verify_epoch_headers: bool, pub verify_non_epoch_headers: bool, pub verify_header_timestamp: bool, pub allow_update_after_misbehavior: bool, pub allow_update_after_expiry: bool, } impl ToRlp for LightClientState { fn to_rlp(&self) -> Vec<u8> { rlp::encode(self) } } impl FromRlp for LightClientState { fn from_rlp(bytes: &[u8]) -> Result<Self, Error> { match rlp::decode(&bytes) { Ok(config) => Ok(config), Err(err) => Err(Kind::RlpDecodeError.context(err).into()), } } } impl StateConfig for LightClientState { fn epoch_size(&self) -> u64 { self.epoch_size } fn allowed_clock_skew(&self) -> u64 { self.allowed_clock_skew } fn verify_epoch_headers(&self) -> bool { self.verify_epoch_headers } fn verify_non_epoch_headers(&self) -> bool { self.verify_non_epoch_headers } fn verify_header_timestamp(&self) -> bool { self.verify_header_timestamp } } <file_sep>use crate::algebra::CanonicalDeserialize; use crate::errors::{Error, Kind}; use crate::istanbul::min_quorum_size; use crate::serialization::rlp::big_int_to_rlp_compat_bytes; use crate::types::header::Hash; use crate::types::istanbul::{IstanbulAggregatedSeal, IstanbulMsg}; use crate::types::state::Validator; use bls_crypto::{hash_to_curve::try_and_increment::DIRECT_HASH_TO_G1, PublicKey, Signature}; use num_bigint::BigInt as Integer; /// Uses BLS signature verification to validate header against provided validator set pub fn verify_aggregated_seal( header_hash: Hash, validators: &[Validator], aggregated_seal: &IstanbulAggregatedSeal, ) -> Result<(), Error> { let proposal_seal = prepare_commited_seal(header_hash, &aggregated_seal.round); let expected_quorum_size = min_quorum_size(validators.len()); // Find which public keys signed from the provided validator set let public_keys = validators .iter() .enumerate() .filter(|(i, _)| aggregated_seal.bitmap.bit(*i as u64)) .map(|(_, validator)| deserialize_pub_key(&validator.public_key)) .collect::<Result<Vec<PublicKey>, Error>>()?; if public_keys.len() < expected_quorum_size { return Err(Kind::MissingSeals { current: public_keys.len(), expected: expected_quorum_size, } .into()); } let sig = deserialize_signature(&aggregated_seal.signature)?; let apk = PublicKey::aggregate(public_keys); match apk.verify(&proposal_seal, &[], &sig, &*DIRECT_HASH_TO_G1) { Ok(_) => Ok(()), Err(_) => Err(Kind::BlsVerifyError.into()), } } fn prepare_commited_seal(hash: Hash, round: &Integer) -> Vec<u8> { let round_bytes = big_int_to_rlp_compat_bytes(&round); let commit_bytes = [IstanbulMsg::Commit as u8]; [&hash[..], &round_bytes[..], &commit_bytes[..]].concat() } fn deserialize_signature(signature: &[u8]) -> Result<Signature, Error> { Signature::deserialize(signature).map_err(|e| Kind::BlsInvalidSignature.context(e).into()) } fn deserialize_pub_key(key: &[u8]) -> Result<PublicKey, Error> { PublicKey::deserialize(key).map_err(|e| Kind::BlsInvalidPublicKey.context(e).into()) } <file_sep>pub mod bytes; pub mod rlp; <file_sep>/// Returns a reference to the elements of `$slice` as an array, verifying that /// the slice is of length `$len`. /// /// source: https://github.com/rust-lang/rfcs/issues/1833 #[macro_export] macro_rules! slice_as_array_ref { ($slice:expr, $len:expr) => { { use crate::errors::{Error, Kind}; fn slice_as_array_ref<T>(slice: &[T]) -> Result<&[T; $len], Error> { if slice.len() != $len { return Err( Kind::InvalidDataLength { expected: $len, current: slice.len(), } .into() ); } Ok(unsafe { &*(slice.as_ptr() as *const [T; $len]) }) } slice_as_array_ref($slice) } } }
d6ef18df3c2c0aa3911d239e19e127dcd290b3e0
[ "Markdown", "Rust", "TOML" ]
26
Rust
sekmet/celo-light-client
bff197a6dc685af86936414c825d809692631bcb
8c1fd41278db4968fe774fac0c5443e9243ba7cf
refs/heads/master
<file_sep>import requests from structures import * import lib import copy import json API_TOKEN = '9<PASSWORD>' def api_get(url: str, headers=dict()): headers = copy.deepcopy(headers) headers['Authorization'] = f'Bearer {API_TOKEN}' r = requests.get(f'https://poses.live/api/{url}', headers=headers) return r.json() def api_post(url: str, data, headers=dict()): headers = copy.deepcopy(headers) headers['Authorization'] = f'Bearer {API_TOKEN}' r = requests.post(f'https://poses.live/api/{url}', headers=headers, data=json.dumps(data)) return r.json() def load(problem: str) -> Input: inp = Input() inp.read_json(api_get(f'problems/{problem}')) inp.problem_id = problem return inp def submit(problem: str, solution: VerticesList): return api_post(f'problems/{problem}/solutions', data={'vertices': solution.to_json()}) def check_and_submit(problem: Input, solution: VerticesList): if not lib.is_valid(problem, solution, True): raise RuntimeError("Bad submission") dislikes = lib.count_dislikes(problem, solution) submit(problem.problem_id, solution) print(f"Submitted {problem.problem_id}, expected score is {dislikes}") <file_sep>import argparse from fractions import Fraction import json from shapely.geometry import polygon from shapely.geometry.linestring import LineString from shapely.geometry.point import Point from physics import Physics from lib import count_dislikes from structures import Figure, Input, Vec, VerticesList import random import net # Physics steps after each mutation PHYSICS_STEPS = 50 def eval_solution(problem: Input, solution: VerticesList): # TODO: Come up with better constants for the penalties # (currently just tweaked per problem) polygon = problem.hole_polygon penalty = 0.0 for a,b in problem.figure.edges: line = LineString([solution[a].to_tuple(), solution[b].to_tuple()]) outside = line.difference(polygon).length if outside > 0: penalty += 1000 + 100 * outside * outside dist_orig = (problem.figure.vertices[a] - problem.figure.vertices[b]).len2() dist_new = (solution[a] - solution[b]).len2() ratio = abs(Fraction(dist_new, dist_orig) - 1) bound = Fraction(problem.epsilon, int(1e6)) if ratio > bound: penalty += 1000 + 1000 * float(ratio - bound) for v in solution.vertices: outside = polygon.distance(Point(v.x, v.y)) if outside > 0: penalty += 1000 + 100 * outside penalty += count_dislikes(problem, solution) return penalty def mutate_solution(problem: Input, solution: VerticesList, deviation: float) -> VerticesList: # TODO: Idea, try making it more likely to select vertices that "matter" # e.g. ones that incur a penalty or closest to a hole vertex new_vertices = [] for i, v in enumerate(solution.vertices): dx = random.normalvariate(0, deviation) dy = random.normalvariate(0, deviation) new_vertices.append(v + Vec(dx, dy)) physics = Physics() vs = VerticesList(new_vertices) for _ in range(PHYSICS_STEPS): vs = physics.apply(problem, VerticesList(vs)) rounded = VerticesList([Vec(round(p.x), round(p.y)) for p in vs]) return rounded def crossover(s1: VerticesList, s2: VerticesList): vs = [random.choice([a, b]) for a, b in zip(s1.vertices, s2.vertices)] return VerticesList(vs) def hill_climb(problem: Input, sol: VerticesList): num_steps = 100 num_mutations = 20 start_deviation = 5 end_deviation = 1 for step in range(num_steps): deviation = start_deviation + (end_deviation - start_deviation) * step / (num_steps-1) new_sols = [sol] + [mutate_solution(problem, sol, deviation) for _ in range(num_mutations)] sol = min(new_sols, key=lambda sol: eval_solution(problem, sol)) print(step+1, eval_solution(problem, sol)) return sol def genetic_alg(problem: Input, init_sol: VerticesList): pop_size = 20 keep_top = 3 start_deviation = 10 end_deviation = 1 num_steps = 100 crossover_num = 5 population = [init_sol] * pop_size for step in range(num_steps): deviation = start_deviation + (end_deviation - start_deviation) * step / (num_steps-1) # keep the top `keep_top`, add mutations for each population member # and then all pairwise cross-overs for top `crossover_num` new_pop = population[:keep_top] for sol in population: new_pop.append(mutate_solution(problem, sol, deviation)) for i in range(crossover_num): for j in range(i+1, crossover_num): new_pop.append(crossover(population[i], population[j])) new_pop.sort(key=lambda sol: eval_solution(problem, sol)) population = new_pop[:pop_size] print(step+1, eval_solution(problem, population[0])) return population[0] def main(): argparser = argparse.ArgumentParser() argparser.add_argument('problem', type=int, help="Problem id") argparser.add_argument('--vertices', dest="vertices", help="Load vertices from a file (JSON)") argparser.add_argument('--output', dest="output", help="File to write vertices to (default stdout)") args = argparser.parse_args() problem = net.load(args.problem) if args.vertices: with open(args.vertices) as f: vs = VerticesList() vs.read_json(json.loads(f.read())) print("Loaded vertices:", vs) else: vs = problem.figure.vertices print("Starting..") # result = hill_climb(problem, vs) result = genetic_alg(problem, vs) result_json = json.dumps(result.to_json()) print("Done.\n") if args.output: with open(args.output, "w") as f: f.write(result_json) print("Wrote result to file", args.output) else: print(result_json) if __name__ == "__main__": main()<file_sep>from structures import * from shapely.geometry import LineString, Polygon from fractions import Fraction import typing def on_segment(p: Vec, a: Vec, b: Vec): return Vec.cross(a - p, a - b) == 0 and Vec.dot(p - a, p - b) <= 0 def dist(p: Vec, a: Vec, b: Vec): if Vec.dot(b - a, p - a) < 0: return (p - a).len() if Vec.dot(a - b, p - b) < 0: return (p - b).len() return abs((a - p).cross(b - p)) / (a - b).len() def inside_polygon(p: Vec, polygon: typing.List[Vec]): for i in range(len(polygon)): if on_segment(p, polygon[i], polygon[(i + 1) % len(polygon)]): return True count = 0 for i in range(len(polygon)): a = polygon[i] b = polygon[(i + 1) % len(polygon)] if a.y == b.y: continue if p.y < min(a.y, b.y) or p.y >= max(a.y, b.y): continue if a.y > b.y: a, b = b, a if Vec.cross(p - a, b - a) < 0: count += 1 return count % 2 == 1 def is_edge_valid(a: int, b: int, problem: Input, solution: VerticesList, print_message=False): polygon = problem.hole_polygon line = LineString([solution[a].to_tuple(), solution[b].to_tuple()]) if line.crosses(polygon): if print_message: print(f"edge {a}-{b} crosses polygon") return False dist_orig = (problem.figure.vertices[a] - problem.figure.vertices[b]).len2() dist_new = (solution[a] - solution[b]).len2() ratio = abs(Fraction(dist_new, dist_orig) - 1) if ratio > Fraction(problem.epsilon, int(1e6)): if print_message: print(f"edge {a}-{b} has bad length, target: {dist_orig}, reality: {dist_new}") return False return True def is_valid(problem: Input, solution: VerticesList, print_message=False): for (a, b) in problem.figure.edges: if not is_edge_valid(a, b, problem, solution, print_message): return False for a in range(len(solution)): if not inside_polygon(solution[a], problem.hole.vertices): if print_message: print(f"vertex {a} not inside the hole") return False return True # assumes solution is valid def count_dislikes(problem: Input, solution: VerticesList): dislikes = 0 for h in problem.hole: closest = int(1e18) for v in solution: closest = min(closest, (h - v).len2()) dislikes += closest return dislikes<file_sep>from re import S from lib import count_dislikes, is_edge_valid import typing from structures import Vec, Figure, VerticesList, Input import copy from shapely.geometry import Point import net import argparse import time import itertools import math # this file contains a branch-and-bound algorithm to solve the problem by trying all combinations (but in a smart way).The run time can become really terrible, so it won't finish on many problem instances in a reasonable time # it's reasonable if there are few legal points and if the figure has only few vertices, all of which are highly connected best_found_dislikes = 9999999999 # returns a set containing all legal points, i.e.Vec within the polygon def all_legal_points(problem: Input): x_coords = [v.x for v in problem.hole] y_coords = [v.y for v in problem.hole] result = set() for x in range(min(x_coords), max(x_coords)+1): for y in range(min(y_coords), max(y_coords)+1): p = Point((x, y)) if p.intersection(problem.hole_polygon): result.add(Vec(x,y)) return result # assumes the point p is within the polygon def is_point_valid(p: Vec, a: int, fixed: typing.Set[int], problem: Input, solution: VerticesList): solution[a] = p for b in problem.figure.neighbors[a]: if b not in fixed: continue if not is_edge_valid(a, b, problem, solution): return False return True def branch_and_bound(fixed: typing.Set[int], remaining: typing.List[Vec], problem: Input, solution: VerticesList, all_legal_points: typing.Set[Vec], optimum: int = 0): if not remaining: global best_found_dislikes dislikes = count_dislikes(problem, solution) if dislikes < best_found_dislikes: print(f"found a solution with {dislikes} dislikes") best_found_dislikes = dislikes return solution, dislikes a = remaining.pop() fixed.add(a) options = [p for p in all_legal_points if is_point_valid(p, a, fixed, problem, solution)] # if len(options) > 2: print(f"point {a} has {len(options)} options") best_solution = None dislikes = 99999999 for round, p in enumerate(options): if (len(fixed) == 1): print(f"start round {round} of {len(options)}") solution[a] = p s, d = branch_and_bound(fixed, remaining, problem, solution, all_legal_points) if s and d < dislikes: best_solution = copy.deepcopy(s) dislikes = d if d == optimum: break remaining.append(a) fixed.remove(a) return best_solution, dislikes # ideas for improvement: # - compute good order # - treat order as a tree: if independent component can't find solution, there is no point in continuing # - store intermediate best solutions, so we can stop early def heuristic_order(fixed, remaining, problem: Input): remaining = set(remaining) rev_order = [] connectivity = dict([(i, 0) for i in remaining]) for a in remaining: for b in problem.figure.neighbors[a]: if b in fixed: connectivity[a] += 1 while remaining: max_connectivity = max(connectivity.values()) candidates = [a for a in remaining if connectivity[a] == max_connectivity] a = max(candidates, key=lambda a : len(problem.figure.neighbors[a])) rev_order.append(a) remaining.remove(a) del connectivity[a] for b in problem.figure.neighbors[a]: if b in remaining: connectivity[b] += 1 return list(reversed(rev_order)) def run_branch_and_bound_for_perfect_solution(problem: Input): legal_points = all_legal_points(problem) solution = copy.deepcopy(problem.figure.vertices) hole = problem.hole figure_indices = range(len(problem.figure.vertices)) n = len(figure_indices) k = len(hole) max_round = math.factorial(n) / math.factorial(n-k) print(f"there are {k} hole vertices and {n} figure vertices, {max_round} rounds") round = 0 for perm in itertools.permutations(figure_indices, len(hole)): round += 1 if round % 100000 == 0: print(f"checkpoint {round}") fixed = set() valid = True for i in range(len(hole)): fixed.add(i) solution[perm[i]] = hole[i] if not is_point_valid(hole[i], perm[i], fixed, problem, solution): valid = False break if not valid: continue remaining = [i for i in figure_indices if i not in fixed] remaining = heuristic_order(fixed, remaining, problem) print(f"starting round {round} of {max_round}") result, dislikes = branch_and_bound(fixed, remaining, problem, solution, legal_points, 0) if result: return result, dislikes print("Could not find any perfect solution!") return None, -1 def run_branch_and_bound(problem: Input, optimum: int = 0): legal_points = all_legal_points(problem) solution = copy.deepcopy(problem.figure.vertices) remaining = heuristic_order(set(), [i for i in range(len(solution))], problem) solution, dislikes = branch_and_bound(set(), remaining, problem, solution, legal_points, optimum) return solution argparser = argparse.ArgumentParser() argparser.add_argument('problem', type=int, help="Problem id") argparser.add_argument('optimum', type=int, help="minimum number of dislikes (algorithm can terminate once it finds a solution of this quality)") args = argparser.parse_args() problem = net.load(args.problem) optimum = args.optimum best_found_dislikes = 9999999999 start = time.time() if optimum > 0: solution = run_branch_and_bound(problem, optimum) else: run_branch_and_bound_for_perfect_solution(problem) end = time.time() print(f"the algorithm took {end - start} seconds") net.check_and_submit(problem, solution)<file_sep>import typing import copy from abc import ABCMeta, abstractmethod from shapely.geometry import Polygon class Vec: @staticmethod def dist2(a, b): return (a.x - b.x) ** 2 + (a.y - b.y) ** 2 @staticmethod def dist(a, b): return ((a.x - b.x) ** 2 + (a.y - b.y) ** 2) ** 0.5 def __init__(self, x=0, y=0): self.x = x self.y = y def __repr__(self): return f'Vec({self.x}, {self.y})' def __add__(self, other): return Vec(self.x + other.x, self.y + other.y) def __sub__(self, other): return Vec(self.x - other.x, self.y - other.y) def __imul__(self, k): self.x *= k self.y *= k return self def __iadd__(self, other): self.x += other.x self.y += other.y return self def __isub__(self, other): self.x -= other.x self.y -= other.y return self def __rmul__(self, k): return Vec(k * self.x, k * self.y) def len2(self): return self.x * self.x + self.y * self.y def len(self): return self.len2() ** 0.5 @staticmethod def dot(v1, v2): return v1.x * v2.x + v1.y * v2.y @staticmethod def cross(v1, v2): return v1.x * v2.y - v1.y * v2.x def norm(v): return Vec(v.x / v.len(), v.y / v.len()) def __eq__(self, b): return self.x == b.x and self.y == b.y def __hash__(self): return hash((self.x, self.y)) def to_tuple(self): return (self.x, self.y) # Hole # solution # Figure.vertices class VerticesList: def __init__(self, vertices: typing.List[Vec] = []): self.vertices = copy.deepcopy(vertices) def read_json(self, data: typing.List[list]): self.vertices = [Vec(pt[0], pt[1]) for pt in data] def to_json(self): return [[vec.x, vec.y] for vec in self.vertices] def __repr__(self): return 'VerticesList([' + ','.join(repr(v) for v in self.vertices) + '])' def __getitem__(self, i): return self.vertices[i] def __setitem__(self, i, val): self.vertices[i] = val def __len__(self): return len(self.vertices) # interprets the vertices list as a shapley polygon def to_polygon(self): return Polygon([v.to_tuple() for v in self.vertices]) class Figure: def __init__(self, vertices: VerticesList = VerticesList(), edges: typing.List[typing.Tuple[int, int]] = []): self.vertices = copy.deepcopy(vertices) self.edges = copy.deepcopy(edges) self.neighbors = self.compute_neighbors() def read_json(self, data): self.vertices.read_json(data['vertices']) self.edges = [(pt[0], pt[1]) for pt in data['edges']] self.neighbors = self.compute_neighbors() def __repr__(self): return f'Figure(vertices={self.vertices}, edges={self.edges})' def compute_neighbors(self): indices = [i for i in range(len(self.vertices))] neighbors = dict([(i, []) for i in indices]) for a, b in self.edges: neighbors[a].append(b) neighbors[b].append(a) return neighbors class Input: def __init__(self, hole: VerticesList = VerticesList(), figure: Figure = Figure(), epsilon=0, problem_id=None): self.hole = copy.deepcopy(hole) self.hole_polygon = self.hole.to_polygon() self.figure = copy.deepcopy(figure) self.epsilon = epsilon self.problem_id = problem_id def read_json(self, data): self.epsilon = data['epsilon'] self.figure.read_json(data['figure']) self.hole.read_json(data['hole']) self.hole_polygon = self.hole.to_polygon() def __repr__(self): return f'Input(hole={self.hole}, figure={self.figure}, epsilon={self.epsilon})' class Transformation(object, metaclass=ABCMeta): def __init__(self): pass @staticmethod def apply_all(transformations, data: Input): vertices = copy.deepcopy(data.figure.vertices) for t in transformations: vertices = t.apply(data, vertices) return vertices @abstractmethod def apply(self, data: Input, cur: VerticesList) -> VerticesList: return data.figure.vertices <file_sep>import json from PyQt5.QtCore import QPoint, Qt from PyQt5.QtWidgets import QApplication, QWidget from PyQt5.QtGui import QPainter, QBrush, QPen import argparse import sys import net import random from structures import * from physics import Physics class ICFPCPainter(QWidget): POINT_RADIUS = 4 WIDTH = 700 HEIGHT = 700 MARGIN = 50 DRAG_THRESHOLD = 9 def __init__(self, input, input_vertices=None): super(QWidget, self).__init__() self.setGeometry(0, 0, ICFPCPainter.WIDTH, ICFPCPainter.HEIGHT) self.hole = input.hole self.input = input self.figure = copy.deepcopy(input.figure) if input_vertices: self.figure.vertices = copy.deepcopy(input_vertices) self.is_pinned = [False for x in self.figure.vertices] self.dragging = False self.init_cds() self.show() def init_cds(self): xs = list(map(lambda x: x.x, self.hole.vertices + self.figure.vertices.vertices)) ys = list(map(lambda x: x.y, self.hole.vertices + self.figure.vertices.vertices)) self.center = 0.5 * Vec(min(xs) + max(xs), min(ys) + max(ys)) self.scale_factor = max(max(xs) - min(xs), max(ys) - min(ys)) * 1.5 self.user_scale = 1.0 def scale(self, p): transformed = (self.user_scale / self.scale_factor) * (p - self.center) + Vec(0.5, 0.5) return transformed.x * ICFPCPainter.HEIGHT, transformed.y * ICFPCPainter.HEIGHT def unscale(self, transformed): transformed = Vec(transformed[0], transformed[1]) transformed = (1 / ICFPCPainter.HEIGHT) * transformed transformed -= Vec(0.5, 0.5) transformed *= self.scale_factor / self.user_scale return transformed + self.center def paintEvent(self, e): self.draw_input() def draw_input(self): self.qp = QPainter() self.qp.begin(self) self.draw_grid() self.draw_hole() self.draw_figure() self.qp.end() def keyPressEvent(self, e): if e.key() == Qt.Key_S: try: rounded = VerticesList([Vec(round(p.x), round(p.y)) for p in self.figure.vertices]) net.check_and_submit(self.input, rounded) except Exception as ex: print(ex) elif e.key() == Qt.Key_I: rounded = VerticesList([Vec(round(p.x), round(p.y)) for p in self.figure.vertices]) self.figure.vertices = rounded self.update() elif e.key() == Qt.Key_P: state = self.figure.vertices for go in [0.1, 0.05, 0.001]: physics = Physics(go, self.is_pinned) for steps in range(int(1e3)): state = physics.apply(self.input, state) self.figure.vertices = state self.update() elif e.key() == Qt.Key_R: xs = list(map(lambda x: x.x, self.hole.vertices)) ys = list(map(lambda x: x.y, self.hole.vertices)) for i, _ in enumerate(self.figure.vertices): rx = random.uniform(min(xs), max(xs)) ry = random.uniform(min(ys), max(ys)) self.figure.vertices[i] = Vec(rx, ry) self.update() elif e.key() == Qt.Key_U: edges = copy.deepcopy(self.input.figure.edges) random.shuffle(edges) for i, u2 in enumerate(self.input.hole): u1 = self.input.hole[i - 1] h_len = (u1 - u2).len2() for e in edges: if self.is_pinned[e[0]] or self.is_pinned[e[1]]: continue from fractions import Fraction v1 = self.input.figure.vertices[e[0]] v2 = self.input.figure.vertices[e[1]] p_len = (v1 - v2).len2() ratio = abs(Fraction(h_len, p_len) - 1) if ratio <= Fraction(self.input.epsilon, int(1e6)): self.figure.vertices[e[0]] = copy.deepcopy(u1) self.figure.vertices[e[1]] = copy.deepcopy(u2) break self.update() elif e.key() == Qt.Key_Plus: self.user_scale *= 1.1 self.update() elif e.key() == Qt.Key_Minus: self.user_scale /= 1.1 self.update() elif e.key() == Qt.Key_Left: self.center.x -= (ICFPCPainter.HEIGHT / 40) / self.user_scale self.update() elif e.key() == Qt.Key_Right: self.center.x += (ICFPCPainter.HEIGHT / 40) / self.user_scale self.update() elif e.key() == Qt.Key_Up: self.center.y -= (ICFPCPainter.HEIGHT / 40) / self.user_scale self.update() elif e.key() == Qt.Key_Down: self.center.y += (ICFPCPainter.HEIGHT / 40) / self.user_scale self.update() else: self.figure.vertices = Physics(is_pinned=self.is_pinned).apply(self.input, self.figure.vertices) self.update() def draw_grid(self): self.qp.setPen(QPen(Qt.gray, Qt.SolidLine)) for x in range(-50, ICFPCPainter.WIDTH): self.draw_line(Vec(x, -50), Vec(x, ICFPCPainter.HEIGHT)) for y in range(-50, ICFPCPainter.HEIGHT): self.draw_line(Vec(-50, y), Vec(ICFPCPainter.WIDTH, y)) def draw_hole(self): self.qp.setPen(QPen(Qt.black, Qt.SolidLine)) for i in range(len(self.hole.vertices)): self.draw_line(self.hole.vertices[i - 1], self.hole.vertices[i]) self.qp.setBrush(QBrush(Qt.gray, Qt.SolidPattern)) self.draw_point(self.hole.vertices[i]) def draw_figure(self): from fractions import Fraction for u, v in self.figure.edges: new_d = self.figure.vertices.vertices[u] - self.figure.vertices.vertices[v] old_d = self.input.figure.vertices.vertices[u] - self.input.figure.vertices.vertices[v] correct_coef = Fraction(self.input.epsilon / 10 ** 6) coef = Fraction((new_d.x * new_d.x + new_d.y * new_d.y) / (old_d.x * old_d.x + old_d.y * old_d.y) - 1) if abs(coef) > correct_coef: if (coef > 0): pen = QPen(Qt.blue, Qt.SolidLine) else: pen = QPen(Qt.red, Qt.SolidLine) else: pen = QPen(Qt.darkGreen, Qt.SolidLine) pen.setWidth(3) self.qp.setPen(pen) self.draw_line(self.figure.vertices.vertices[u], self.figure.vertices.vertices[v]) self.qp.setPen(QPen(Qt.green, Qt.SolidLine)) for (pin, v) in zip(self.is_pinned, self.figure.vertices.vertices): if pin: self.qp.setBrush(QBrush(Qt.darkRed, Qt.SolidPattern)) else: self.qp.setBrush(QBrush(Qt.darkGreen, Qt.SolidPattern)) self.draw_point(v) def draw_point(self, point): r = ICFPCPainter.POINT_RADIUS self.qp.drawEllipse(QPoint(*self.scale(point)), r, r) def draw_line(self, a, b): self.qp.drawLine(QPoint(*self.scale(a)), QPoint(*self.scale(b))) def mousePressEvent(self, e): self.dragging = None pos = self.unscale((e.pos().x(), e.pos().y())) mndist_id = 0 mndist = 1e18 for i in range(len(self.figure.vertices.vertices)): new_mndist = (self.figure.vertices.vertices[i] - pos).len2() if new_mndist < mndist: mndist = new_mndist mndist_id = i if mndist > ICFPCPainter.DRAG_THRESHOLD: return if e.buttons() & Qt.RightButton: self.is_pinned[mndist_id] = not self.is_pinned[mndist_id] self.update() else: if not self.is_pinned[mndist_id]: self.dragging = mndist_id def mouseMoveEvent(self, e): if self.dragging is not None: self.figure.vertices.vertices[self.dragging] = self.unscale((e.pos().x(), e.pos().y())) self.update() def mouseReleaseEvent(self, e): self.dragging = None def main(): argparser = argparse.ArgumentParser() argparser.add_argument('problem', type=str, help="Problem id") argparser.add_argument('--vertices', dest="vertices", help="Load vertices from a file (JSON)") args = argparser.parse_args() problem_input = net.load(args.problem) if args.vertices: with open(args.vertices) as f: vs = VerticesList() vs.read_json(json.loads(f.read())) print("Loaded vertices:", vs) else: vs = None app = QApplication(sys.argv) window = ICFPCPainter(problem_input, vs) app.exec_() if __name__ == "__main__": main() <file_sep>from structures import * class Physics(Transformation): def __init__(self, k=0.05, is_pinned=None): super(Transformation, self).__init__() self.k = k self.is_pinned = is_pinned def apply(self, data: Input, cur: VerticesList) -> VerticesList: forces = [Vec() for _ in cur] vertices = [] def sign(a): if a < 0: return -1 if a > 0: return +1 return 0 deltas = [] dists = [] for i, e in enumerate(data.figure.edges): a, b = data.figure.vertices[e[0]], data.figure.vertices[e[1]] a_cur, b_cur = cur[e[0]], cur[e[1]] import math delta = Vec.dist(a, b) - Vec.dist(a_cur, b_cur) if a_cur != b_cur: forces[e[0]] += self.k * delta * (a_cur - b_cur).norm() forces[e[1]] += self.k * delta * (b_cur - a_cur).norm() else: # Select arbitrary direction forces[e[0]] += self.k * delta * Vec(1,0) forces[e[1]] += self.k * delta * Vec(-1,0) if self.is_pinned: for i, val in enumerate(self.is_pinned): if val: forces[i] = Vec() for i, v in enumerate(cur): vertices.append(v + forces[i]) return VerticesList(vertices)
f27dfd019c80a3eb59a5fc1f102cf188f8898b1d
[ "Python" ]
7
Python
cdkrot/icfpc2021
148ee41e3c3ec7d44f9a10a691d1e0d49a2afc18
63730f5492a13c694fd1ccc2eebb83c3fab321e3
refs/heads/master
<file_sep>let sketch = function (p) { const particles = []; p.setup = function () { p.createCanvas(window.innerWidth, window.innerHeight); const particlesLength = Math.floor(window.innerWidth / 10); for (let i = 0; i < particlesLength; i++) { particles.push(new Particle()); } }; p.draw = function () { p.background(37, 41, 52); particles.map((particle, index) => { particle.update(); particle.draw(); particle.checkParticles(particles.slice(index)); }); }; class Particle { constructor() { // Position this.pos = p.createVector(p.random(p.width), p.random(p.height)); // Size this.size = 5; // Velocity this.vel = p.createVector(p.random(-3, 3), p.random(-2, 2)); } update() { this.pos.add(this.vel); this.edges(); } // draw() { // p.noStroke(); // // p.circle(this.pos.x, this.pos.y, this.size); // } draw() { const randomBetween = (min, max) => min + Math.floor(Math.random() * (max - min + 1)); const r = randomBetween(0, 255); const g = randomBetween(0, 255); const b = randomBetween(0, 255); p.noStroke(); // p.fill("#" + (((1 << 24) * Math.random()) | 0).toString(16)); p.fill(`rgba(${r},${g},${b},.8)`); p.circle(this.pos.x, this.pos.y, this.size); } edges() { if (this.pos.x < 0 || this.pos.x > p.width) { this.vel.x *= -1; } if (this.pos.y < 0 || this.pos.y > p.height) { this.vel.y *= -1; } } checkParticles(particles) { particles.map((particle) => { const distance = p.dist( this.pos.x, this.pos.y, particle.pos.x, particle.pos.y ); if (distance < 100) { p.stroke('rgba(255,255,255,0.1)'); p.line(this.pos.x, -100, particle.pos.x, particle.pos.y); } }); } } }; new p5(sketch, 'header');
de9d95ca899d4119f398dc1913a274a631fa4012
[ "JavaScript" ]
1
JavaScript
rabiulalam1/ParticleJS
47809dcd2ce2a4db9b90852d7931dd6937ca7691
2d85e32b63c327c97fade14e76ea36cc2b8c99c6
refs/heads/master
<repo_name>frankatacorner/S18ESM262FW<file_sep>/S18_ESM262_HW1_FrankWang.Rmd --- title: "S18_ESM262_HW1_FrankWang" author: "<NAME>" date: "5/2/2018" output: html_document --- ```{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE) ``` ## Import and Tidy **Question 1.** Read the gazetteer data as-is (all columns; no type conversion) into a `gaz_raw` _tibble_. **Answer** Import the tidyverse library in case it is not available on the current device by using the `library("tidyverse")` command in R. ```{r tidyverse, echo=TRUE} library("tidyverse") ``` Set the working directory to where data is available. ```{r directory, echo=TRUE} setwd("~/OneDrive/MA Year 4/S18_ESM262") ``` Import the gazetteer data into RStudio. ```{r Q1. raw import, echo=TRUE} gaz_raw <- read_delim("CA_Features_20180401.txt", delim = "|", col_names = T) ``` **Question 2.** Copy only the following columns into a `gaz` tibble (you can rename them if you like): feature ID/feature name/feature class/state alpha/county name/primary latitude (decimal)/primary longitude (decimal)/source latitude (decimal)/source longitude (decimal)/elevation in meters/map name/date created/date edited. **Answer** Use the `select` function and pick out desired columns. ```{r Q2. select columns, echo=TRUE} gaz <- gaz_raw %>% select(starts_with("feature", ignore.case = T), STATE_ALPHA, COUNTY_NAME, ends_with("DEC", ignore.case = F), ELEV_IN_M, MAP_NAME, starts_with("date", ignore.case = T)) ``` **Question 3.** Convert the `gaz` columns to the appropriate type. Convert any placeholders for unknown data to `NA`. **Answer** Convert any entry with "Unknown" to `NA`. ```{r Q3. eliminate unkowns, echo=TRUE} gaz[gaz == "Unknown"] <- NA ``` Create two new columns for "date created" and "date edited" information, and attach them to the `gaz` tibble with `mutate` function after selecting the columns from `gaz` that have the appropriate types. ```{r Q3. column type, echo=TRUE} date_created <- parse_date(gaz$DATE_CREATED, format = "%m/%d/%Y") date_edited <- parse_date(gaz$DATE_EDITED, format = "%m/%d/%Y") gaz <- gaz %>% select(starts_with("feature", ignore.case = T), STATE_ALPHA, COUNTY_NAME, ends_with("DEC", ignore.case = F), ELEV_IN_M, MAP_NAME) %>% mutate(., date_created, date_edited) ``` **Question 4.** Delete from `gaz` rows where: * the **primary** latitude or longitude are unknown * the feature is not in California **Answer** Use the `filter` function to select rows that record features in California `filter(gaz, STATE_ALPHA == "CA")`, and pipe the results into another filter to make sure there is no missing value in primary latitude or primary longitude, then pipe the results again to remove primary coordinates that contain zero. Notice that !x & !y is the same as !(x | y). ```{r delete rows} gaz <- filter(gaz, STATE_ALPHA == "CA") %>% filter(., !is.na(PRIM_LAT_DEC) & !is.na(PRIM_LONG_DEC)) %>% filter(!(PRIM_LAT_DEC == 0 | PRIM_LONG_DEC == 0)) ``` **Question 5.** Write the `gaz` tibble to a CSV file (using `"|"` as a delimiter). **Answer** Use the `write_delim` function to set the deliminator as "|", which `write_csv` is not able to do. Specify the type of file, csv, in the file path instead. ```{r write out csv} write_delim(gaz, "CA_features_20180401_clean.csv", delim = "|", na = "NA", append = F) ``` *** ## Analyze Create R code snippets that answer the following questions about California: **Question 1.** What is the most-frequently-occurring _feature_ name? **Answer** Group the data set by its feature name using the `group_by` function, then count the occurrence of each feature name, sorted from the largest to the smallest. ```{r sort feature name} feature_name <- group_by(gaz, FEATURE_NAME) feat_name_count <- tally(feature_name, sort = T) head(feat_name_count, n = 1) ``` The most-frequently-occurring feature name is `r head(feat_name_count, n = 1)` **Question 2.** What is the least-frequently-occurring feature class? **Answer** Group the data set by its feature class using the `group_by` function, then count the occurrence of each feature class, sorted from the largest to the smallest. ```{r sort feature class} feature_class <- group_by(gaz, FEATURE_CLASS) feat_class_count <- tally(feature_class, sort = T) ``` The bottom five rows of the feature_count tibble is displayed, essentially showing us the least-frequently-occurring feature classes. ```{r check tail of feature class, echo=TRUE} tail(feat_class_count, n = 5) ``` As there are two feature classes that appear only once, we can add a `filter` to pick them out. ```{r choose tail of feature class, echo=TRUE} tail(feat_class_count, n = 5) %>% filter(n == 1) ``` The least-frequently-occurring feature classes are _Isthmus_ and _Sea_. (*Note: the "occurring" in the current version of the assignment has a missing letter "r".*) **Question 3.** What is the approximate center point of each county? * Hint: Calculate the center of the bounding box of the county’s **point** features. **Answer** Group the gazetteer data by county name and calculate the mean coordinates of each county. The approximate center point of some county is listed below (latitude & longitude). ```{r county centers, echo=TRUE} county_name <- group_by(gaz, COUNTY_NAME) summarise(county_name, mean_lat = mean(PRIM_LAT_DEC), mean_lon = mean(PRIM_LONG_DEC)) ``` **Question 4.** What are the fractions of the total number of features in each county that are natural? man-made? * Hint: Construct a tibble with two columns, one containing all possible feature classes (see “[Feature Class Definitions](https://geonames.usgs.gov/apex/f?p=gnispq:8:0:::::)”), and another containing the string “natural” or “man-made”, which you assign (it’s pretty obvious.) Then join this tibble to the gazetteer tibble. **Answer** The "[Feature Class Definitions](https://geonames.usgs.gov/apex/f?p=gnispq:8:0:::::)" has been downloaded as "Class_Code_Definitions.csv" in the working directory. Manually classify the 65 classes by using a vector of characters and create a `class_and_type` tibble by selecting the class names and class types. ```{r import class code as a tibble} n <- "natural" a <- "man-made" class_type <- c(a, n, n, n, n, n, n, n, n, n, a, a, a, n, n, a, a, n, a, a, n, n, a, a, n, n, n, n, n, n, a, a, n, n, n, n, a, a, a, a, a, a, n, n, a, a, n, n, a, a, n, a, n, n, n, n, n, n, a, a, a, n, n, a, n) class_code <- read_delim("Class_Code_Definitions.csv", delim = ",", col_names = T) class_and_type <- select(class_code, Class) %>% mutate(Class, class_type) ``` Now this `class_and_type` tibble can be used to join with the gazetteer tibble, after which the data is grouped by class type to allow for counting of their occurrences. ```{r} left_join(gaz, class_and_type, by = c("FEATURE_CLASS" = "Class")) %>% group_by(class_type) %>% tally() ``` The tally shows that there are 82240 man-made features and 38982 natural features, which translates to `r 82240/(82240+38982)` fraction of man-made features and `r 38982/(82240+38982)` fraction of natural features. **Concluding remarks** I adore this assignment greatly. I don't have much experience with programming and this is the first time I wrote codes in R (and in R Markdown) that allowed me to see the potential of its application. If time allows, could you address the following two questions in class? 1. Convert the `gaz` columns to the appropriate type. Convert any placeholders for unknown data to `NA`. 2. For the most/least frequently occurring features, is there a way to further pipe the results from `tally`, instead of having to wait and see the numbers? 3. Somehow when I tried to use `summarise` on some grouped data, the program would not return the counts. I decided to use `tally` after consulting the help menu, but wonder if there is some trick to make `summarise` work. **Thank you!**<file_sep>/ESM262_HW3_FW.Rmd --- title: "ESM262_HW3_FW" author: "<NAME>" date: "6/6/2018" output: html_document --- ```{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE) ``` ```{r install required packages} #install.packages("roxygen2") #install.packages("devtools") library(roxygen2) library(devtools) library(ggplot2) ``` ## Generate Data for the Fish Market Function ``` {r} # create a list of possible fish to sample from possible_fish = c("anchovy","eel","halibut","mackerel","trout","tuna") # generate typical prices for each possible fish prices = data.frame(fish=possible_fish, price=c(20,30,10,25,18,20)) locs = c("California","Washington","Hokkaido","Baha","Peru") # Create an empty data frame with proper dimensions to hold fish catch data to be generated example_catch = matrix(nrow=length(possible_fish), ncol=length(locs)) colnames(example_catch)=locs rownames(example_catch)=possible_fish # Simulate different productivities or typical size of catch at each locale locs = data.frame(name=locs, size = c(2000,2000,5000,4000,7000)) # and different relative population size for fish for ( i in 1:length(possible_fish)) { for (j in 1:nrow(locs)) { example_catch[i,j] = round(rnorm(mean=locs$size[j], sd=0.15*locs$size[j], n=1)) } } # run function # fisheries_summary(catches=example_catch, prices=prices, plot=FALSE) # try with a plot fisheries_summary(catches=example_catch, prices=prices, plot=TRUE) ``` ## Fish Growth Rate vs. Temperature ```{r} library(tidyverse) input_para <- read_csv("Table2.csv", col_names = T) a = input_para$a b = input_para$b c = input_para$c d = input_para$d fish_growth(20) ``` Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot. <file_sep>/README.md # S18ESM262FW Collection of assignments and documents for ESM 262 (Spring 2018) created by <NAME> <file_sep>/S18_ESM262_HW2_FrankWang_clean.Rmd --- title: "S18 ESM 262 Assignment 2 Database" author: "<NAME>" date: "5/15/2018" output: html_document --- ```{r setup, include=FALSE} knitr::opts_chunk$set( echo = TRUE, message = FALSE, warning = FALSE ) library(DBI) library(dplyr) library(dbplyr) library("tidyverse") ``` ## Create database **Replace** step 5 (“Write the `gaz` tibble to a CSV file …”) with: 1. Create a connection to a new `gaz.db` SQLite database. 2. Copy the `gaz` tibble into the `gaz.db` database. **Answer 1** Install the dbplyr package in case it is not available on the current device by using the `install.packages("dbplyr")` command in R. ``` {r Import dbplyr, echo=TRUE} # install.packages("dbplyr") ``` Load the library `dbplyr` and establish a connection to a new `gaz.db` SQLite databse. ``` {r Databse connection, echo=TRUE, collapse = TRUE} gaz_db <- DBI::dbConnect(RSQLite::SQLite(), path = ":memory:") ``` **Answer 2** Create a `gaz` tibble by importing the cleaned csv file from the previous assignment using the `read_delim` function from tidyverse. Alternatively, re-run the codes from the previous assignment to re-create the gaz tibble. ``` {r Create gaz tibble, echo=TRUE} gaz <- read_delim("../S18_ESM262_HW1/CA_features_20180401_clean.csv",delim = "|", col_names = T) ``` Copy the `gaz` tibble into the `gaz.db` database by using the `copy_to()` function. ```{r Copy to gaz.db, echo=TRUE} copy_to(gaz_db, gaz, "gaz", overwrite = TRUE) ``` ## Analyze Using SQL queries and the dbGetQuery function, create R code snippets that answer the following questions about California: 1. What is the most-frequently-occuring feature name? Use the `dbGetQuery` function to send query in SQL and assign the result into a variable called `gaz_feat_name`. The query asks SQLite to select the feature name based on the occurrence of features from our gaz database in a descending order. ```{r Most feature} gaz_feat_name <- dbGetQuery(gaz_db, "SELECT FEATURE_NAME AS 'Most frequently occuring feature', COUNT(FEATURE_NAME) AS Occurrence FROM gaz GROUP BY FEATURE_NAME ORDER BY COUNT(FEATURE_NAME) DESC LIMIT 1;") ``` **Answer 1:** The most frequently occuring feature was **`r gaz_feat_name[,1]`**. 2. What is the least-frequently-occuring feature class? Use the `dbGetQuery` function to send query in SQL and assign the result into a variable called `gaz_class_name`. The query asks SQLite to select the feature class based on the occurrence of classes from our gaz database in an ascending order. ```{r Least class} gaz_class_name <- dbGetQuery(gaz_db, "SELECT FEATURE_CLASS AS 'Least frequently occuring class' FROM gaz GROUP BY FEATURE_CLASS ORDER BY COUNT(FEATURE_CLASS) ASC LIMIT 5;" ) ``` **Answer 2:** The least frequently occuring feature class was **`r gaz_class_name[1,]`**. 3. What is the approximate center point of each county? Calculate the center of the bounding box of the county’s **point** features by finding the minima and the maxima of the latitudes and longitudes of the point features in each county. ```{r county coordinates, echo=TRUE, warning=FALSE} # This chunk was produced during experimenting with SQL syntax and can display the minimum and maximum latitude and longitude of each county, but the display is not needed for calculating the county centers county_coor <- dbGetQuery(gaz_db, "SELECT COUNTY_NAME AS 'County', min(PRIM_LAT_DEC) AS 'County latitude minima', max(PRIM_LAT_DEC) AS 'County latitude maxima', min(PRIM_LONG_DEC) AS 'County longitude minima', max(PRIM_LONG_DEC) AS 'County longitude maxima' FROM gaz WHERE COUNTY_NAME IS NOT NULL GROUP BY COUNTY_NAME ORDER BY COUNTY_NAME ASC") ``` ```{r county centers, echo=TRUE} county_center <- dbGetQuery(gaz_db, "SELECT COUNTY_NAME AS 'County', round((min(PRIM_LAT_DEC)+max(PRIM_LAT_DEC))/2, 5) AS 'County Center Lat', round((min(PRIM_LONG_DEC)+max(PRIM_LONG_DEC))/2, 5) AS 'County Center Lon' FROM gaz WHERE COUNTY_NAME IS NOT NULL GROUP BY COUNTY_NAME ORDER BY COUNTY_NAME ASC") ``` **Answer 3:** The coordinates of the approximate center point of each county are displayed in the table below. ``` {r} county_center ``` 4. What are the fractions of the total number of features in each county that are natural? man-made? + Hint: Copy the feature class categories tibble you created into the gaz.db database. Then you can JOIN it to the the gaz table. ```{r} class_code <- read_delim("../S18_ESM262_HW1/Class_Code_Definitions.csv", delim = ",", col_names = T) n <- "natural" a <- "man-made" class_type <- c(a, n, n, n, n, n, n, n, n, n, a, a, a, n, n, a, a, n, a, a, n, n, a, a, n, n, n, n, n, n, a, a, n, n, n, n, a, a, a, a, a, a, n, n, a, a, n, n, a, a, n, a, n, n, n, n, n, n, a, a, a, n, n, a, n) class_and_type <- select(class_code, Class) %>% mutate(Class, class_type) dbWriteTable(gaz_db, name = "Class_Info", class_and_type, overwrite = T, row.names = NULL, temporary = FALSE) Natural_by_county <- dbGetQuery(gaz_db, "SELECT COUNTY_NAME AS County, count(class_type) AS Natural_Feature_Tally FROM gaz JOIN Class_Info ON gaz.FEATURE_CLASS = Class_Info.Class WHERE Class_Type = 'natural' AND COUNTY_NAME IS NOT NULL GROUP BY COUNTY_NAME ORDER BY COUNTY_NAME ASC;") Manmade_by_county <- dbGetQuery(gaz_db, "SELECT COUNTY_NAME AS County, count(class_type) AS ManMade_Feature_Tally FROM gaz JOIN Class_Info ON gaz.FEATURE_CLASS = Class_Info.Class WHERE Class_Type = 'man-made' AND COUNTY_NAME IS NOT NULL GROUP BY COUNTY_NAME ORDER BY COUNTY_NAME ASC;") Feature_by_county <- left_join(as_tibble(Natural_by_county), as_tibble(Manmade_by_county), by = c("County" = "County")) Natural_Feat_Fraction <- round(Feature_by_county$Natural_Feature_Tally/(Feature_by_county$Natural_Feature_Tally+Feature_by_county$ManMade_Feature_Tally)*100, 1) Manmade_Feat_Fraction <- round(Feature_by_county$ManMade_Feature_Tally/(Feature_by_county$Natural_Feature_Tally+Feature_by_county$ManMade_Feature_Tally)*100, 1) Feature_by_county <- add_column(Feature_by_county, Natural_Feat_Fraction, Manmade_Feat_Fraction) Feature_by_county ``` **Answer 4:** The fractions of the total number of features in each county that are natural vs. man-made are summarized above.<file_sep>/fish_growth.R #' Fish Growth Rate #' #' This function computes growth rate of fish in environment with various temperatures measured in degrees Celsius. The third order polynomial function is from Bjoornsson et al., 2007 #' @param a is derived from Table 2, Bjoornsson et al., 2007 #' @param b is derived from Table 2, Bjoornsson et al., 2007 #' @param c is derived from Table 2, Bjoornsson et al., 2007 #' @param d is derived from Table 2, Bjoornsson et al., 2007 #' @author <NAME> #' @return Fish growth rate G(%/day) #' @export library(tidyverse) fish_growth <- function(Temp){ G = a + b*Temp + c*Temp^2 + d*Temp^3 return(G) } <file_sep>/fisheries_summary.R #' Fisheries Summary #' #' Takes in a table of catches of different fish species at multiple locations #' Takes in another table of fish prices #' Gives the most frequetly caught species at each location, the total revenue at each location, and the overall revenue #' @param catches is a table of fish counts with rows of fish species and columns of locations #' @param prices is a table of fish prices #' @param plot is set to be FALSE by default #' @author <NAME> #' @export fisheries_summary <- function(catches, prices, plot=FALSE){ # Return most frequently caught fish in each location rownames = rownames(catches) revenue = vector(mode = "numeric", length = ncol(catches)) max_catch = rep("none", ncol(catches)) for (j in 1:ncol(catches)) { a = which.max(catches[,j]) max_catch[j] = rownames[a] revenue[j] = sum(prices[,2]*catches[,j]) } fish_summary <- data.frame(row.names =locs$name, Popular_species = max_catch, Location_Revenue = revenue, Total_Revenue = sum(revenue)) if (plot) { lb = sprintf("The total revenue is %d dollars", sum(revenue)) p = ggplot(data = as.data.frame(fish_summary), aes(locs$name, Location_Revenue, fill=locs$name))+geom_col()+ labs(x = "Locations", y="revenue in dollars")+annotate("text", x=2, y=1000000, label=lb, col="red") } else p=NULL return(fish_summary) }
62b568ba7cb1c02a4645899596a90c5bb6511bc8
[ "Markdown", "R", "RMarkdown" ]
6
RMarkdown
frankatacorner/S18ESM262FW
67da12e814646ec411ccc9a55333259aa745b84d
f3ed0f37f798c514bf609db70d9dde66c04a7961
refs/heads/master
<repo_name>amirtha4501/Angular-Framework-Intro<file_sep>/src/app/services/feedback.service.ts import { Observable } from 'rxjs'; import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { ProcessHTTPMsgService } from '../services/process-httpmsg.service'; import { Feedback } from '../shared/feedback'; import { Restangular } from 'ngx-restangular'; @Injectable({ providedIn: 'root' }) export class FeedbackService { constructor( private http: HttpClient, private processHTTPMsgService: ProcessHTTPMsgService, private restangular: Restangular ) { } submitFeedback(feedback: Feedback): Observable<Feedback> { return this.restangular.all('feedback').post(feedback); } }
6fdefed3af172e70d30a0eaa2835819b4ec0e050
[ "TypeScript" ]
1
TypeScript
amirtha4501/Angular-Framework-Intro
e9086a099f87b1f259c629b64b589a95a15412e2
326022fe6f63ce5777a14b343f43866635072fad
refs/heads/master
<file_sep>--- title: Installing Istio overview: This task shows you how to setup the Istio service mesh. order: 10 layout: docs type: markdown --- {% include home.html %} This page shows how to install and configure Istio in a Kubernetes cluster. ## Prerequisites * The following instructions assume you have access to a Kubernetes cluster. To install Kubernetes locally, try [minikube](https://kubernetes.io/docs/getting-started-guides/minikube/). * If you are using [Google Container Engine](https://cloud.google.com/container-engine), please make sure you are using static client certificates before fetching cluster credentials: ```bash gcloud config set container/use_client_certificate True ``` Find out your cluster name and zone, and fetch credentials: ```bash gcloud container clusters get-credentials <cluster-name> --zone <zone> --project <project-name> ``` * Install the Kubernetes client [kubectl](https://kubernetes.io/docs/tasks/tools/install-kubectl/), or upgrade to the latest version supported by your cluster. * If you previously installed Istio on this cluster, please uninstall first by following the [uninstalling]({{home}}/docs/tasks/installing-istio.html#uninstalling) steps at the end of this page. ## Installation steps For the {{ site.data.istio.version }} release, Istio must be installed in the same Kubernetes namespace as the applications. Instructions below will deploy Istio in the default namespace. They can be modified for deployment in a different namespace. 1. Go to the [Istio release](https://github.com/istio/istio/releases) page, to download the installation file corresponding to your OS. 2. Extract the installation file, and change directory to the location where the files were extracted. Following instructions are relative to this installation directory. The installation directory contains: * yaml installation files for Kubernetes * sample apps * the `istioctl` client binary, needed to inject Envoy as a sidecar proxy, and useful for creating routing rules and policies. * the istio.VERSION text file containing the Istio version. 3. Run the following command to determine if your cluster has [RBAC (Role-Based Access Control)](https://kubernetes.io/docs/admin/authorization/rbac/) enabled: ```bash kubectl api-versions | grep rbac ``` * If the command displays an error, or does not display anything, it means the cluster does not support RBAC, and you can proceed to step 4. * If the command displays 'beta' version, or both 'alpha' and 'beta', please apply istio-rbac-beta.yaml configuration: ```bash kubectl apply -f install/kubernetes/istio-rbac-beta.yaml ``` * If the command displays only 'alpha' version, please apply istio-rbac-alpha.yaml configuration: ```bash kubectl apply -f install/kubernetes/istio-rbac-alpha.yaml ``` 4. Install Istio's core components . There are two mutually exclusive options at this stage: * Install Istio without enabling [Istio Auth](https://istio.io/docs/concepts/network-and-auth/auth.html) feature: ```bash kubectl apply -f install/kubernetes/istio.yaml ``` This command will install Istio-Manager, Mixer, Ingress-Controller, Egress-Controller core components. * Install Istio and enable [Istio Auth](https://istio.io/docs/concepts/network-and-auth/auth.html) feature: ```bash kubectl apply -f install/kubernetes/istio-auth.yaml ``` This command will install Istio-Manager, Mixer, Ingress-Controller, and Egress-Controller, and the Istio CA (Certificate Authority). 5. *Optional:* To view metrics collected by Mixer, install [Prometheus](https://prometheus.io), [Grafana](http://staging.grafana.org) or ServiceGraph addons. *Note 1*: The Prometheus addon is *required* as a prerequisite for Grafana and the ServiceGraph addons. ```bash kubectl apply -f install/kubernetes/addons/prometheus.yaml kubectl apply -f install/kubernetes/addons/grafana.yaml kubectl apply -f install/kubernetes/addons/servicegraph.yaml ``` The Grafana addon provides a dashboard visualization of the metrics by Mixer to a Prometheus instance. The simplest way to access the Istio dashboard is to configure port-forwarding for the grafana service, as follows: ```bash kubectl port-forward $(kubectl get pod -l app=grafana -o jsonpath='{.items[0].metadata.name}') 3000:3000 ``` Then open a web browser to [http://localhost:3000/dashboard/db/istio-dashboard](http://localhost:3000/dashboard/db/istio-dashboard). The dashboard at that location should look something like the following: ![Grafana Istio Dashboard](./img/grafana_dashboard.png) *Note 2*: In some deployment environments, it will be possible to access the dashboard directly (without the `kubectl port-forward` command). This is because the default addon configuration requests an external IP address for the grafana service. When applicable, the external IP address for the grafana service can be retrieved via: ```bash kubectl get services grafana ``` With the EXTERNAL-IP returned from that command, the Istio dashboard can be reached at `http://<EXTERNAL-IP>:3000/dashboard/db/istio-dashboard`. ## Verifying the installation 1. Ensure the following Kubernetes services were deployed: "istio-manager", "istio-mixer", "istio-ingress", "istio-egress", and "istio-ca" (if Istio Auth is enabled). ```bash kubectl get svc ``` ```bash NAME CLUSTER-IP EXTERNAL-IP PORT(S) AGE istio-egress 10.7.241.106 <none> 80/TCP 39m istio-ingress 10.83.241.84 172.16.58.3 80:30583/TCP 39m istio-manager 10.83.251.26 <none> 8080/TCP 39m istio-mixer 10.83.242.1 <none> 9091/TCP,42422/TCP 39m ``` Note that if your cluster is running in an environment that does not support an external loadbalancer (e.g., minikube), the `EXTERNAL-IP` will say `<pending>` and you will need to access the application using the service NodePort instead. 2. Check the corresponding Kubernetes pods were deployed: "istio-manager-\*", "istio-mixer-\*", "istio-ingress-\*", "istio-egress-\*", and "istio-ca-\*" (if Istio Auth is enabled). ```bash kubectl get pods ``` ```bash NAME READY STATUS RESTARTS AGE istio-egress-597320923-0szj8 1/1 Running 0 49m istio-ingress-594763772-j7jbz 1/1 Running 0 49m istio-manager-373576132-p2t9k 1/1 Running 0 49m istio-mixer-1154414227-56q3z 1/1 Running 0 49m istio-ca-1726969296-9srv2 1/1 Running 0 49m ``` ## Deploy your application You can now deploy your own application, or one of the sample applications provided with the installation, for example [BookInfo]({{home}}/docs/samples/bookinfo.html). Note that the application should use HTTP/1.1 or HTTP/2.0 protocol for all its HTTP traffic; HTTP/1.0 is not supported. When deploying the application, you must use [istioctl kube-inject]({{home}}/docs/reference/commands/istioctl.html#istioctl-kube-inject) to automatically inject Envoy containers in your application pods: ```bash kubectl create -f <(istioctl kube-inject -f <your-app-spec>.yaml) ``` ## Uninstalling 1. Uninstall Istio core components: * If Istio was installed without Istio auth feature: ```bash kubectl delete -f install/kubernetes/istio.yaml ``` * If Istio was installed with auth feature enabled: ```bash kubectl delete -f install/kubernetes/istio-auth.yaml ``` 2. Uninstall RBAC Istio roles: * If beta version was installed: ```bash kubectl delete -f istio-rbac-beta.yaml ``` * If alpha version was installed: ```bash kubectl delete -f istio-rbac-alpha.yaml ``` ## What's next * See the sample [BookInfo]({{home}}/docs/samples/bookinfo.html) application. <file_sep>--- title: Overview overview: Provides a broad overview of what problems Istio is designed to solve. order: 15 layout: docs type: markdown --- This page introduces Istio: an open platform to connect, manage, and secure microservices. As monolithic applications transition towards a distributed microservice architecture they become more difficult to manage and understand. These architectures need basic necessities such as discovery, load balancing, failure recovery, metrics and monitoring, and more complex operational requirements such as A/B testing, canary releases, rate limiting, access control, and end-to-end authentication. The term service mesh is used to describe the network of microservices that make up applications and the interactions between them. As the service mesh grows in size and complexity, it becomes harder to understand and manage. Istio provides a complete solution to satisfy these diverse requirements of microservice applications, by providing developers and operators with behavioral insights and operational control over the service mesh as a whole. Istio does this by providing a number of key capabilities uniformly across the network of services: - **Traffic Management**. Control the flow of traffic and API calls between services, make calls more reliable and make the network more robust in the face of adverse conditions. - **Observability**. Gain understanding of the dependencies between services, the nature and flow of traffic between them and be able to quickly identify issues. - **Policy Enforcement**. Apply organizational policy to the interaction between services, ensure access policies are enforced and resources are fairly distributed among consumers. Policy changes are made by configuring the mesh, not by changing application code. - **Service Identity and Security**. Provide services in the mesh with a verifiable identity and provide the ability to protect service traffic as it flows over networks of varying degrees of trustability. In addition to these behaviors, Istio is designed for extensibility to meet diverse deployment needs: - **Platform Support**. Istio is designed to run in a variety of environments including ones that span Cloud, on-premise, Kubernetes, Mesos etc. We’re initially focused on Kubernetes but are working to support other environments soon. - **Integration and Customization**. The policy enforcement component can be extended and customized to integrate with existing solutions for ACLs, logging, monitoring, quotas, auditing and more. These capabilities greatly decrease the coupling between application code, the underlying platform and policy. This decreased coupling not only makes services easier to implement but also makes it simpler for operators to move application deployments between environments or to new policy schemes. Applications become inherently more portable as a result. Istio’s service mesh is logically split into a *data plane* and a *control plane*. The data plane is composed of a set of intelligent (HTTP, HTTP/2, gRPC, TCP or UDP) proxies deployed as sidecars that mediate and control all network communication between microservices. The control plane is responsible for managing and configuring proxies to route traffic, as well as enforce policies at runtime. ## What's next * Learn about Istio's [design goals](./goals.html). * Explore Istio's [high-level architecture](./architecture.html). <file_sep>--- title: Enabling Istio Auth overview: This task shows you how to setup Istio-Auth to provide mutual TLS authentication between services. order: 100 layout: docs type: markdown --- {% include home.html %} This task shows how to set up Istio Auth in a Kubernetes cluster. You'll learn how to: * Enable Istio Auth * Disable Istio Auth * Verify Istio Auth setup ## Before you begin This task assumes you have: * Read the [Istio Auth concepts]({{home}}/docs/concepts/network-and-auth/index.html). * Cloned https://github.com/istio/istio to your local machine (Step 1 in [the Istio installation guide](./installing-istio.html#installing-on-an-existing-cluster)). In real world systems, only a single Istio CA should be present in a Kubernetes cluster, which is always deployed in a dedicated namespace. The Istio CA issues certificates/keys to all pods in the Kubernetes cluster. This offers strong security and automatic trust between namespaces in the same cluster. However, this task also instructs how to deploy a namespace-scoped Istio CA, for easy setup and clean up during the experiments. ## Enabling Istio Auth ### Option 1: using per-namespace CA Per namespace CA is convenient for doing experiments. Because each Istio CA is scoped within a namespace, Istio CAs in different namespaces will not interfere with each other and they are easy to clean up through a single command. We have the YAML files *istio-auth-X.yaml* for deploying all Istio components including Istio CA into the namespace. Follow [the Istio installation guide](./installing-istio.html), and **choose "If you would like to enable Istio Auth" in step 3**. ### Option 2: (recommended) using per-cluster CA Only a single Istio CA is deployed for the Kubernetes cluster, in a dedicated namespace. Doing this offers the following benefits: * In the near future, the dedicated namespace will use [Kubernetes RBAC](https://kubernetes.io/docs/admin/authorization/rbac/) (beta in Kubernetes V1.6) to provide security boundary. This will offer strong security for Istio CA. * Services in the same Kubernetes cluster but different namespaces are able to talk to each other through Istio Auth without extra trust setup. #### Deplying CA The following command creates namespace *istio-system* and deploys CA into the namespace: ```bash kubectl apply -f ./kubernetes/istio-auth/istio-cluster-ca.yaml ``` #### <a name="istioconfig"></a>Enabling Istio Auth in Istio config The following command uncomments the line *authPolicy: MUTUAL_TLS* in the file *kubernetes/istio-X.yaml*, and backs up the original file as *istio-X.yaml.bak* (*X* corresponds to the Kubernetes server version, choose "15" or "16"). ```bash sed "s/# authPolicy: MUTUAL_TLS/authPolicy: MUTUAL_TLS/" ./kubernetes/istio-X.yaml > ./kubernetes/istio-auth-X.yaml ``` #### Deploying other services Follow [the general Istio installation guide](./installing-istio.html), and **choose "If you would like to enable Istio Auth" in step 3**. ## Disabling Istio Auth Disabling Istio Auth requires all Istio services and applications to be reconfigured and restarted without auth config. ### For per-namespace CA Istio Auth Run the following command to uninstall Istio, and redeploy Istio without auth: ```bash kubectl delete -f ./kubernetes/istio-auth-X.yaml kubectl apply -f ./kubernetes/istio-X.yaml ``` Also, redeploy your application by running: ```bash kubectl replace -f <(istioctl kube-inject -f <your-app-spec>.yaml) ``` ### For per-cluster CA Istio Auth #### Removing per-cluster Istio CA The following command removes Istio CA and its namespace *istio-system*. ```bash kubectl delete -f ./kubernetes/istio-auth/istio-cluster-ca.yaml ``` #### Redeploying Istio and applications Run the following command to uninstall Istio, and redeploy Istio without auth: ```bash kubectl delete -f ./kubernetes/istio-auth-X.yaml kubectl apply -f ./kubernetes/istio-X.yaml ``` Also, redeploy your application by running: ```bash kubectl replace -f <(istioctl kube-inject -f <your-app-spec>.yaml) ``` #### Recovering the original config files The following command will recover the original *istio-auth-X.yaml* file. ```bash git checkout ./kubernetes/istio-auth-X.yaml ``` ## Verifying Istio Auth setup The following instructions assume the applications are deployed in the "default" namespace. They can be modified for deployments in a separate namespace. Verify AuthPolicy setting in ConfigMap: ```bash kubectl get configmap istio -o yaml | grep authPolicy ``` ```bash # Istio Auth is enabled if the line "authPolicy: MUTUAL_TLS" is uncommented. ``` Check the certificate and key files are mounted onto the application pod *app-pod*: ```bash kubectl exec <app-pod> -c proxy -- ls /etc/certs ``` ```bash # Expected files: cert-chain.pem, key.pem and root-cert.pem. ``` When Istio Auth is enabled for a pod, *ssl_context* stanzas should be in the pod's proxy config. The following commands verifies the proxy config on *app-pod* has *ssl_context* configured: ```bash kubectl exec <app-pod> -c proxy -- ls /etc/envoy ``` ```bash # Get the config file named "envoy-revX.json". ``` ```bash kubectl exec <app-pod> -c proxy -- cat /etc/envoy/envoy-revX.json | grep ssl_context ``` ```bash # Expect ssl_context in the output. ``` <file_sep>(function ($) { function doSearch() { var url = '/search/?q=' + document.getElementsByName('q')[0].value; window.location.assign(url); } $(document).ready(function() { $('#searchbox_demo').on('submit', function(e) { e.preventDefault(); doSearch(); }); $('.btn-search').on('click', function(e) { e.preventDefault(); doSearch(); }); }); }(jQuery)); <file_sep>--- title: Community overview: Information on the various ways to participate and interact with the Istio community. layout: community type: markdown --- {% include home.html %} # Our community Istio is an open source project with an active community that supports its use and on-going development. We'd love for you to join us and get involved! There are quite a few ways to get in touch with the community, see below to learn the best approach for different cases. See [here](/bugs/) if you're trying to figure out how to report a bug in Istio. |![Stack Overflow]({{home}}/img/stackoverflow.png)|[Stack Overflow](https://stackoverflow.com/questions/tagged/istio) is for practical questions and curated answers on deploying, configuring, and using Istio. |![Mailing Lists]({{home}}/img/group.png)|Join the [istio-users](https://groups.google.com/forum/#!forum/istio-users) mailing list to get announcements, participate in discussions, and get help troubleshooting problems using Istio. The [istio-dev](https://groups.google.com/forum/#!forum/istio-dev) mailing lists is there for help developers hacking on Istio's code. |![Slack]({{home}}/img/slack.png)|[Slack](https://istio.slack.com) is where to go if you have something urgent you need help with. You can have interactive conversations with members of the community and development team. |![GitHub]({{home}}/img/github.png)|[GitHub](https://github.com/istio) is where development takes place on Istio code. <file_sep>--- title: BookInfo overview: This sample deploys a simple application composed of four separate microservices which will be used to demonstrate various features of the Istio service mesh. order: 10 layout: docs type: markdown --- {% include home.html %} This sample deploys a simple application composed of four separate microservices which will be used to demonstrate various features of the Istio service mesh. ## Before you begin * If you use GKE, please ensure your cluster has at least 4 standard GKE nodes. * Setup Istio by following the instructions in the [Installation guide]({{home}}/docs/tasks/installing-istio.html). ## Overview In this sample we will deploy a simple application that displays information about a book, similar to a single catalog entry of an online book store. Displayed on the page is a description of the book, book details (ISBN, number of pages, and so on), and a few book reviews. The BookInfo application is broken into four separate microservices: * *productpage*. The productpage microservice calls the *details* and *reviews* microservices to populate the page. * *details*. The details microservice contains book information. * *reviews*. The reviews microservice contains book reviews. It also calls the *ratings* microservice. * *ratings*. The ratings microservice contains book ranking information that accompanies a book review. There are 3 versions of the reviews microservice: * Version v1 doesn't call the ratings service. * Version v2 calls the ratings service, and displays each rating as 1 to 5 black stars. * Version v3 calls the ratings service, and displays each rating as 1 to 5 red stars. The end-to-end architecture of the application is shown below. ![BookInfo application without Istio](./img/bookinfo/noistio.svg) This application is polyglot, i.e., the microservices are written in different languages. ## Start the application 1. Source the Istio configuration file from the root of the installation directory: ```bash cd istio ``` ```bash source istio.VERSION ``` 1. Change your current working directory to the `bookinfo` application directory: ```bash cd demos/apps/bookinfo ``` 1. Bring up the application containers: ```bash kubectl apply -f <(istioctl kube-inject -f bookinfo.yaml) ``` The above command launches four microservices and creates the gateway ingress resource as illustrated in the diagram above. The reviews microservice has 3 versions: v1, v2, and v3. > Note that in a realistic deployment, new versions of a microservice are deployed over time instead of deploying all versions simultaneously. Notice that the `istioctl kube-inject` command is used to modify the `bookinfo.yaml` file before creating the deployments. This injects Envoy into Kubernetes resources as documented [here]({{home}}/docs/reference/commands/istioctl.html#istioctl-kube-inject). Consequently, all of the microservices are now packaged with an Envoy sidecar that manages incoming and outgoing calls for the service. The updated diagram looks like this: ![BookInfo application](./img/bookinfo/withistio.svg) 1. Confirm all services and pods are correctly defined and running: ```bash kubectl get services ``` which produces the following output: ```bash NAME CLUSTER-IP EXTERNAL-IP PORT(S) AGE details 10.0.0.31 <none> 9080/TCP 6m istio-ingress 10.0.0.122 <pending> 80:31565/TCP 8m istio-manager 10.0.0.189 <none> 8080/TCP 8m istio-mixer 10.0.0.132 <none> 9091/TCP,42422/TCP 8m kubernetes 10.0.0.1 <none> 443/TCP 14d productpage 10.0.0.120 <none> 9080/TCP 6m ratings 10.0.0.15 <none> 9080/TCP 6m reviews 10.0.0.170 <none> 9080/TCP 6m ``` and ```bash kubectl get pods ``` which produces ```bash NAME READY STATUS RESTARTS AGE details-v1-1520924117-48z17 2/2 Running 0 6m istio-ingress-3181829929-xrrk5 1/1 Running 0 8m istio-manager-175173354-d6jm7 2/2 Running 0 8m istio-mixer-3883863574-jt09j 2/2 Running 0 8m productpage-v1-560495357-jk1lz 2/2 Running 0 6m ratings-v1-734492171-rnr5l 2/2 Running 0 6m reviews-v1-874083890-f0qf0 2/2 Running 0 6m reviews-v2-1343845940-b34q5 2/2 Running 0 6m reviews-v3-1813607990-8ch52 2/2 Running 0 6m ``` 1. Determine the gateway ingress URL: ```bash kubectl get ingress -o wide ``` ```bash NAME HOSTS ADDRESS PORTS AGE gateway * 192.168.3.11 80 1d ``` ```bash export GATEWAY_URL=192.168.3.11:80 ``` If your Kubernetes cluster is running in an environment that supports external load balancers, like for instance GKE, and the Istio ingress service was able to obtain an External IP, the ingress' resource IP Address will be equal to the ingress' service External IP. You can directly use that IP Address in your browser to access the http://$GATEWAY_URL/productpage. If the service did not obtain an External IP, the ingress' IP Address will display a list of NodePort addresses. You can use any of these addresses to access the ingress, but if the cluster has a firewall, you will also need to create a firewall rule to allow TCP traffic to the NodePort. For instance, in GKE, create a firewall rule with these commands: ```bash kubectl get svc istio-ingress -o jsonpath='{.spec.ports[0].nodePort}' ``` ```bash 31201 ``` ```bash gcloud compute firewall-rules create allow-book --allow tcp:31201 ``` 1. Confirm that the BookInfo application is running by opening in your browser http://$GATEWAY_URL/productpage , or with the following `curl` command: ```bash curl -o /dev/null -s -w "%{http_code}\n" http://$GATEWAY_URL/productpage ``` ```bash 200 ``` 1. If you enabled auth and want to play with it, you can use curl from one envoy to send request to other services. For example, you want to ssh into the envoy container of details service, and send request to other services by curl. There are several steps: Step 1: get the details pod name ```bash kubectl get pods -l app=details ``` ```bash NAME READY STATUS RESTARTS AGE details-v1-4184313719-5mxjc 2/2 Running 0 23h ``` Make sure the pod is "Running". Step 2: ssh into the envoy container ```bash kubectl exec -it details-v1-4184313719-5mxjc -c proxy /bin/bash ``` Step 3: make sure the key/cert is in /etc/certs/ directory ```bash ls /etc/certs/ ``` ```bash cert-chain.pem key.pem ``` Step 4: send requests to another service, for example, productpage. ```bash curl https://productpage:9080 -v --key /etc/certs/key.pem --cert /etc/certs/cert-chain.pem -k ``` ```bash ... < HTTP/1.1 200 OK < content-type: text/html; charset=utf-8 < content-length: 1867 < server: envoy < date: Thu, 11 May 2017 18:59:42 GMT < x-envoy-upstream-service-time: 2 ... ``` The service name and port are defined [here](https://github.com/istio/istio/blob/master/samples/apps/bookinfo/bookinfo.yaml). Note that '-k' option above is to disable service cert verification. Otherwise the curl command will not work. The reason is that in Istio cert, there is no service name, which is the information curl needs to verify service identity. To verify service identity, Istio uses service account, please refer to [here](https://istio.io/docs/concepts/network-and-auth/auth.html) for more information. 1. If you have installed the Istio addons, in particular the servicegraph addon, from the [Installation guide]({{home}}/docs/tasks/installing-istio.html), a generated servicegraph of the cluster is available. Get the external IP Address (and port) of the servicegraph service: ```bash kubectl get svc servicegraph ``` ```bash NAME CLUSTER-IP EXTERNAL-IP PORT(S) AGE servicegraph 10.75.240.195 172.16.31.10 8088:32556/TCP 23m ``` The servicegraph service provides both a textual (JSON) representation (via `/graph`) and a graphical visualization (via `/dotviz`) of the underlying servicegraph. To view the graphical visualization, visit `http://EXTERNAL-IP:PORT/dotviz` (here: http://172.16.31.10:8088/dotviz). After the single `curl` request from an earlier step, the resulting image will look something like: ![BookInfo service graph](./img/bookinfo/servicegraph.png) The servicegraph should show very low (or zero) QPS values, as only a single request has been sent. The service uses a default time window of 5 minutes for calculating moving QPS averages. Send a consistent flow of traffic through the example application and refresh the servicegraph to view updated QPS values that match the generated level of traffic. ## What's next Now that you have the BookInfo sample up and running, you can use Istio to control traffic routing, inject faults, rate limit services, etc.. * To get started, check out the [request routing task]({{home}}/docs/tasks/request-routing.html) * When you're finished experimenting with the BookInfo sample, you can uninstall it as follows: 1. Delete the routing rules and terminate the application pods ```bash ./cleanup.sh ``` 1. Confirm shutdown ```bash istioctl get route-rules #-- there should be no more routing rules kubectl get pods #-- the BookInfo pods should be deleted ```
71e76c65d719c3753e8a1dfb96988c5fe1ffe411
[ "Markdown", "JavaScript" ]
6
Markdown
andraxylia/andraxylia.github.io
eb2fcbec76cb1cf239e54964900e9824d89e3ada
23246f78a4f0ad4e9e5e4a5691d09e6c4c42c4f5
refs/heads/master
<repo_name>EduardoMendonca2001/CRUD<file_sep>/js/index.js $(document).ready(function () { var $campoCpf = $("#cpf1"); $campoCpf.mask('000.000.000-00', {reverse: true}); }); function validaCampos() { var cpf = document.getElementById("cpf1").value; var senha = document.getElementById("senha1").value; var cpf -> $campoCpf.unmask(); if (cpf == "" || senha == "") { alert ("Preencha os campos em branco!"); return false; } } <file_sep>/paginaAdm/registro.php <?php require_once("conexaoBanco.php"); $nome = $_POST['nome']; $cpf = $_POST['cpf']; $data = $_POST['data']; $tel = $_POST['telefone']; $comando="INSERT INTO clientes (cpf, nome, dataNasc, telefone) VALUES ('".$cpf."', '".$nome."', '".$data."', '".$tel."')"; $resultado = mysqli_query($conexao, $comando); if ($resultado == true) { header("Location:registroForm.php?retorno=1"); }else{ header("Location:registroForm.php?retorno=0"); } ?> <file_sep>/bd/bd_clinica.sql -- MySQL Script generated by MySQL Workbench -- Thu Aug 29 15:49:39 2019 -- Model: New Model Version: 1.0 -- MySQL Workbench Forward Engineering SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0; SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0; SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION'; -- ----------------------------------------------------- -- Schema bd_clinicaEstetica -- ----------------------------------------------------- -- O banco de dados é utilizado para guardar os registros e dados do login de uma clinica de estética -- -- Nome:<NAME> -- Data:15/08/2019 -- ----------------------------------------------------- -- Schema bd_clinicaEstetica -- -- O banco de dados é utilizado para guardar os registros e dados do login de uma clinica de estética -- -- Nome:<NAME> -- Data:15/08/2019 -- ----------------------------------------------------- CREATE SCHEMA IF NOT EXISTS `bd_clinicaEstetica` DEFAULT CHARACTER SET utf8 COLLATE utf8_bin ; USE `bd_clinicaEstetica` ; -- ----------------------------------------------------- -- Table `bd_clinicaEstetica`.`clientes` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `bd_clinicaEstetica`.`clientes` ( `cpf` VARCHAR(15) NOT NULL COMMENT 'CPF do cliente como chave primaria.', `nome` VARCHAR(45) NOT NULL COMMENT 'Vai pegar o nome completo do Cliente.', `dataNasc` DATE NOT NULL COMMENT 'Pegar a data de nascimento do cliente.', `telefone` VARCHAR(15) NOT NULL COMMENT 'Pegar o telefone do cliente.', PRIMARY KEY (`cpf`)) ENGINE = InnoDB COMMENT = 'Vai pegar todos os registros do clientes para ser armazenados.'; -- ----------------------------------------------------- -- Table `bd_clinicaEstetica`.`usuarios` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `bd_clinicaEstetica`.`usuarios` ( `cpf` VARCHAR(15) NOT NULL COMMENT 'Vai pegar o CPF do proprietário para fazer o login.', `senha` VARCHAR(32) NOT NULL COMMENT 'Vai pegar a senha do proprietário para o login.', PRIMARY KEY (`cpf`)) ENGINE = InnoDB COMMENT = 'Vai pegar os dados dos proprietarios para poder fazer o login.'; SET SQL_MODE=@OLD_SQL_MODE; SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS; SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS; <file_sep>/js/edita.js $(document).ready(function () { var $campoTel = $("#telefone1"); $campoTel.mask('(47)0000-0000', {reverse: true}); }); <file_sep>/paginaAdm/excluiCliente.php <?php require_once("conexaoBanco.php"); $cpf = $_POST['cpf']; $comando="DELETE FROM clientes WHERE cpf='".$cpf."'"; $resultado = mysqli_query($conexao,$comando); if ($resultado==true){ header("Location: registroForm.php?retorno=1"); }else{ header("Location: registroForm.php?retorno=0"); } ?> <file_sep>/paginaAdm/editaClienteForm.php <!DOCTYPE html> <html lang="pt-br"> <head> <title>Edição de clientes</title> <meta charset="UTF-8"> <link rel="stylesheet" href="../css/edicaoClientes.css"> <script src="../js/jquery-3.4.1.min.js"></script> <script src="../js/jquery.mask.min.js"></script> <script src="../js/edita.js"></script> </head> <body> <?php include("menu.php"); ?> <br><br><br> <h1>Edição de clientes</h1> <div> <?php if(isset($_GET['retorno']) && $_GET['retorno']==1){ include("../alertas/sucesso.html"); }else if(isset($_GET['retorno']) && $_GET['retorno']==2){ include("../alertas/erro.html"); } ?> </div> <fieldset> <legend>Dados do cliente</legend> <?php require_once("conexaoBanco.php"); $cpf = $_POST['cpf']; $comando="SELECT * FROM clientes WHERE cpf='".$cpf."'"; $resultado=mysqli_query($conexao,$comando); $clientes=mysqli_fetch_assoc($resultado); ?> <form action="editaCliente.php" method="POST"> <input class="inputsForm" type="hidden" name="cpf" value="<?=$clientes['cpf'];?>"> <label>Nome do cliente</label> <input class="inputsForm" type="text" name="nome" placeholder="ex.:Eduardo" value="<?=$clientes['nome'];?>"><br> <label>Data de Nascimento</label> <input class="inputsForm" type="date" name="dataNasc" placeholder="ex.:08/09/10" value="<?=$clientes['dataNasc'];?>"><br> <label>Telefone</label> <input class="inputsForm" type="text" name="telefone" id="telefone1" placeholder="ex.:(47)99999-9999" value="<?=$clientes['telefone'];?>"><br> <button class="botoesAcao" type="submit">Enviar</button> </form> </fieldset> </body> </html> <file_sep>/paginaAdm/conexaoBanco.php <?php $conexao = mysqli_connect("localhost","root","root","bd_clinicaestetica"); $conexao -> set_charset("utf-8"); ?> <file_sep>/paginaAdm/registroForm.php <?php session_start(); if(isset($_SESSION['cpfLogado'])==true){ ?> <!DOCTYPE html> <html lang="pt-br"> <head> <title>Registro de Clientes</title> <meta charset="UTF-8"> <link rel="stylesheet" href="../css/registro.css"/> <script src="../js/jquery-3.4.1.min.js"></script> <script src="../js/jquery.mask.min.js"></script> <script src="../js/registro.js"></script> </head> <body> <?php include("menu.php"); ?> <h1 id="h1Registro">Registro de Clientes</h1> <div id="divRegistro"> <form action="registro.php" method="POST" name="formulario" onsubmit="return validarCampos()"> <fieldset id="registroCliente"> <legend id="legRegistro">Dados pessoais</legend> <label class="registro">*Nome completo</label><br> <input type="text" maxlength="50" name="nome" id="nome1" placeholder="Ex: <NAME>"> <br><br> <label class="registro">*CPF</label><br> <input type="text" maxlength="11" name="cpf" id="cpf1" placeholder="Ex: 999.999.999-99"> <br><br> <label class="registro">Data de nascimento</label><br> <input type="date" name="data" id="data1"> <br><br> <label class="registro">Telefone</label><br> <input type="text" maxlength="9" name="telefone" id="telefone1" placeholder="Insira seu telefone"> <br><br> <button type="reset" name="Limpar" id="limpar">Limpar</button> <button type="submit" name="Logar" id="login">Enviar</button> </fieldset> </form> </div> <div id="divConsulta"> <fieldset id="consultaCliente"> <legend id="legConsulta">Consulta de cliente</legend> <form action="#" method="GET" id="formConsulta" onsubmit="return validarDados()"> <label for="consultaNomeCliente" id="labelConsultaNome">Nome:</label> <input type="text" name="consultaNomeCliente" id="consultaNomeCliente"> <button type="submit">Buscar</button> </form> <table> <tr> <th>Nome completo</th> <th>CPF</th> <th>Data de nascimento</th> <th>Telefone</th> <th>Ações</th> </tr> <?php require_once("conexaoBanco.php"); if(isset($_GET['consultaNomeCliente'])==false){ $comando="SELECT * FROM clientes"; } else if(isset($_GET['consultaNomeCliente'])==true && $_GET['consultaNomeCliente']==""){ $comando="SELECT * FROM clientes"; } else if(isset($_GET['consultaNomeCliente'])==true && $_GET['consultaNomeCliente']!=""){ $busca = $_GET['consultaNomeCliente']; $comando = "SELECT * FROM clientes WHERE nome LIKE '".$busca."%'"; } $resultado = mysqli_query($conexao,$comando); $linhas=mysqli_num_rows($resultado); if($linhas==0){ ?> <tr> <td colspan="5">Nenhum cliente encontrado!</td> </tr> <?php }else{ $retornaClientes = array(); while($cadaLinha = mysqli_fetch_assoc($resultado)){ array_push($retornaClientes,$cadaLinha); } foreach ($retornaClientes as $cadaCliente) { ?> <tr> <td> <?php echo $cadaCliente['nome'];?> </td> <td> <?php echo $cadaCliente['cpf'];?></td> <td> <?php echo $cadaCliente['dataNasc'];?></td> <td> <?php echo $cadaCliente['telefone'];?></td> <td> <form action="editaClienteForm.php" method="POST"> <input type="hidden" name="cpf" value="<?=$cadaCliente['cpf'];?>"> <button type="submit"><img src="../img/pencil.png" alt="Botão editar"></button> </form> <form action="excluiCliente.php" method="POST"> <input type="hidden" name="cpf" value="<?=$cadaCliente['cpf'];?>"> <button type="submit"><img src="../img/trash.png" alt="Botão lixeiro"></button> </form> </td> </tr> <?php } } ?> </table> <div> <?php if(isset($_GET['retorno'])==true){ if($_GET['retorno']==1){ $msg="Sucesso ao realizar operação!"; include("../alertas/sucesso.php"); }else if ($_GET['retorno']==0){ $msg="Erro ao realizar operação!"; include("../alertas/erro.php"); } } ?> </div> </fieldset> </div> </body> </html> <?php }else{ header("Location: ../index.php"); } ?> <file_sep>/js/registro.js $(document).ready(function () { var $campoCpf = $("#cpf1"); $campoCpf.mask('000.000.000-00', {reverse: true}); }); $(document).ready(function () { var $campoTel = $("#telefone1"); $campoTel.mask('(47)00000-0000', {reverse: true}); }); function validarCampos(){ var nome = document.getElementById("nomeC").value; var cpf = document.getElementById("cpf1").value; var data = document.getElementById("dataN").value; var tel = document.getElementById("telefone1").value; if (nome=="" || (cpf=="" && cpf.length!=11) || data=="" || (tel =="" && tel.length!=14)){ alert("Preencha os campos corretamente!"); return false; }else{ return true; } } function validarDados(){ var nome1 = document.getElementById("consultaNomeCliente").value; if (nome1==""){ alert("Consulte um nome valido!"); return false; }else{ return true; } } <file_sep>/paginaAdm/efetuaLogin.php <?php require_once("conexaoBanco.php"); $cpf = $_POST['cpf']; $senha = $_POST['senha']; $senha=md5($senha); $comando="SELECT * FROM usuarios WHERE cpf='".$cpf."' AND senha='".$senha."'"; $resultado=mysqli_query($conexao,$comando); $usuario=mysqli_fetch_assoc($resultado); $linhas=mysqli_num_rows($resultado); if($linhas==0){ header("Location: ../index.php"); }else{ session_start(); $_SESSION['cpfLogado']=$usuario['cpf']; if(isset($_SESSION['cpfLogado'])==true){ header("Location: paginaAdminis.php"); }else{ header("Location: ../index.php"); } } ?> <file_sep>/paginaAdm/editaCliente.php <?php require_once("conexaoBanco.php"); $cpf = $_POST['cpf']; $nome = $_POST['nome']; $data = $_POST['dataNasc']; $tel = $_POST['telefone']; $comando="UPDATE clientes SET nome='".$nome."' , dataNasc='".$data."' , telefone='".$tel."' WHERE cpf='".$cpf."'"; $resultado=mysqli_query($conexao,$comando); if ($resultado==true) { header("Location: registroForm.php?retorno=1"); }else{ header("Location: registrForm.php?retorno=0"); } ?>
9897198ccba64bcde8eee12c9726339b69dc34f0
[ "JavaScript", "SQL", "PHP" ]
11
JavaScript
EduardoMendonca2001/CRUD
82d6b66bae78df8b92477ebe897c218c6e21fd1c
14bab982121399bdf114567e35750384cd1b78c2
refs/heads/master
<repo_name>Sumeet-Jain/mazeGame<file_sep>/Maze.js //Key codes for arrow keys. function Position(x,y){ this.x = x; this.y = y; this.getCoords = function(){ return "" + this.x + "/" + this.y; }; this.equals = function(other){ return (other.x == this.x && other.y == this.y); }; } function Layout(sqSize, xLength, yLength){ this.sqSize = sqSize; this.xLength = xLength; this.yLength = yLength; this.color = "#45c5f7"; this.color2 = "#e05f26"; //orange this.color3 = "#2a1f47"; //purple this.heroPosition = new Position(0,0); this.portalPosition; this.hero = new Piece(this.sqSize, this.heroPosition, "hero"); this.sqaures; this.level = 1; this.score = 0; this.time = 0; this.canAccessTime = true; this.squaresUsed = 1; this.createBoard(); } //Change into classes that inherit shit function Piece(size, pos, name){ this.elem = document.createElement("img"); this.elem.src = "images/" + name + ".png" ; this.elem.setAttribute("id", name); this.elem.setAttribute("height", size); this.elem.setAttribute("width", size ); this.name = name; this.pos = pos; } function Square(sqSize, color, x, y){ this.x = x; this.y = y; this.canWalk = false; this.id = "" + x + "/" + y; this.sqSize = sqSize; this.has; var div = "<div id=" + this.id + " style = \""; div += "background-color: " + color +";"; div += "position : absolute; left: " + x * this.sqSize+ "; "; div += "top : " + y * this.sqSize + "; "; div += "width : " + this.sqSize + "; "; div += "height : " + this.sqSize + " \">"; //End of style tag. div += "</div>"; this.divTag = div; this.bombs = 0; } function Square_changeColor(color){ document.getElementById(this.id).background.color = color; } Square.prototype.changeColor = Square_changeColor; function Layout_createBoard(){ this.hero = new Piece(this.sqSize, this.heroPosition, "hero"); this.squares = new Array(this.yLength); for(var i = 0; i < this.squares.length; i++){ this.squares[i] = new Array(this.xLength); } if(document.getElementById("womp") == null){ document.write("<audio id=\"womp\" src=\"audio/womp.mp3\" preload = \"auto\" > </audio>"); } document.write((document.getElementById("board") == null) ? "<div id = \"board\">" : ""); for(var x = 0; x < this.xLength; x++){ for(var y = 0; y < this.yLength; y++){ var sq = new Square(this.sqSize, this.color2, x, y); this.squares[y][x] = sq; if(document.getElementById("board") == null){ document.getElementById("board").appendChild(sq.divTag); } else { document.write(sq.divTag); } } } document.write(this.createText()); document.write((document.getElementById("board") == null) ? "" : ""); this.makeRandomPath(); document.getElementById(this.heroPosition.getCoords()).appendChild(this.hero.elem); this.squares[this.heroPosition.y][this.heroPosition.x].has = "hero"; //this.putBombs(); } function Layout_createText(){ var leftPos = (this.xLength + 1) * this.sqSize; return ("<p id = \"score\" style = \"position: absolute; left: " + leftPos + ";font-size: 14pt; font-family: Arial, Helvetica, sans-serif;\"> Level: " + this.level + "<br>Score: " + this.score + "<br><br>Time: " + this.time + "</p>"); } function Layout_deleteBoard(){ var board = document.getElementById("board"); while(board.hasChildNodes()){ board.removeChild(board.firstChild); } this.squaresUsed = 1; } Layout.prototype.createBoard = Layout_createBoard; Layout.prototype.deleteBoard = Layout_deleteBoard; Layout.prototype.createText = Layout_createText; function Layout_validPos(pos){ return (pos.x >= 0 && pos.x < this.xLength && pos.y >= 0 && pos.y < this.yLength); } Layout.prototype.validPos = Layout_validPos; function Layout_moveGuy(x, y){ var xPos = this.heroPosition.x + x, yPos = this.heroPosition.y + y, newPos = new Position(xPos, yPos); if(this.validPos(newPos) && (this.squares[yPos][xPos].canWalk)){ document.getElementById(this.heroPosition.getCoords()).removeChild(this.hero.elem); this.heroPosition = newPos; if(this.squares[this.heroPosition.y][this.heroPosition.x].has == "portal"){ this.nextLevel(); } else { this.squares[this.heroPosition.y][this.heroPosition.x].has == "hero"; document.getElementById(this.heroPosition.getCoords()).innerHTML = ""; document.getElementById(this.heroPosition.getCoords()).appendChild(this.hero.elem); } } else { document.getElementById("womp").play(); alert("EXPLOSION! .\nTry climbing again."); this.restart(); } } function Layout_restart(){ this.level = 1; this.score = 0; if(this.canAccessTime){ //Is this necessary? this.canAccessTime = false; this.time = 0; this.canAccessTime = true; } this.heroPosition = new Position(0,0); this.deleteBoard(); this.createBoard(); } function Layout_nextLevel(){ this.level++; this.score += (10000 / this.time >> 0) + 500; if(this.canAccessTime){ this.canAccessTime = false; this.time = 0; this.canAccessTime = true; } this.heroPosition = new Position(0, this.portalPosition.y); this.deleteBoard(); this.createBoard(); } Layout.prototype.nextLevel = Layout_nextLevel; Layout.prototype.restart = Layout_restart; function Layout_keyPressDoer(obj){ var LEFT = '37', UP = '38', RIGHT = '39', DOWN = '40'; function wrap(e){ var key = e.keyCode; if(key == LEFT || key == 'A'.charCodeAt(0)){ obj.moveGuy(-1,0); } else if (key == RIGHT || key == 'D'.charCodeAt(0)) { obj.moveGuy(1,0); } else if (key == UP || key == 'W'.charCodeAt(0)) { obj.moveGuy(0,-1); } else if (key == DOWN || key == 'S'.charCodeAt(0)) { obj.moveGuy(0,1); } } return wrap; } Layout.prototype.moveGuy = Layout_moveGuy; Layout.prototype.keyPressDoer = Layout_keyPressDoer; function Layout_makeRandomPath(){ var currPos = new Position(this.heroPosition.x, this.heroPosition.y); document.getElementById(currPos.getCoords()).style.background = this.color; var U = 0, D = 1, R = 2, L = 3, previous = 5, counter = 0, random; do{ random = Math.floor(Math.random() * 3); var newPos = new Position(currPos.x, currPos.y); if(previous == random){ continue; } previous = random; if (random == D){ newPos.y = currPos.y + 1; } else if (random == R){ newPos.x = currPos.x + 1; } else if (random == L){ newPos = currPos.x - 1; } else if (random == U){ newPos.y = currPos.y - 1; } if(!currPos.equals(newPos) && this.validPos(newPos) && !this.squares[newPos.y][newPos.x].canWalk && !newPos.equals(this.heroPosition)){ var node = document.getElementById(newPos.getCoords()); node.style.background = this.color; this.squares[newPos.y][newPos.x].canWalk = true; counter = 0; currPos = newPos; this.squaresUsed++; } else { counter++; } }while(currPos.x < this.xLength - 1 && counter < 10); var portal = new Piece(this.sqSize, currPos, "portal"); document.getElementById(currPos.getCoords()).appendChild(portal.elem); this.squares[currPos.y][currPos.x].has = "portal"; this.portalPosition = currPos; } Layout.prototype.makeRandomPath = Layout_makeRandomPath; function Layout_putBombs(){ var numOfBombs = this.level * 3 + 40. x, y; if(numOfBombs >= (this.xLength * this.yLength) - this.squaresUsed){ //iterate through every square. If i cant walk on it, the increment bombs //I should change this. Game becomes stupidly easy. for(x = 0; x < this.squares[0].length; x++){ for(y = 0; y < this.squares.length; y++){ if(!this.squares[y][x].canWalk){ this.updateAdjBombs(this.squares[y][x]); } } } } else { var counter = 0; while(numOfBombs > 0 && counter < 20){ x = (Math.random() * this.xLength) >> 0; y = (Math.random() * this.yLength) >> 0; if(this.squares[y][x].canWalk || this.squares[y][x].has == "bomb"){ counter++; } else { counter = 0; this.squares[y][x].has = "bomb"; this.updateAdjBombs(this.squares[y][x]); numOfBombs--; } } } for(x = 0; x < this.squares[0].length; x++){ for(y = 0; y < this.squares.length; y++){ var text = "<p class = \"number\">"; text += this.squares[y][x].bombs + "</p>"; if(document.getElementById(this.squares[y][x].id).innerHTML === ""){ document.getElementById(this.squares[y][x].id).innerHTML = text; } } } } Layout.prototype.putBombs = Layout_putBombs; function Layout_updateAdjBombs(square){ var x, y; for(x = square.x - 1; x <= square.x + 1 ; x++){ if(x >= 0 && x < this.squares[0].length){ for(y = square.y - 1; y <= square.y + 1; y++){ if(y >= 0 && y < this.squares.length){ this.squares[y][x].bombs++; } } } } this.squares[square.y][square.x].bombs--; this.squares[square.y][square.x].has = "bomb"; } Layout.prototype.updateAdjBombs = Layout_updateAdjBombs; function load(){ var layout = new Layout(50,20,10); //Time increaser setInterval(function(){ if(layout.canAccessTime){ layout.canAccessTime = false; layout.time++; document.getElementById("score").parentNode.removeChild(document.getElementById("score")); document.write(layout.createText()); layout.canAccessTime = true; } }, 1000); document.onkeydown = layout.keyPressDoer(layout); }
6ce3aa32704779110aff053596fa4f46df2aaa9c
[ "JavaScript" ]
1
JavaScript
Sumeet-Jain/mazeGame
ef19817a001b03f4928fa27e8d54c5d741570a2f
5394a2174cc41b2424cbd015c2c2bea9ec609f29
refs/heads/master
<repo_name>yongbiaoshi/zookeeper<file_sep>/src/main/java/com/tsingda/zk/demo/ZKWatcher.java package com.tsingda.zk.demo; import java.util.concurrent.CountDownLatch; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.Watcher.Event.KeeperState; public class ZKWatcher implements Watcher { private static CountDownLatch connectedSemaphore = new CountDownLatch(1); public void process(WatchedEvent event) { System.out.println("receive watched event:" + event); if (KeeperState.SyncConnected == event.getState()) { connectedSemaphore.countDown(); } } public void await() throws InterruptedException{ connectedSemaphore.await(); } }
524d80d951814a73ef70cc42072f6ab2f928bde6
[ "Java" ]
1
Java
yongbiaoshi/zookeeper
6590575625f12a2d5104c9a3c6364cf0d7d84489
36fec4eccfc1305dc4e3760204cbe51d1104ab9d
refs/heads/master
<file_sep># person-app Example application for Spring and JSF Primefaces (2017) <file_sep>package com.szabodev.person.service.mapper; import com.szabodev.person.model.Person; import com.szabodev.person.service.dto.PersonDTO; import org.mapstruct.Mapper; import org.mapstruct.factory.Mappers; import java.util.List; @Mapper public interface PersonMapper { PersonMapper INSTANCE = Mappers.getMapper(PersonMapper.class); PersonDTO toDTO(Person person); Person toEntity(PersonDTO personDTO); List<PersonDTO> toDTOs(List<Person> persons); } <file_sep>package com.szabodev.person.service; import com.szabodev.person.dao.PersonDAO; import com.szabodev.person.model.Person; import com.szabodev.person.service.dto.PersonDTO; import com.szabodev.person.service.mapper.PersonMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class PersonServiceImpl implements PersonService { private PersonDAO personDAO; @Autowired public void setPersonDAO(PersonDAO personDAO) { this.personDAO = personDAO; } @SuppressWarnings("unchecked") @Override public void addPerson(PersonDTO p) { Person person = PersonMapper.INSTANCE.toEntity(p); this.personDAO.saveOrUpdate(person); } @SuppressWarnings("unchecked") @Override public List<PersonDTO> listPersons() { List<Person> all = this.personDAO.getAll(); return PersonMapper.INSTANCE.toDTOs(all); } @SuppressWarnings("unchecked") @Override public void updatePerson(PersonDTO p) { Person person = PersonMapper.INSTANCE.toEntity(p); this.personDAO.saveOrUpdate(person); } @Override public void deletePerson(PersonDTO p) { Person person = PersonMapper.INSTANCE.toEntity(p); this.personDAO.delete(person); } } <file_sep>Environment setup Copy spring-example-logback.xml -> C:/work/config/spring-example Copy spring-example.properties -> C:/work/config/spring-example Configure Tomcat: Configure -> Java -> Java Options: -Dspring-example.properties=C:/work/config/spring-example/spring-example.properties <file_sep>package com.szabodev.person.model; import javax.persistence.*; import java.io.Serializable; import java.util.Date; @Entity @Table(name="PERSON") public class Person implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name="id") private Integer id; private String name; private String city; @Temporal(TemporalType.DATE) private Date dateOfBirth; private String gender; public Date getDateOfBirth() { return dateOfBirth; } public void setDateOfBirth(Date dateOfBirth) { this.dateOfBirth = dateOfBirth; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } @Override public String toString() { return "Person{" + "id=" + id + ", name='" + name + '\'' + ", city='" + city + '\'' + ", dateOfBirth=" + dateOfBirth + ", gender='" + gender + '\'' + '}'; } }<file_sep>package com.szabodev.person.dao; import java.util.List; interface AbstractDAO<T> { Integer save(final T o); void delete(final Object object); T get(final Integer id); T merge(T o); void saveOrUpdate(T o); List<T> getAll(); } <file_sep>package com.szabodev.person.service.soap; import com.szabodev.person.business.PersonAppConfiguration; import com.szabodev.person.service.PersonService; import com.szabodev.person.service.dto.PersonDTO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.jws.WebMethod; import javax.jws.WebService; import java.util.List; @SuppressWarnings("unused") @Service @WebService(serviceName = "testWebService") public class TestWebService { private PersonAppConfiguration personAppConfiguration; private PersonService personService; @WebMethod(exclude = true) @Autowired public void setPersonService(PersonService personService) { this.personService = personService; } @WebMethod(exclude = true) @Autowired public void setPersonAppConfiguration(PersonAppConfiguration personAppConfiguration) { this.personAppConfiguration = personAppConfiguration; } @WebMethod public void loadConfiguration() { personAppConfiguration.loadProperties(); } @WebMethod public String getProperty(String propertyName) { return personAppConfiguration.getProperty(propertyName); } @WebMethod public void addPerson(PersonDTO p) { personService.addPerson(p); } @WebMethod public List<PersonDTO> listPersons() { return personService.listPersons(); } @WebMethod public void updatePerson(PersonDTO p) { personService.updatePerson(p); } @WebMethod public void deletePerson(PersonDTO p) { personService.deletePerson(p); } }<file_sep>package com.szabodev.person.web; import com.szabodev.person.service.PersonService; import com.szabodev.person.service.dto.PersonDTO; import org.primefaces.event.RowEditEvent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import javax.faces.application.FacesMessage; import javax.faces.context.FacesContext; import java.util.List; @Component @Scope(value = "request") public class PersonController { private static final Logger logger = LoggerFactory.getLogger(PersonController.class); private PersonService personService; @Autowired public void setPersonService(PersonService personService) { this.personService = personService; } private PersonDTO person; private List<PersonDTO> persons; @PostConstruct public void init() { persons = personService.listPersons(); person = new PersonDTO(); } public PersonDTO getPerson() { return person; } public void setPerson(PersonDTO person) { this.person = person; } public List<PersonDTO> getPersons() { return persons; } public void setPersons(List<PersonDTO> persons) { this.persons = persons; } public void addPerson() { personService.addPerson(person); init(); } public void onRowEdit(RowEditEvent event) { logger.debug("onRowEdit called"); PersonDTO editedPerson = (PersonDTO) event.getObject(); personService.updatePerson(editedPerson); persons = personService.listPersons(); FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "", "Person's details updated!")); } public void removePerson(PersonDTO person) { logger.debug("removePerson called"); personService.deletePerson(person); persons = personService.listPersons(); FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "", "Person's details deleted!")); } }
3f317de8fbb0493fe56218df5eba12212d6fc9a5
[ "Markdown", "Java", "Text" ]
8
Markdown
szaboz89/person-app
97162e68ff591888133497378ba052a52e3f88a6
2694feb61c86d791d94f9dcb57f12400f91e0814
refs/heads/master
<repo_name>zhangweiguo702141367/mybatis-plus<file_sep>/mybatis-plus/src/main/java/com/baomidou/mybatisplus/mapper/SqlQuery.java /** * Copyright (c) 2011-2020, hubin (<EMAIL>). * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.baomidou.mybatisplus.mapper; import java.util.Collections; import java.util.List; import java.util.Map; import org.apache.ibatis.logging.Log; import org.apache.ibatis.logging.LogFactory; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import com.baomidou.mybatisplus.entity.GlobalConfiguration; import com.baomidou.mybatisplus.entity.TableInfo; import com.baomidou.mybatisplus.plugins.pagination.Pagination; import com.baomidou.mybatisplus.toolkit.CollectionUtils; import com.baomidou.mybatisplus.toolkit.StringUtils; import com.baomidou.mybatisplus.toolkit.TableInfoHelper; /** * <p> * SqlQuery 执行 SQL * </p> * * @author Caratacus * @Date 2016-12-11 */ public class SqlQuery { private static final Log logger = LogFactory.getLog(SqlQuery.class); // 单例Query public static final SqlQuery SQL_QUERY = new SqlQuery(); private SqlSessionFactory sqlSessionFactory; private TableInfo tableInfo; public SqlQuery() { this.tableInfo = TableInfoHelper.getRandomTableInfo(); String configMark = tableInfo.getConfigMark(); GlobalConfiguration globalConfiguration = GlobalConfiguration.GlobalConfig(configMark); this.sqlSessionFactory = globalConfiguration.getSqlSessionFactory(); } public SqlQuery(Class<?> clazz) { this.tableInfo = SqlHelper.table(clazz); GlobalConfiguration globalConfiguration = GlobalConfiguration.GlobalConfig(tableInfo.getConfigMark()); this.sqlSessionFactory = globalConfiguration.getSqlSessionFactory(); } public boolean insert(String sql, Object... args) { return SqlHelper.retBool(sqlSession().insert(sqlStatement("insertSql"), StringUtils.sqlArgsFill(sql, args))); } public boolean delete(String sql, Object... args) { return SqlHelper.retBool(sqlSession().delete(sqlStatement("deleteSql"), StringUtils.sqlArgsFill(sql, args))); } public boolean update(String sql, Object... args) { return SqlHelper.retBool(sqlSession().update(sqlStatement("updateSql"), StringUtils.sqlArgsFill(sql, args))); } public List<Map<String, Object>> selectList(String sql, Object... args) { return sqlSession().selectList(sqlStatement("selectListSql"), StringUtils.sqlArgsFill(sql, args)); } public int selectCount(String sql, Object... args) { return sqlSession().<Integer>selectOne(sqlStatement("selectCountSql"), StringUtils.sqlArgsFill(sql, args)); } public Map<String, Object> selectOne(String sql, Object... args) { List<Map<String, Object>> list = selectList(sql, args); if (CollectionUtils.isNotEmpty(list)) { int size = list.size(); if (size > 1) { logger.warn(String.format("Warn: selectOne Method There are %s results.", size)); } return list.get(0); } return Collections.emptyMap(); } public List<Map<String, Object>> selectPage(Pagination page, String sql, Object... args) { if (null == page) { return null; } return sqlSession().selectList(sqlStatement("selectPageSql"), StringUtils.sqlArgsFill(sql, args), page); } /** * 获取默认的SqlQuery(适用于单库) * * @return */ public static SqlQuery db() { return SQL_QUERY; } /** * 根据当前class对象获取SqlQuery(适用于多库) * * @param clazz * @return */ public static SqlQuery db(Class<?> clazz) { return new SqlQuery(clazz); } /** * <p> * 获取Session 默认自动提交 * <p/> */ private SqlSession sqlSession() { return sqlSessionFactory.openSession(true); } private String sqlStatement(String sqlMethod) { return tableInfo.getSqlStatement(sqlMethod); } }
3d5bc8d186755fc8f53927e7f63c1c0cbb708c88
[ "Java" ]
1
Java
zhangweiguo702141367/mybatis-plus
94ffc15eee18470b06b414ebb4ed3a7ab904eedd
13daf32aab88f3219497f94157dd00b9e744a0db
refs/heads/master
<file_sep> //import java.nio.channels.Channel; import java.util.*; public class ChronoTimer { private static boolean power; //true = on, false = off private static Channel [] channels = {new Channel(0), new Channel(1)}; //2 channels for first sprint, initialized to 8 disarmed channels private static ArrayList<Competitor> toStart; //the racers who have not yet started private static Queue<Competitor> toFinish; //the racers who have started but not finished yet private static ArrayList<Competitor> completedRacers; //racers who have finished //private static Time time; //used for recording the system time at any given moment in time public static void powerOn() { power = true; } public static void powerOff() { power = false; } public static void exit() { if(power == true) System.exit(0); //might need to be redone, not sure what exit is supposed to do } public static void reset() { //default values if(power == true) { toStart.clear(); toFinish.clear(); completedRacers.clear(); disarmAll(); } } public static void connectChannel(String type, int index) // we don't need this, all 8 channels are connected by default { if(index>=channels.length) throw new IllegalArgumentException(); channels[index].connectSensor(new Sensor(type)); } public static void armChannel(int index) { if(index>=channels.length) throw new IllegalArgumentException(); if(channels[index] == null) throw new IllegalArgumentException(); channels[index].arm(); } public static void disarmChannel(int index) { if(index>=channels.length) throw new IllegalArgumentException(); if(channels[index] == null) throw new IllegalArgumentException(); channels[index].disArm(); } public static void disarmAll() { if(!power) throw new IllegalStateException(); for (Channel ch : channels){ if(ch == null); else ch.disArm(); } } public static void addCompetitor(Competitor c) { if(!power) throw new IllegalStateException(); if(toStart.contains(c)) throw new IllegalArgumentException(); toStart.add(c); } public static void start() //start, finish, dnf, and cancel are either called manually (in driver/test class) { // or called in trigger() (in Channel) if(!power) throw new IllegalStateException(); if(toStart.isEmpty()) throw new IllegalStateException(); Competitor c = toStart.remove(0); c.setStartTime(Time.getCurrentTime()); toFinish.add(c); } public static void finish() { if(!power) throw new IllegalStateException(); if(toFinish.peek() == null) throw new IllegalStateException(); //completedRacers.add(toFinish.remove().setFinishTime(Time.getCurrentTime())); Competitor c = toFinish.remove(); c.setFinishTime(Time.getCurrentTime()); completedRacers.add(c); } public static void dnf() { if(!power) throw new IllegalStateException(); if(toFinish.peek() == null) throw new IllegalStateException(); //completedRacers.add(toFinish.remove().setFinishTime(-1)); Competitor c = toFinish.remove(); c.setFinishTime(-1); //maybe add "did not finish" variable in competitor? TODO TODO TODO completedRacers.add(c); } public static void cancel() { if(!power) throw new IllegalStateException(); if(toFinish.peek() == null) throw new IllegalStateException(); //toStart.set(0,toFinish.remove().setStartTime(0)); Competitor c = toFinish.remove(); c.setStartTime(0.0); //clear the start time toStart.set(0, c); //adds the canceled racer back to the head of toStart so they can redo the start. } public static void print() { if(!power) throw new IllegalStateException(); System.out.println("Run /t BIB /t TIME"); for (Competitor c : completedRacers) { if(!c.isDNF()) System.out.println("1 /t" + c.getNumber() + "/t" + c.calculateTotalTime()); else System.out.println("1 /t" + c.getNumber() + "/t" + "DNF"); } } }
381afc94cca23d38dd0471d8bbaacfe7c76dbd58
[ "Java" ]
1
Java
amadouba/ClassProject
befc6cde96bce0bcabf364ab1b643100955c6327
07e4df4d4e6133a563526e6d2a8fb97139d433d4
refs/heads/master
<file_sep>package com.lambostudio.calculator interface MainView { fun setUpCalculator() fun pressNumber(number: Int) fun updateText() fun clearScreen() }<file_sep>package com.lambostudio.calculator enum class Operator { NONE, SUBSTRACT, ADDITION, MULTIPLY, DIVIDE } <file_sep>package com.lambostudio.calculator interface PerformOperation { fun changeOperator(operator: Operator) fun pressEquals() }<file_sep>package com.lambostudio.calculator; class MainActivityPresenter(mainView: MainView,performOperation: PerformOperation) { val mainView = mainView val performOperation = performOperation fun clear() { mainView.clearScreen() } fun calculate() { performOperation.pressEquals() } fun setupUi() { mainView.setUpCalculator() } fun updateText() { mainView.updateText() } } <file_sep>package com.lambostudio.calculator import android.os.Bundle import android.util.Log import androidx.appcompat.app.AppCompatActivity import com.lambostudio.calculator.databinding.ActivityMainBinding import java.text.DecimalFormat class MainActivity : AppCompatActivity(), PerformOperation, MainView { private lateinit var presenter: MainActivityPresenter private lateinit var binding: ActivityMainBinding var isLastButtonOperator = false var currentOperator = Operator.NONE var labelString = "" // will contain the string that is entered in the textView var savedNum = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) val view = binding.root setContentView(view) presenter = MainActivityPresenter(this, this) presenter.setupUi() } override fun setUpCalculator() { val allButtons = arrayOf( binding.zero, binding.one, binding.two, binding.three, binding.four, binding.five, binding.six, binding.seven, binding.height, binding.nine ) for (i in allButtons.indices) { allButtons[i].setOnClickListener { pressNumber(i) Log.e("###", "$i") } } binding.add.setOnClickListener { changeOperator(Operator.ADDITION) } binding.subtract.setOnClickListener { changeOperator(Operator.SUBSTRACT) } binding.multiply.setOnClickListener { changeOperator(Operator.MULTIPLY) } binding.divide.setOnClickListener { changeOperator(Operator.DIVIDE) } binding.equal.setOnClickListener { presenter.calculate() } binding.ac.setOnClickListener { presenter.clear() } } override fun pressEquals() { if (isLastButtonOperator) { return } val labelInt = labelString.toInt()// second number when (currentOperator) { Operator.ADDITION -> savedNum += labelInt Operator.SUBSTRACT -> savedNum -= labelInt Operator.MULTIPLY -> savedNum *= labelInt Operator.DIVIDE -> savedNum /= labelInt Operator.NONE -> return } currentOperator = Operator.NONE labelString = "$savedNum" presenter.updateText() isLastButtonOperator = true } override fun updateText() { if (labelString.length > 8) { presenter.clear() // reset everything to 0 binding.display.text = "too long" return } val labelInt = labelString.toInt() // convert it to a number to prevent multiple 0 start labelString = labelInt.toString() if (currentOperator == Operator.NONE) { savedNum = labelInt } val df = DecimalFormat("#,###") binding.display.text = df.format(labelInt) } override fun clearScreen() { isLastButtonOperator = false currentOperator = Operator.NONE labelString = "" // will contain the string that is entered in the textView savedNum = 0 binding.display.text = "0" } override fun pressNumber(number: Int) { val stringValue = number.toString() if (isLastButtonOperator) { isLastButtonOperator = false labelString = "0" } labelString = "$labelString$stringValue" updateText() } override fun changeOperator(operator: Operator) { if (savedNum == 0) { return } currentOperator = operator isLastButtonOperator = true } }
a826bbfcf9b7396a4602d7f7d3d21f850c9b09c3
[ "Kotlin" ]
5
Kotlin
brandondasb/Calculator
0653d8c8b9eded478d8bf86deaecde854a9f96d6
0fd7f1ec0e86d76b5997ddafb5697a136a83f11f
refs/heads/master
<file_sep>use std::env; use std::path::{Path}; use std::process::{Command}; // Environment variables: // // * LLVM_CONFIG_PATH - provides a path to an `llvm-config` executable // * LIBCLANG_PATH - provides a path to a directory containing a `libclang` shared library // * LIBCLANG_STATIC_PATH - provides a path to a directory containing LLVM and Clang static libraries /// Returns whether the supplied directory contains the supplied file. fn contains(directory: &str, file: &str) -> bool { Path::new(&directory).join(&file).exists() } /// Panics with a user friendly error message. fn error(file: &str, env: &str) -> ! { panic!("could not find {0}, set the {1} environment variable to a path where {0} can be found", file, env); } /// Runs a console command, returning the output if the command was successfully executed. fn run(command: &str, arguments: &[&str]) -> Option<String> { Command::new(command).args(arguments).output().map(|o| { String::from_utf8_lossy(&o.stdout).into_owned() }).ok() } /// Runs `llvm-config`, returning the output if the command was successfully executed. fn run_llvm_config(arguments: &[&str]) -> Option<String> { run(&env::var("LLVM_CONFIG_PATH").unwrap_or("llvm-config".into()), arguments) } /// Backup search directories for Linux. const SEARCH_LINUX: &'static [&'static str] = &[ "/usr/lib", "/usr/lib/llvm", "/usr/lib/llvm-3.8/lib", "/usr/lib/llvm-3.7/lib", "/usr/lib/llvm-3.6/lib", "/usr/lib/llvm-3.5/lib", "/usr/lib/llvm-3.4/lib", "/usr/lib64/llvm", "/usr/lib/x86_64-linux-gnu", "/usr/local/lib", ]; /// Backup search directories for OS X. const SEARCH_OSX: &'static [&'static str] = &[ "/usr/local/opt/llvm/lib", "/Library/Developer/CommandLineTools/usr/lib", "/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib", "/usr/local/opt/llvm35/lib/llvm-3.8/lib", "/usr/local/opt/llvm35/lib/llvm-3.7/lib", "/usr/local/opt/llvm35/lib/llvm-3.6/lib", "/usr/local/opt/llvm35/lib/llvm-3.5/lib", ]; /// Backup search directories for Windows. const SEARCH_WINDOWS: &'static [&'static str] = &[ "C:\\Program Files\\LLVM\\bin", "C:\\Program Files\\LLVM\\lib", ]; /// Searches for a library, returning the directory it can be found in if the search was successful. fn find(file: &str, env: &str) -> Option<String> { // Search the directory provided by the relevant environment variable, if set. if let Some(directory) = env::var(env).ok() { if contains(&directory, file) { return Some(directory); } } // Search the directory returned by `llvm-config --libdir`, if `llvm-config` is available. if let Some(output) = run_llvm_config(&["--libdir"]) { let directory = output.lines().map(|s| s.to_string()).next().unwrap(); if contains(&directory, file) { return Some(directory); } } // Search the backup directories. let search = if cfg!(any(target_os="freebsd", target_os="linux")) { SEARCH_LINUX } else if cfg!(target_os="macos") { SEARCH_OSX } else if cfg!(target_os="windows") { SEARCH_WINDOWS } else { return None; }; search.iter().find(|d| contains(d, file)).map(|s| s.to_string()) } /// Clang libraries required to link to `libclang` statically. const CLANG_LIBRARIES: &'static [&'static str] = &[ "clang", "clangAST", "clangAnalysis", "clangBasic", "clangDriver", "clangEdit", "clangFrontend", "clangIndex", "clangLex", "clangParse", "clangRewrite", "clangSema", "clangSerialization", ]; /// Returns the LLVM libraries required to link to `libclang` statically. fn get_llvm_libraries() -> Vec<String> { run_llvm_config(&["--libs"]).expect( "could not execute `llvm-config --libs`, set the LLVM_CONFIG_PATH environment variable to \ a path to an `llvm-config` executable" ).split_whitespace().filter_map(|p| { // Depending on the version of `llvm-config` in use, listed libraries may be in one of two // forms, a full path to the library or simply prefixed with `-l`. if p.starts_with("-l") { Some(p[2..].into()) } else { Path::new(p).file_stem().map(|l| l.to_string_lossy()[3..].into()) } }).collect() } fn main() { if cfg!(feature="static") { // Find LLVM and Clang static libraries. let directory = match find("libclang.a", "LIBCLANG_STATIC_PATH") { Some(directory) => directory, _ => error("libclang.a", "LIBCLANG_STATIC_PATH"), }; print!("cargo:rustc-flags="); // Specify required LLVM and Clang static libraries. print!("-L {} ", directory); for library in get_llvm_libraries() { print!("-l static={} ", library); } for library in CLANG_LIBRARIES { print!("-l static={} ", library); } // Specify required system libraries. if cfg!(any(target_os="freebsd", target_os="linux")) { println!("-l ffi -l ncursesw -l stdc++ -l z"); } else if cfg!(target_os="macos") { println!("-l ffi -l ncurses -l stdc++ -l z"); } else { panic!("unsupported operating system for static linking"); }; } else { let file = if cfg!(target_os="windows") { // The filename of the `libclang` shared library on Windows is `libclang.dll` instead of // the expected `clang.dll`. "libclang.dll".into() } else { format!("{}clang{}", env::consts::DLL_PREFIX, env::consts::DLL_SUFFIX) }; // Find the `libclang` shared library. let directory = match find(&file, "LIBCLANG_PATH") { Some(directory) => directory, _ => error(&file, "LIBCLANG_PATH") }; println!("cargo:rustc-link-search={}", directory); if cfg!(all(target_os="windows", target_env="msvc")) { let lib_file = "libclang.lib"; // Find the `libclang` link library. let lib_directory = match find(lib_file, "LIBCLANG_PATH") { Some(directory) => directory, _ => error(lib_file, "LIBCLANG_PATH") }; println!("cargo:rustc-link-search={}", lib_directory); println!("cargo:rustc-link-lib=dylib=libclang"); } else { println!("cargo:rustc-link-lib=dylib=clang"); }; } }
7dd82ad3e92d80e94579b2f6fa2d991e8d649296
[ "Rust" ]
1
Rust
JoNil/clang-sys
06e1c1b9cb28136a27aa848ac13c4f06a7fb8f8f
bdc7d258488d57fe17580e54cc7699079dc28cf5
refs/heads/master
<repo_name>jakeibeemassa0908/PostOfficeMock<file_sep>/DataBase/PostOfficeSQLScript.sql -- MySQL Workbench Forward Engineering SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0; SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0; SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION'; -- ----------------------------------------------------- -- Schema PostOffice -- ----------------------------------------------------- -- ----------------------------------------------------- -- Schema PostOffice -- ----------------------------------------------------- CREATE SCHEMA IF NOT EXISTS `PostOffice` DEFAULT CHARACTER SET utf8 ; USE `PostOffice` ; -- ----------------------------------------------------- -- Table `PostOffice`.`Authentication` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `PostOffice`.`Authentication` ( `AuthenticationID` INT(11) NOT NULL AUTO_INCREMENT, `AuthenticationLevel` VARCHAR(20) NOT NULL, PRIMARY KEY (`AuthenticationID`), UNIQUE INDEX `AUTHID_UNIQUE` (`AuthenticationID` ASC), UNIQUE INDEX `AUTHLevel_UNIQUE` (`AuthenticationLevel` ASC)) ENGINE = InnoDB AUTO_INCREMENT = 4 DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `PostOffice`.`Customer` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `PostOffice`.`Customer` ( `CustomerID` INT(11) NOT NULL AUTO_INCREMENT, `Fname` VARCHAR(25) NOT NULL, `MInit` VARCHAR(1) NOT NULL, `Lname` VARCHAR(25) NOT NULL, `Email` VARCHAR(60) NOT NULL, `MobileNumber` VARCHAR(20) NOT NULL, `HouseNumber` VARCHAR(10) NOT NULL, `Street` VARCHAR(40) NOT NULL, `ZipCode` VARCHAR(10) NOT NULL, `City` VARCHAR(20) NOT NULL, `State` VARCHAR(20) NOT NULL, `Country` VARCHAR(20) NOT NULL, PRIMARY KEY (`CustomerID`, `Email`), UNIQUE INDEX `CustomerID_UNIQUE` (`CustomerID` ASC), UNIQUE INDEX `Email_UNIQUE` (`Email` ASC), UNIQUE INDEX `MobileNumber_UNIQUE` (`MobileNumber` ASC)) ENGINE = InnoDB AUTO_INCREMENT = 10002 DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `PostOffice`.`CustomerLogin` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `PostOffice`.`CustomerLogin` ( `CustomerEmail` VARCHAR(60) NOT NULL, `CustomerPassword` VARCHAR(60) NOT NULL, PRIMARY KEY (`CustomerEmail`), UNIQUE INDEX `Customer_Email_UNIQUE` (`CustomerEmail` ASC), INDEX `fk_CustomerLogin_Customer1_idx` (`CustomerEmail` ASC), CONSTRAINT `fk_CustomerLogin_Customer1` FOREIGN KEY (`CustomerEmail`) REFERENCES `PostOffice`.`Customer` (`Email`) ON UPDATE CASCADE) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `PostOffice`.`Location` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `PostOffice`.`Location` ( `LocationID` INT(11) NOT NULL AUTO_INCREMENT, `Hours` VARCHAR(10) NOT NULL, `BuildingNumber` VARCHAR(10) NOT NULL, `Street` VARCHAR(40) NOT NULL, `ZipCode` VARCHAR(10) NOT NULL, `City` VARCHAR(20) NOT NULL, `State` VARCHAR(20) NOT NULL, `Country` VARCHAR(20) NOT NULL, PRIMARY KEY (`LocationID`), UNIQUE INDEX `LocationID_UNIQUE` (`LocationID` ASC)) ENGINE = InnoDB AUTO_INCREMENT = 103 DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `PostOffice`.`Roles` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `PostOffice`.`Roles` ( `RolesID` INT(11) NOT NULL AUTO_INCREMENT, `RoleName` VARCHAR(20) NOT NULL, PRIMARY KEY (`RolesID`), UNIQUE INDEX `RolesID_UNIQUE` (`RolesID` ASC), UNIQUE INDEX `RoleName_UNIQUE` (`RoleName` ASC)) ENGINE = InnoDB AUTO_INCREMENT = 6 DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `PostOffice`.`Employee` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `PostOffice`.`Employee` ( `EmployeeID` INT(11) NOT NULL AUTO_INCREMENT, `LocationID` INT(11) NOT NULL, `RoleID` INT(11) NOT NULL, `AuthID` INT(11) NOT NULL, `Fname` VARCHAR(25) NOT NULL, `MInit` VARCHAR(1) NOT NULL, `Lname` VARCHAR(25) NOT NULL, `MobliePhone` VARCHAR(20) NOT NULL, `WorkPhone` VARCHAR(20) NULL DEFAULT NULL, `Wage` DOUBLE NOT NULL, `HiredOn` DATE NOT NULL, `WorkEmail` VARCHAR(60) NOT NULL, `PersonalEmail` VARCHAR(60) NULL DEFAULT NULL, `HouseNumber` VARCHAR(10) NOT NULL, `Street` VARCHAR(40) NOT NULL, `ZipCode` VARCHAR(10) NOT NULL, `City` VARCHAR(20) NOT NULL, `State` VARCHAR(20) NOT NULL, `Country` VARCHAR(20) NOT NULL, `CurrentlyEmployed` TINYINT(1) NOT NULL DEFAULT '1', PRIMARY KEY (`EmployeeID`), UNIQUE INDEX `EmployeesID_UNIQUE` (`EmployeeID` ASC), UNIQUE INDEX `MobliePhone_UNIQUE` (`MobliePhone` ASC), UNIQUE INDEX `WorkEmail_UNIQUE` (`WorkEmail` ASC), UNIQUE INDEX `PersonalEmail_UNIQUE` (`PersonalEmail` ASC), UNIQUE INDEX `WorkPhone_UNIQUE` (`WorkPhone` ASC), INDEX `fk_Employee_Location1_idx` (`LocationID` ASC), INDEX `fk_Employee_Roles1_idx` (`RoleID` ASC), INDEX `fk_Employee_AUTH1_idx` (`AuthID` ASC), CONSTRAINT `fk_Employee_AUTH1` FOREIGN KEY (`AuthID`) REFERENCES `PostOffice`.`Authentication` (`AuthenticationID`) ON UPDATE CASCADE, CONSTRAINT `fk_Employee_Location1` FOREIGN KEY (`LocationID`) REFERENCES `PostOffice`.`Location` (`LocationID`) ON UPDATE CASCADE, CONSTRAINT `fk_Employee_Roles1` FOREIGN KEY (`RoleID`) REFERENCES `PostOffice`.`Roles` (`RolesID`) ON UPDATE CASCADE) ENGINE = InnoDB AUTO_INCREMENT = 10005 DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `PostOffice`.`EmployeeLogin` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `PostOffice`.`EmployeeLogin` ( `EmployeeID` INT(11) NOT NULL, `EmployeePassword` VARCHAR(60) NOT NULL, PRIMARY KEY (`EmployeeID`), UNIQUE INDEX `EmployeeID_UNIQUE` (`EmployeeID` ASC), CONSTRAINT `fk_EmployeeLogin_Employee1` FOREIGN KEY (`EmployeeID`) REFERENCES `PostOffice`.`Employee` (`EmployeeID`) ON UPDATE CASCADE) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `PostOffice`.`Online Products` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `PostOffice`.`Online Products` ( `ProductID` INT(11) NOT NULL AUTO_INCREMENT, `ProductName` VARCHAR(20) NOT NULL, `Stock` INT(10) UNSIGNED NOT NULL, `Price` DOUBLE UNSIGNED NOT NULL, `ReStockDate` DATE NOT NULL, `Available` TINYINT(1) NOT NULL DEFAULT '1', `ImagePath` VARCHAR(100) NULL DEFAULT NULL, PRIMARY KEY (`ProductID`), UNIQUE INDEX `ProductID_UNIQUE` (`ProductID` ASC)) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `PostOffice`.`Payment type` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `PostOffice`.`Payment type` ( `typeID` INT(11) NOT NULL AUTO_INCREMENT, `PaymentTypeName` VARCHAR(15) NOT NULL, PRIMARY KEY (`typeID`), UNIQUE INDEX `Name_UNIQUE` (`PaymentTypeName` ASC)) ENGINE = InnoDB AUTO_INCREMENT = 6 DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `PostOffice`.`Transactions` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `PostOffice`.`Transactions` ( `TransactionID` INT(11) NOT NULL AUTO_INCREMENT, `CustomerID` INT(11) NOT NULL, `DateOfSale` DATETIME NOT NULL, `TotalPrice` DOUBLE UNSIGNED NOT NULL, `FirstFourCC` VARCHAR(4) NULL DEFAULT NULL, `FnameCC` VARCHAR(25) NULL DEFAULT NULL, `LnameCC` VARCHAR(25) NULL DEFAULT NULL, `MInitCC` VARCHAR(1) NULL DEFAULT NULL, `PaymentTypeID` INT(11) NOT NULL, `EmployeeID` INT(11) NULL DEFAULT NULL, PRIMARY KEY (`TransactionID`), UNIQUE INDEX `TransactionID_UNIQUE` (`TransactionID` ASC), INDEX `fk_Online Transactions_Customer1_idx` (`CustomerID` ASC), INDEX `fk_Transactions_Payment type1_idx` (`PaymentTypeID` ASC), INDEX `fk_Transactions_Employee1_idx` (`EmployeeID` ASC), CONSTRAINT `fk_Online Transactions_Customer1` FOREIGN KEY (`CustomerID`) REFERENCES `PostOffice`.`Customer` (`CustomerID`) ON UPDATE CASCADE, CONSTRAINT `fk_Transactions_Employee1` FOREIGN KEY (`EmployeeID`) REFERENCES `PostOffice`.`Employee` (`EmployeeID`) ON UPDATE CASCADE, CONSTRAINT `fk_Transactions_Payment type1` FOREIGN KEY (`PaymentTypeID`) REFERENCES `PostOffice`.`Payment type` (`typeID`) ON UPDATE CASCADE) ENGINE = InnoDB AUTO_INCREMENT = 10002 DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `PostOffice`.`Order Details` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `PostOffice`.`Order Details` ( `ProductID` INT(11) NOT NULL, `TransactionID` INT(11) NOT NULL, `Quantity` INT(10) UNSIGNED NOT NULL, `UnitPrice` DOUBLE UNSIGNED NOT NULL, PRIMARY KEY (`ProductID`, `TransactionID`), INDEX `fk_Online Products_has_Online Transactions_Online Transacti_idx` (`TransactionID` ASC), INDEX `fk_Online Products_has_Online Transactions_Online Products1_idx` (`ProductID` ASC), CONSTRAINT `fk_Online Products_has_Online Transactions_Online Products1` FOREIGN KEY (`ProductID`) REFERENCES `PostOffice`.`Online Products` (`ProductID`) ON UPDATE CASCADE, CONSTRAINT `fk_Online Products_has_Online Transactions_Online Transactions1` FOREIGN KEY (`TransactionID`) REFERENCES `PostOffice`.`Transactions` (`TransactionID`) ON UPDATE CASCADE) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `PostOffice`.`Package State` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `PostOffice`.`Package State` ( `PackageStateID` INT(11) NOT NULL AUTO_INCREMENT, `State` VARCHAR(20) NOT NULL, PRIMARY KEY (`PackageStateID`), UNIQUE INDEX `PackageStateID_UNIQUE` (`PackageStateID` ASC), UNIQUE INDEX `State_UNIQUE` (`State` ASC)) ENGINE = InnoDB AUTO_INCREMENT = 6 DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `PostOffice`.`Package` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `PostOffice`.`Package` ( `PackageID` INT(11) NOT NULL AUTO_INCREMENT, `TransactionID` INT(11) NOT NULL, `CustomerID` INT(11) NOT NULL, `SendToHouseNumber` VARCHAR(10) NOT NULL, `SendToStreet` VARCHAR(40) NOT NULL, `SendToZipCode` VARCHAR(10) NOT NULL, `SendToCity` VARCHAR(20) NOT NULL, `SendToState` VARCHAR(20) NOT NULL, `SendToCountry` VARCHAR(20) NOT NULL, `PackageWeight` DOUBLE UNSIGNED NOT NULL, `PackageSize` DOUBLE UNSIGNED NOT NULL, `SentDate` DATE NOT NULL, `ETA` DATE NOT NULL, `PackageStateID` INT(11) NOT NULL, `Subscribed` TINYINT(1) UNSIGNED NOT NULL DEFAULT '0', PRIMARY KEY (`PackageID`), UNIQUE INDEX `PackageID_UNIQUE` (`PackageID` ASC), INDEX `fk_Package_Customer1_idx` (`CustomerID` ASC), INDEX `fk_Package_Package State1_idx` (`PackageStateID` ASC), INDEX `fk_Package_Transactions1_idx` (`TransactionID` ASC), CONSTRAINT `fk_Package_Customer1` FOREIGN KEY (`CustomerID`) REFERENCES `PostOffice`.`Customer` (`CustomerID`) ON UPDATE CASCADE, CONSTRAINT `fk_Package_Package State1` FOREIGN KEY (`PackageStateID`) REFERENCES `PostOffice`.`Package State` (`PackageStateID`) ON UPDATE CASCADE, CONSTRAINT `fk_Package_Transactions1` FOREIGN KEY (`TransactionID`) REFERENCES `PostOffice`.`Transactions` (`TransactionID`) ON UPDATE CASCADE) ENGINE = InnoDB AUTO_INCREMENT = 10002 DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `PostOffice`.`Trucks` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `PostOffice`.`Trucks` ( `TruckID` INT(11) NOT NULL AUTO_INCREMENT, `EmployeeID` INT(11) NOT NULL, PRIMARY KEY (`TruckID`), UNIQUE INDEX `TruckID_UNIQUE` (`TruckID` ASC), INDEX `fk_Trucks_Employee1_idx` (`EmployeeID` ASC), CONSTRAINT `fk_Trucks_Employee1` FOREIGN KEY (`EmployeeID`) REFERENCES `PostOffice`.`Employee` (`EmployeeID`) ON UPDATE CASCADE) ENGINE = InnoDB AUTO_INCREMENT = 102 DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `PostOffice`.`Tracking` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `PostOffice`.`Tracking` ( `ROW` INT(11) NOT NULL AUTO_INCREMENT, `PackageID` INT(11) NOT NULL, `TruckID` INT(11) NOT NULL, `HandlerID` INT(11) NOT NULL, `CurrentLocationID` INT(11) NOT NULL, `GoingToHouseNumber` VARCHAR(10) NULL DEFAULT NULL, `GoingToStreet` VARCHAR(40) NULL DEFAULT NULL, `GoingToZipCode` VARCHAR(10) NULL DEFAULT NULL, `GoingToCity` VARCHAR(20) NULL DEFAULT NULL, `GoingToState` VARCHAR(20) NULL DEFAULT NULL, `GoingToCountry` VARCHAR(20) NULL DEFAULT NULL, `GoingToLocationID` INT(11) NULL DEFAULT NULL, `Date` DATETIME NOT NULL, PRIMARY KEY (`ROW`), UNIQUE INDEX `ROW_UNIQUE` (`ROW` ASC), INDEX `fk_Tracking_Package1` (`PackageID` ASC), INDEX `fk_Tracking_Trucks1_idx` (`TruckID` ASC), INDEX `fk_Tracking_Employee1_idx` (`HandlerID` ASC), INDEX `fk_Tracking_Location1_idx` (`CurrentLocationID` ASC), INDEX `fk_Tracking_Location2_idx` (`GoingToLocationID` ASC), CONSTRAINT `fk_Tracking_Employee1` FOREIGN KEY (`HandlerID`) REFERENCES `PostOffice`.`Employee` (`EmployeeID`) ON UPDATE CASCADE, CONSTRAINT `fk_Tracking_Location1` FOREIGN KEY (`CurrentLocationID`) REFERENCES `PostOffice`.`Location` (`LocationID`) ON UPDATE CASCADE, CONSTRAINT `fk_Tracking_Location2` FOREIGN KEY (`GoingToLocationID`) REFERENCES `PostOffice`.`Location` (`LocationID`) ON UPDATE CASCADE, CONSTRAINT `fk_Tracking_Package1` FOREIGN KEY (`PackageID`) REFERENCES `PostOffice`.`Package` (`PackageID`) ON UPDATE CASCADE, CONSTRAINT `fk_Tracking_Trucks1` FOREIGN KEY (`TruckID`) REFERENCES `PostOffice`.`Trucks` (`TruckID`) ON UPDATE CASCADE) ENGINE = InnoDB AUTO_INCREMENT = 3 DEFAULT CHARACTER SET = utf8; SET SQL_MODE=@OLD_SQL_MODE; SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS; SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS; <file_sep>/FrontEnd/PostOfficeAngularSite/src/app/login/login.component.ts import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { Router } from '@angular/router'; import { AuthService } from '../_services/auth.service'; import { APIService } from '../_services/api.service'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.css'] }) export class LoginComponent implements OnInit { loginForm: FormGroup; hideAlert = true; errorMessage = ''; constructor(private formBuilder: FormBuilder, public auth: AuthService, public api: APIService, public myRoute: Router) { } ngOnInit() { this.loginForm = this.formBuilder.group({ email: ['', Validators.compose([Validators.required])], password: ['', Validators.compose([Validators.required])] }); } login() { //login forms were filled out if (this.loginForm.valid) { var data = this.api.userLoginAuth(this.loginForm.value.email, this.loginForm.value.password) .subscribe((data: {}) => { //we have logged in a nd API returns user ID if (data[0] != undefined) { console.log("User: " + data[0].CustomerID + " has logged in"); this.auth.sendToken("user", data[0].CustomerID); this.myRoute.navigate(["home"]); } else { this.hideAlert = false; this.errorMessage = "Incorect Email or Passowrd"; } });; } //something was missing. else { this.errorMessage = "One of the fields is missing!"; this.hideAlert = false; } } closeAlert() { this.hideAlert = true; } } <file_sep>/FrontEnd/PostOfficeAngularSite/server/routes/api.js const express = require('express'); const router = express.Router(); var mysql = require('mysql') // Connect const connection = mysql.createConnection({ host: 'mysqlinstance.c0mjh6ewr0w9.us-east-2.rds.amazonaws.com', user: 'masterUsername', password: '<PASSWORD>', database: 'PostOffice' }); connection.connect(function (err) { if (err) { console.error('error connecting: ' + err.stack); return; } console.log('connected as id ' + connection.threadId); }); //LOGIN //return ID of the User that logged in. email & password as params router.get('/userLogin', (req, res) => { Email = req.query.email; Password = <PASSWORD> connection.query('SELECT CustomerID FROM Customer WHERE Email = (SELECT CustomerEmail FROM CustomerLogin WHERE CustomerEmail = ? AND CustomerPassword = ?)', [Email, Password], function (err, rows, fields) { if (err) throw err res.json(rows); }); }); //TRACKING by ID return DATE Location City & state Package Send to address & status based on row router.get('/packageTracking', (req, res) => { console.log(req.query.id); connection.query( 'SELECT Tracking.Date, Location.City, Location.State, Package.SendToHouseNumber, Package.SendToStreet FROM Tracking LEFT JOIN Location ON Tracking.CurrentLocationID = Location.LocationID LEFT JOIN Package ON Package.PackageID = Tracking.PackageID WHERE Tracking.PackageID = ?',[req.query.id], function (err, rows, fields) { if (err) throw err for (var x in rows) { //last in tracking if (x == rows.length - 1) { if (rows[x].City == null) { rows[x].Status = "delivered"; rows[x].City = rows[x].SendToHouseNumber; rows[x].State = rows[x].SendToStreet; } else { rows[x].Status = "in transit"; } } //arived else if (x < rows.length - 1) { rows[x].Status = "arived"; } } res.json(rows); }); }); //myPackages by user ID Return Package ID, SendTO address, ETA, status router.get('/myPackages', (req, res) => { connection.query('SELECT Package.PackageID, Package.SendToHouseNumber, Package.SendToStreet, Package.SendToCity, Package.SendToState, Package.ETA, `Package State`.State FROM Package LEFT JOIN `Package State` ON `Package State`.PackageStateID = Package.PackageStateID WHERE CustomerID = ?', [req.query.id], function (err, rows, fields) { if (err) throw err res.json(rows); }); }); //packages going to Users ADDRESS by id RETURN Package ID, SendTO address, ETA, status router.get('/packagesToAddress', (req, res) => { connection.query('SELECT Package.PackageID, Package.SendToHouseNumber, Package.SendToStreet, Package.SendToCity, Package.SendToState, Package.ETA, `Package State`.State FROM Package LEFT JOIN `Package State` ON `Package State`.PackageStateID = Package.PackageStateID LEFT JOIN Customer ON Package.SendToHouseNumber = Customer.HouseNumber AND Package.SendToStreet = Customer.Street AND Package.SendToZipCode = Customer.ZipCode WHERE Customer.CustomerID = ?', [req.query.id], function (err, rows, fields) { if (err) throw err res.json(rows); }); }); //find location based on ABS of ZipCode router.get('/findLocation', (req, res) => { connection.query('SELECT Location.LocationID, Location.BuildingNumber, Location.ZipCode, Location.City, Location.State, Location.Hours FROM Location ORDER BY ABS(Location.ZipCode - ?) DESC', [req.query.zip], function (err, rows, fields) { if (err) throw err res.json(rows); }); }); router.get('/registerUser', (req, res) => { console.log(req.query); connection.query('INSERT INTO Customer (`Fname`, `MInit`, `Lname`, `Email`, `MobileNumber`, `HouseNumber`, `Street`, `ZipCode`, `City`, `State`, `Country`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, "USA")', [req.query.Fname, req.query.MInit, req.query.Lname, req.query.Email, req.query.MobileNumber, req.query.HouseNumber, req.query.Street, req.query.ZipCode, req.query.City, req.query.State], function (err, rows, fields) { if (err) console.log(err); res.json(err); }); }); router.get('/registerUserLogin', (req, res) => { console.log(req.query); connection.query('INSERT INTO CustomerLogin (`CustomerEmail`, `CustomerPassword`) VALUES (?, ?)', [req.query.Email, req.query.Password], function (err, rows, fields) { if (err) console.log(err); res.json(err); }); }); module.exports = router; <file_sep>/FrontEnd/PostOfficeAngularSite/src/app/location-employees/location-employees.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-location-employees', templateUrl: './location-employees.component.html', styleUrls: ['./location-employees.component.css'] }) export class LocationEmployeesComponent implements OnInit { constructor() { } ngOnInit() { } } <file_sep>/FrontEnd/PostOfficeAngularSite/src/app/tracking/tracking.component.ts import { Component, OnInit } from '@angular/core'; import { FormControl } from '@angular/forms'; import { APIService } from '../_services/api.service'; @Component({ selector: 'app-tracking', templateUrl: './tracking.component.html', styleUrls: ['./tracking.component.css'] }) export class TrackingComponent implements OnInit { ID = ''; IDForm = new FormControl(''); hideAlert = true; hideTracking = true; panelOpenState = false; Response; constructor(public api: APIService) {} trackPackage() //validate the package id { this.api.packageTracking(this.IDForm.value) .subscribe((data: {}) => { //no package if (data[0] == undefined) { this.hideTracking = true; this.hideAlert = false; this.ID = ''; } //found the package else if (data[0] != undefined) { this.Response = data; console.log(this.Response); this.hideAlert = true; this.hideTracking = false; } });; } closeAlert() { this.hideAlert = true; } ngOnInit() { } } <file_sep>/FrontEnd/PostOfficeAngularSite/src/app/shop/shop.component.ts import { Component, OnInit, ViewChild } from '@angular/core'; export interface Item { title: string; description: string; image: string; price: string; } @Component({ selector: 'app-shop', templateUrl: './shop.component.html', styleUrls: ['./shop.component.css'] }) export class ShopComponent implements OnInit { constructor() { } ngOnInit() { } items: Item[] = [ {title: 'Thingamajig', description: '4 out of 5 experts agree: it does something', image: 'assets/shop_images/box1.jpg', price: '$500'}, {title: 'Foobar', description: 'It foos the bars', image: 'assets/shop_images/box2.jpg', price: '$500'}, {title: 'Placeholder', description: 'Lorem ipsum latin stuff blah blah', image: 'assets/shop_images/box3.jpg', price: '$500'}, {title: 'Whocares', description: 'Stop reading this', image: 'assets/shop_images/box4.jpg', price: '$500'}, ]; } <file_sep>/FrontEnd/PostOfficeAngularSite/src/app/_services/api.service.ts import { Injectable } from '@angular/core'; import { HttpClientModule, HttpHeaders, HttpErrorResponse, HttpParams, HttpClient } from '@angular/common/http'; import { Observable, of } from 'rxjs'; import { map, catchError, tap } from 'rxjs/operators'; const endpoint = 'http://localhost:3000/api/'; const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) }; @Injectable({ providedIn: 'root' }) export class APIService { constructor(private http: HttpClient) {} private extractData(res: Response) { let body = res; return body || {}; } //USER LOGIN WITH EMAIL & PASSWORD userLoginAuth(email : string, password : string): Observable<any> { const params = new HttpParams().set('email', email).set('password', <PASSWORD>); return this.http.get('http://localhost:3000/api/userLogin', { params }); } //tracking package with ID packageTracking(id: string): Observable<any> { const params = new HttpParams().set('id', id); return this.http.get('http://localhost:3000/api/packageTracking', { params }); } //myPackages by user id myPackages(id: string): Observable<any> { const params = new HttpParams().set('id', id); return this.http.get('http://localhost:3000/api/myPackages', { params }); } //packages to address by user id packagesToAddress(id: string): Observable<any> { const params = new HttpParams().set('id', id); return this.http.get('http://localhost:3000/api/packagesToAddress', { params }); } //closest location based on zip findLocation(zip: string): Observable<any> { const params = new HttpParams().set('zip', zip); return this.http.get('http://localhost:3000/api/findLocation', { params }); } //register User in Customer Table registerUser(Fname: string, MInit: string, Lname: string, Email: string, MobileNumber: string, HouseNumber: string, Street: string, City: string, State: string, ZipCode: string): Observable<any> { const params = new HttpParams().set('Fname', Fname).set('MInit', MInit).set('Lname', Lname).set('Email', Email).set('MobileNumber', MobileNumber).set('HouseNumber', HouseNumber).set('Street', Street).set('City', City).set('State', State).set('ZipCode', ZipCode); return this.http.get('http://localhost:3000/api/registerUser', { params }); } //user to Login table registerUserLogin(Email: string, Password: string): Observable<any> { const params = new HttpParams().set('Email', Email).set('Password', <PASSWORD>); return this.http.get('http://localhost:3000/api/registerUserLogin', { params }); } }
5e5a538e207b7f499f06e06990bdecf731c8f911
[ "JavaScript", "SQL", "TypeScript" ]
7
SQL
jakeibeemassa0908/PostOfficeMock
079511882b7370d1741e55d7d8dec75ab2da5587
d3d4388b22a630712a8e33238dfde2b47d0132af
refs/heads/master
<file_sep>var xPos = 5; function setup () { createCanvas (600, 400); } function draw () { background(250,250,100); stroke (150,0,150); strokeWeight(10); if (mouseX > 300) { line (0,0,600,400); } else if (mouseX > 200) { fill (255,0,0); rect (200,200,100,100); } else if (mouseX > 100) { fill (0,255,0); triangle (300,400,200,150,600,400); } else { fill (0,0,255); ellipse (40,40,200,200); } }
0bea03f54bec9373ef1dbd1673851f0f19f293b5
[ "JavaScript" ]
1
JavaScript
yammy0104/drawing
8f4705765a50c4cb127b02ca7666a2a1a1fed433
f6dc51df6b426fa965809187779b9d6ec502f5dc
refs/heads/master
<repo_name>B4129/LOLTFTTool<file_sep>/src/Data/ItemData.js module.exports.getAllItem =()=>{ return { none: { none: { name: '', icon: '' }, ad: { name: 'BFソード', icon: '1038' }, ap: { name: 'ムダニデカイロッド', icon: '1058' }, as: { name: 'リカーブボウ', icon: '1043' }, mana: { name: '女神の涙', icon: '3070' }, ar: { name: 'チェインベスト', icon: '1031' }, mr: { name: 'なんか魔法防御上がるやつ', icon: '1033' }, hp: { name: 'ジャイアントベルト', icon: '1011' }, other: { name: 'へら', icon: 'https://news-a.akamaihd.net/public/images/articles/2019/june/tftcompendium/Items/spatula.png' } }, ad: { none: { name: 'BFソード', icon: '1038' }, ad: { name: 'インフィニティエッジ', icon: '3031' }, ap: { name: 'ヘクステックガンブレード', icon: '3146' }, as: { name: 'なんか5秒毎にクリティカル上がるやつ', icon: '3131' }, mana: { name: 'ショウジンの矛', icon: '3161' }, ar: { name: 'ガーディアンエンジェル', icon: '3026' }, mr: { name: 'ブラッドサースター', icon: '3072' }, hp: { name: 'ジーク', icon: 'https://vignette.wikia.nocookie.net/leagueoflegends/images/5/54/Zeke%27s_Herald_item.png/revision/latest/scale-to-width-down/46?cb=20171223022057' }, other: { name: '妖夢の霊剣', icon: '3388' }, }, ap: { none: { name: 'ムダニデカイロッド', icon: '1058' }, ad: { category2: 'ad', name: 'ヘクステックガンブレード', icon: '3146' }, ap: { category2: 'ap', name: 'ラバドンデスキャップ', icon: '3089' }, as: { category2: 'as', name: 'グインソーレイジブレード', icon: '3124' }, mana: { category2: 'mana', name: 'ルーデンエコー', icon: '3285' }, ar: { name: 'ソラリのロケット', icon: '3190' }, mr: { category2: 'mr', name: '200ダメージ与える弓', icon: 'https://vignette.wikia.nocookie.net/leagueoflegends/images/9/9c/Ionic_Spark_item.png/revision/latest/scale-to-width-down/46?cb=20171223001148' }, hp: { category2: 'hp', name: 'モレロノミコン', icon: '3165' }, other: { category2: 'other', name: 'ユーミ', icon: 'https://vignette.wikia.nocookie.net/leagueoflegends/images/2/2b/You_and_Me%21.png/revision/latest/scale-to-width-down/46?cb=20190426210438' } }, as: { none: { name: 'リカーブボウ', icon: '1043' }, ad: { category2: 'ad', name: 'なんか5秒毎にクリティカル上がるやつ', icon: '3131' }, ap: { category2: 'ap', name: 'グインソーレイジブレード', icon: '3124' }, as: { category2: 'as', name: 'ラピッドファイアキャノン', icon: '3094' }, mana: { category2: 'mana', name: 'スタティックシヴ', icon: '3087' }, ar: { category2: 'ar', name: 'ファントムダンサー', icon: '3046' }, mr: { category2: 'mr', name: 'レベル下げるやつ', icon: '3137' }, hp: { category2: 'hp', name: 'タイタンハイドラ', icon: '3748' }, other: { category2: 'other', name: 'ルインドキングブレード', icon: '3389' } }, mana: { none: { name: '女神の涙', icon: '3070' }, ad: { category2: 'ad', name: 'ショウジンの矛', icon: '3161' }, ap: { category2: 'ap', name: 'ルーデンエコー', icon: '3285' }, as: { category2: 'as', name: 'スタティックシヴ', icon: '3087' }, mana: { category2: 'mana', name: 'セラフ', icon: '3040' }, ar: { category2: 'ar', name: 'フローズンハート', icon: '3110' }, mr: { category2: 'mr', name: 'サイレンス', icon: 'https://vignette.wikia.nocookie.net/leagueoflegends/images/6/66/Hush_item.png/revision/latest/scale-to-width-down/46?cb=20190618223755' }, hp: { category2: 'hp', name: 'リデンプション', icon: '3107' }, other: { category2: 'other', name: 'デーモンになるやつ', icon: 'https://vignette.wikia.nocookie.net/leagueoflegends/images/d/de/World_Ender.png/revision/latest/scale-to-width-down/46?cb=20180612213606' } }, ar: { none: { name: 'チェインベスト', icon: '1031' }, ad: { category2: 'ad', name: 'ガーディアンエンジェル', icon: '3026' }, ap: { category2: 'ap', name: 'ソラリのロケット', icon: '3190' }, as: { category2: 'as', name: 'ファントムダンサー', icon: '3046' }, mana: { category2: 'mana', name: 'フローズンハート', icon: '3110' }, ar: { category2: 'ar', name: 'ソーンメイル', icon: '3075' }, mr: { category2: 'mr', name: '武装解除', icon: 'https://vignette.wikia.nocookie.net/leagueoflegends/images/e/e8/Sword_Breaker_item.png/revision/latest/scale-to-width-down/46?cb=20190618223710' }, hp: { category2: 'hp', name: '赤バフ', icon: 'https://vignette.wikia.nocookie.net/leagueoflegends/images/e/e7/Red_BramblebackSquare.png/revision/latest/scale-to-width-down/46?cb=20140620025406' }, other: { category2: 'other', name: '騎士の誓い', icon: '3109' } }, mr: { none: { name: 'なんか魔法防御上がるやつ', icon: '1033' }, ad: { category2: 'ad', name: 'ブラッドサースター', icon: '3072' }, ap: { category2: 'ap', name: '200ダメージ与える弓', icon: 'https://vignette.wikia.nocookie.net/leagueoflegends/images/9/9c/Ionic_Spark_item.png/revision/latest/scale-to-width-down/46?cb=20171223001148' }, as: { category2: 'as', name: 'レベル奪う件', icon: '3137' }, mana: { category2: 'mana', name: 'サイレンス', icon: 'https://vignette.wikia.nocookie.net/leagueoflegends/images/6/66/Hush_item.png/revision/latest/scale-to-width-down/46?cb=20190618223755' }, ar: { category2: 'ar', name: '武装解除', icon: 'https://vignette.wikia.nocookie.net/leagueoflegends/images/e/e8/Sword_Breaker_item.png/revision/latest/scale-to-width-down/46?cb=20190618223710' }, mr: { category2: 'mr', name: '魔法耐性', icon: 'https://vignette.wikia.nocookie.net/leagueoflegends/images/f/fd/Dragon%27s_Claw_item.png/revision/latest/scale-to-width-down/46?cb=20190618223744' }, hp: { category2: 'hp', name: 'ゼファー', icon: '3172' }, other: { category2: 'other', name: 'ルナーンハリケーン', icon: '3085' } }, hp: { none: { name: 'ジャイアントベルト', icon: '1011' }, ad: { category2: 'ad', name: 'ジーク', icon: 'https://vignette.wikia.nocookie.net/leagueoflegends/images/5/54/Zeke%27s_Herald_item.png/revision/latest/scale-to-width-down/46?cb=20171223022057' }, ap: { category2: 'ap', name: 'モレロノミコン', icon: '3165' }, as: { category2: 'as', name: 'タイタンハイドラ', icon: '3748' }, mana: { category2: 'mana', name: 'リデンプション', icon: '3107' }, ar: { category2: 'ar', name: '赤バフ', icon: 'https://vignette.wikia.nocookie.net/leagueoflegends/images/e/e7/Red_BramblebackSquare.png/revision/latest/scale-to-width-down/46?cb=20140620025406' }, mr: { category2: 'mr', name: 'ゼファー', icon: '3172' }, hp: { category2: 'hp', name: 'ワーモグアーマー', icon: '3083' }, other: { category2: 'other', name: 'フローズンマレット', icon: '3022' } }, other: { none: { name: 'へら', icon: 'https://news-a.akamaihd.net/public/images/articles/2019/june/tftcompendium/Items/spatula.png' }, ad: { category2: 'ad', name: '妖夢の霊剣', icon: '3388' }, ap: { category2: 'ap', name: 'ユーミ', icon: 'https://vignette.wikia.nocookie.net/leagueoflegends/images/2/2b/You_and_Me%21.png/revision/latest/scale-to-width-down/46?cb=20190426210438' }, as: { category2: 'as', name: 'ルインドキングブレード', icon: '3389' }, mana: { category2: 'mana', name: 'デーモンになるやつ', icon: 'https://vignette.wikia.nocookie.net/leagueoflegends/images/d/de/World_Ender.png/revision/latest/scale-to-width-down/46?cb=20180612213606' }, ar: { category2: 'ar', name: '騎士の誓い', icon: '3109' }, mr: { category2: 'mr', name: 'ルナーンハリケーン', icon: '3085' }, hp: { category2: 'hp', name: 'フローズンマレット', icon: '3022' }, other: { category2: 'other', name: '自然の力', icon: '4401' } } } }
3c9aaa9fc745a204f26b8b233b402c90af993fa9
[ "JavaScript" ]
1
JavaScript
B4129/LOLTFTTool
69673c7ae11fda89f8e17d283fde00e985d253b6
1f65b28b3fabd1ac1d2d232d66f485119d7c9552
refs/heads/master
<repo_name>elath03/SpringFest_assignments<file_sep>/assignment_5/admin.php <?php ob_start(); session_start(); $user=$pass=""; $user_error=$pass_error=""; if($_SERVER["REQUEST_METHOD"]=="POST"){ if(empty($_POST["user"])){ $user_error="*please enter Username"; } else{ $user=($_POST["user"]); } } if($_SERVER["REQUEST_METHOD"]=="POST"){ if(empty($_POST["pass"])){ $pass_error="*please enter password"; } else{ $pass=($_POST["pass"]); $pass_hash=md5($pass); } } if(!empty($user)&&!empty($pass) ){ if($user=='admin'&&$pass=='<PASSWORD>'){ header("Location: adminpage.php"); } else { $message='incorrect data'; echo "<script type='text/javascript'>alert('$message');</script>"; } } ?> <html> <head> <link rel="icon" type="image/png" href="pic.png"> <title> Admin </title> <style> body{ font-family:"Berlin Sans FB"; background-image: url(reg.png); background-size: cover; } form{ color:black; font-family:"Berlin Sans FB"; font-size: 30px; border:black 0px solid; margin-top: 5%; margin-left: 25%; margin-right:25%; padding-left:30px; padding-top: 1px; padding-bottom: 20px; background-color: #7FB3D5 ; border-radius: 10px; } input{ color:black; font-size: 20px; height:45px; background-color:#e8ebed; border:0px black solid; border-radius: 5px; transition:0.5s ease-in-out; padding-left: 5px; } input:focus{ border:1px #e8ebed solid; background-color:white; border-radius: 5px; outline-width: 0px; transition:0.2s ease-in-out; cursor: pointer; } .err{ font-size: 15px; color:red; } #submit{ font-size: 30px; color:white; font-family:"Berlin Sans FB"; padding-left:5px; padding-top:5px; padding-right:5px; padding-bottom:5px; height:50px; width: 150px; cursor:pointer; text-align: center; background-color: #6C3483; letter-spacing: 2px;} #submit:hover{ color: #6C3483; background-color: #e8ebed; letter-spacing: px;} #h,#a{ font-size:45px; text-align: center; letter-spacing: 2px; text-shadow: 2px 2px #D7BDE2; } #p{ margin-left: 40px; } #u{ margin-left: 30px; } #reg,#admin{ text-shadow: none; } #reg:hover,#admin:hover{ color:white; font-size:45px; text-decoration: none; } </style> </head> <BODY> <div id="h"> Do not have an account,connect with us today!<br> <a id="reg" href="register.php">REGISTER</a></div> <form method="POST"> <h4>ADMIN LOGIN</h4> Username:<input id="u" type="text" name="user"> <span class="err"><?php echo $user_error; ?><br><br><br><br></span> Password:<input id="p" type="<PASSWORD>" name="pass"> <span class="err"><?php echo $pass_error; ?><br><br><br><br></span> <input id="submit" type="submit" name="submit" value="Login"> <script type="text/javascript" src="jquery-1.12.4.min.js"></script> </form> <p id="a" > login as a user.. <a id ="admin" href="login.php"> USER</a></p> </body> </html><file_sep>/assignment_3/hide.js var selected_block=0; var block=[]; var i; var k; var a=[]; var b=[]; var c=[]; var container=0; var e=1; $(document).ready(function(){ var count; for(count=0;count<25;count++){ b[0]=Math.floor((Math.random()*9)+1 ); b[1]=Math.floor((Math.random()*9)+1 ); swap_random(); } }); $('#contain div').click(function() { i=$(this).text(); if(selected_block==2){ if(a[0]!=i&&a[1]!=i){ $('#contain div').css("transform","scale(1)"); selected_block=0; } } if(i==a[0]||i==a[1]){ $(this).css("transform","scale(1)"); selected_block--; k=0; if(i==a[0]){ a[0]=0; }; if(i==a[1]){ a[1]=0; }; } else { $(this).css("transform","scale(1.1)"); k= $(this).text(); a[selected_block]=k; var p=$(this).attr('id') c[selected_block]=p; selected_block++; } }); var swap=function(){ container=1; var top1=$("#"+c[0]).css("top"); var left1=$("#"+c[0]).css("left"); var top2=$("#"+c[1]).css("top"); var left2=$("#"+c[1]).css("left"); $("#"+c[0]).animate({ left:left2, top:top2 },500); $("#"+c[1]).animate({ left:left1, top:top1 },500); $("#contain div").css("transform","scale(1)"); a[0]=0; a[1]=0; selected_block=0; c[0]=0; c[1]=0; }; $('#swap').click(function(){ if(selected_block==0){ alert('select blocks');} if(selected_block==2){ swap();} if(selected_block==1){ alert('Select Another Block');} }); var swap_random=function() { var x1=$("#e"+b[0]).text(); var y1=$("#e"+b[1]).text(); var q=$("#e"+b[0]).css("background-color"); var r=$("#e"+b[1]).css("background-color"); $("#e"+b[0]).text(y1); $("#e"+b[1]).css("background-color",q); $("#e"+b[1]).text(x1); $("#e"+b[0]).css("background-color",r); $("#contain div").css("transform","scale(1)"); return;} $('#random').click(function(){ var count; for(count=0;count<25;count++){ b[0]=Math.floor((Math.random()*9)+1 ); b[1]=Math.floor((Math.random()*9)+1 ); swap_random();} }); var check=function(){ var count=0; var i=1; while(i<=9){ if($('#e'+i).text()==1 && $('#e'+i).css('top')=='150px' && $('#e'+i).css('left')=='400px'){count++;} if($('#e'+i).text()==2 && $('#e'+i).css('top')=='150px' && $('#e'+i).css('left')=='570px'){count++;} if($('#e'+i).text()==3 && $('#e'+i).css('top')=='150px' && $('#e'+i).css('left')=='740px'){count++;} if($('#e'+i).text()==4 && $('#e'+i).css('top')=='320px' && $('#e'+i).css('left')=='400px'){count++;} if($('#e'+i).text()==5 && $('#e'+i).css('top')=='320px' && $('#e'+i).css('left')=='570px'){count++;} if($('#e'+i).text()==6 && $('#e'+i).css('top')=='320px' && $('#e'+i).css('left')=='740px'){count++;} if($('#e'+i).text()==7 && $('#e'+i).css('top')=='490px' && $('#e'+i).css('left')=='400px'){count++;} if($('#e'+i).text()==8 && $('#e'+i).css('top')=='490px' && $('#e'+i).css('left')=='570px'){count++;} if($('#e'+i).text()==9 && $('#e'+i).css('top')=='490px' && $('#e'+i).css('left')=='740px'){count++;} i++; } if(count==9){alert('puzzle solved');} else{ alert('puzzle is not solved yet try more'); } }; $('#check').click(function(){ check();} );<file_sep>/assignment_5/welcome.php <?php session_start(); ob_start(); $id=$_SESSION['user']; $roll=$std=$std_error=$roll_error=""; if($_SERVER["REQUEST_METHOD"]=="POST"){ if(empty($_POST["std"])){ $std_error="*please enter student's name"; } else{ $std=($_POST["std"]); } } if($_SERVER["REQUEST_METHOD"]=="POST"){ if(empty($_POST["roll"])){ $roll_error="*please enter roll number"; } else{ $roll=($_POST["roll"]); } } $servername = "localhost"; $username = "u828165350_esha"; $password = "<PASSWORD>"; $dbname = "u828165350_login"; $conn = mysqli_connect($servername, $username, $password, $dbname); if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } if(isset($_SESSION['user'])&&!empty($_SESSION['user'])){ $log="SELECT `Student_Name`,`Student_Roll` FROM esha WHERE `Professor_id`='$id'"; $res=mysqli_query($conn,$log) ; $userRow=mysqli_num_rows($res); if($userRow==0){ $message= "No students are under you"; echo $message; } else{ echo '<div style="font-size:40px;text-align:center" >'."LIST OF STUDENTS ".'</div>'; while($query_row=mysqli_fetch_assoc($res) ) { $student_name=$query_row['Student_Name']; $student_roll=$query_row['Student_Roll']; echo '<div style="font-size:25px;text-align:center;color:PURPLE;border:0px solid black;margin-left:350px;margin-right:350px;padding:5px;margin-top:10px;background-color:#FCDFFF;border-radius:5px;" >'.$student_name." - ".$student_roll.'</div>' ; // "<span style = 'font-color: #ff0000'> Movie List for {$key} 2013 </span>"; } } if(isset($_SESSION['user'])&&!empty($_SESSION['user'])&&!empty($roll)&&!empty($std)){ echo "."; $wel="INSERT INTO esha (Professor_id,Student_Name,Student_Roll) VALUES ( '$id','$std','$roll')"; if (mysqli_query($conn, $wel)) { $messag= "New record created successfully"; echo "<script type='text/javascript'>alert('$messag');</script>"; header("Location: welcome.php");} else { echo "Error: " . $wel . "<br>" . mysqli_error($conn);} } } else{ header("Location: login.php"); } ?> <html> <head> <link rel="icon" type="image/png" href="pic.png"> <title>Welcome</title> <style> body{ font-family:"Berlin Sans FB"; background-image: url(reg.png); background-size: cover; } #logout{ font-size: 35px; background-color: #7FB3D5 ; border-radius: 10px; border:black 0px solid; margin-top: 3%; margin-left: 25%; margin-right:25%; padding-top:5%; padding-bottom: 5%; text-align: center; padding-left: 30px; padding-right: 30px; } #w{ color:blue; } #log{ font-size: 30px; text-decoration: none; border:1px black solid; border-radius: 5px; padding:5px; background-color: #e8ebed; text-align:center; margin-left:600px; } #log:hover{ color: #e8ebed; background-color:#6C3483; } form{ color:black; font-family:"Berlin Sans FB"; font-size: 25px; border:black 0px solid; margin-top: 3%; margin-left: 25%; margin-right:25%; padding-left:30px; padding-top: 20px; padding-bottom: 20px; background-color: #7FB3D5 ; border-radius: 10px; } input{ color:black; font-size: 20px; height:35px; background-color:#e8ebed; border:0px black solid; border-radius: 5px; transition:0.5s ease-in-out; padding-left: 5px; } input:focus{ border:1px #e8ebed solid; background-color:white; border-radius: 5px; outline-width: 0px; transition:0.2s ease-in-out; cursor: pointer; } #del{ font-size:30px; text-align:center; } #hi{ font-size: 30px; color:blue; text-align: center;} #remove:hover{ font-size:40px; text-decoration: none; color:white; } #remove{ font-size:40px; } .error{ font-size:15px; color:red; } #s{ margin-left: 20px; } #r{ margin-left: 45px; } #submit{ font-size: 30px; color:white; font-family:"Berlin Sans FB"; padding-left:5px; padding-top:5px; padding-right:5px; padding-bottom:5px; height:50px; width: 150px; cursor:pointer; text-align: center; background-color: #6C3483; letter-spacing: 1px;} #submit:hover{ color: #6C3483; background-color: #e8ebed; letter-spacing: 1px; . } </style> </head> <body> <div id="hi"> </div> <form action="welcome.php" method="POST"> <?php if(isset($_SESSION['user'])&&!empty($_SESSION['user']) ){ echo "Hello ".$_SESSION['user']." you are logged in! "; } ?><br><br> Student Name:<input id="s" type="text" name="std"> <span class="error"> <?php echo $std_error;?></span><br><br> Student Roll:<input id="r" type="text" name="roll"> <span class="error"> <?php echo $roll_error;?></span><br><br> <input type="submit" value="Submit" id="submit" ><br><br> </form> <div id="del">Want to remove a student from the list? <a href="delete.php" id="remove" > remove </a></div><br><br> <a id="log" href="logout.php">logout</a><br><br> </body> </html><file_sep>/assignment_5/delete.php <?php session_start(); $roll=$std=$std_error=$roll_error=""; if($_SERVER["REQUEST_METHOD"]=="POST"){ if(empty($_POST["std"])){ $std_error="*please enter student's name"; } else{ $std=($_POST["std"]); } } if($_SERVER["REQUEST_METHOD"]=="POST"){ if(empty($_POST["roll"])){ $roll_error="*please enter roll number"; } else{ $roll=($_POST["roll"]); } } $servername = "localhost"; $username = "root"; $password = ""; $dbname = "register"; $conn = mysqli_connect($servername, $username, $password, $dbname); if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } if(isset($_SESSION['user'])&&!empty($_SESSION['user'])){ if(!empty($roll)&&!empty($std)){ $log="DELETE FROM esha WHERE `Student_Name`='$std' AND `Student_Roll`='$roll'"; if (mysqli_query($conn, $log)) { $message="Student has been removed from your list if he/she was present"; echo "<script type='text/javascript'>alert('$message');</script>"; } else { echo "Error deleting record: " .mysqli_error($conn); } }} else{ header("Location: login.php"); } ?> <html> <head> <link rel="icon" type="image/png" href="pic.png"> <title>REMOVE</title> <style> body{ font-family:"Berlin Sans FB"; background-image: url(reg.png); background-size: cover; } form{ color:black; font-family:"Berlin Sans FB"; font-size: 25px; border:black 0px solid; margin-top: 3%; margin-left: 25%; margin-right:25%; height:250px; padding-left:30px; padding-top: 40px; padding-bottom: 20px; background-color: #7FB3D5 ; border-radius: 10px; } input{ color:black; font-size: 20px; height:35px; background-color:#e8ebed; border:0px black solid; border-radius: 5px; transition:0.5s ease-in-out; padding-left: 5px; } input:focus{ border:1px #e8ebed solid; background-color:white; border-radius: 5px; outline-width: 0px; transition:0.2s ease-in-out; cursor: pointer; } #h{ font-size:40px; text-align: center; font-weight: :normal; letter-spacing: 2px; text-shadow: 2px 2px #D7BDE2; } #s{ margin-left: 20px; } #r{ margin-left: 45px; } #w{ color:blue; } #log{ font-size: 40px; text-decoration: none; border:1px black solid; border-radius: 5px; padding:5px; background-color: #e8ebed; margin-top: 50px; margin-left: 600px; } #log:hover{ color: #e8ebed; background-color:#6C3483; } #submit{ font-size: 30px; color:white; font-family:"Berlin Sans FB"; padding-left:5px; padding-top:5px; padding-right:5px; padding-bottom:5px; height:50px; width: 150px; cursor:pointer; text-align: center; background-color: #6C3483; letter-spacing: 1px;} #submit:hover{ color: #6C3483; background-color: #e8ebed; letter-spacing: 1px; } #ho{ font-size: 30px; } .error{ font-size:15px; color:red; } #hom:hover{ font-size:40px; text-decoration: none; color:white; } #hom{ font-size:40px;} </style> </head> <div id="h">Want to remove a student?<br>Fill in his/her details!</div> <form method="POST"> Student Name:<input id="s" type="text" name="std"> <span class="error"> <?php echo $std_error;?></span><br><br> Student Roll:<input id="r" type="text" name="roll"> <span class="error"> <?php echo $roll_error;?></span><br><br> <input type="submit" value="Remove" id="submit" ><br><br> <div id="ho" >Do you want to go back to home page? <a href="welcome.php" id="hom" > home </a></div> </form> <a id="log" href="logout.php">Logout</a> </body> </html><file_sep>/assignment_5/admin_login.php <?php session_start(); ob_start(); $id=$_SESSION['user']; $roll=$std=$std_error=$roll_error=$stud_error=$rol_error=""; if($_SERVER["REQUEST_METHOD"]=="POST"){ if(empty($_POST["std"])){ $std_error="*please enter student's name"; } else{ $std=($_POST["std"]); } } if($_SERVER["REQUEST_METHOD"]=="POST"){ if(empty($_POST["roll"])){ $roll_error="*please enter roll number"; } else{ $roll=($_POST["roll"]); } } if($_SERVER["REQUEST_METHOD"]=="POST"){ if(empty($_POST["stud"])){ $stud_error="*please enter student's name"; } else{ $stud=($_POST["stud"]); } } if($_SERVER["REQUEST_METHOD"]=="POST"){ if(empty($_POST["rol"])){ $rol_error="*please enter roll number"; } else{ $rol=($_POST["rol"]); } } $servername = "localhost"; $username = "u828165350_esha"; $password = "<PASSWORD>"; $dbname = "u828165350_login"; $conn = mysqli_connect($servername, $username, $password, $dbname); if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } if(isset($_SESSION['user'])&&!empty($_SESSION['user'])){ $log="SELECT `Student_Name`,`Student_Roll` FROM esha WHERE `Professor_id`='$id'"; $res=mysqli_query($conn,$log) ; $userRow=mysqli_num_rows($res); if($userRow==0){ $mesage= "No students are under you"; echo "<script type='text/javascript'>alert('$mesage');</script>"; } else{ echo '<div style="font-size:30px;text-align:left" >'.$id.'</div>'; echo '<div style="font-size:40px;text-align:center" >'."LIST OF STUDENTS ".'</div>'; while($query_row=mysqli_fetch_assoc($res) ) { $student_name=$query_row['Student_Name']; $student_roll=$query_row['Student_Roll']; echo '<div style="font-size:25px;text-align:center;color:PURPLE;border:0px solid black;margin-left:350px;margin-right:350px;padding:5px;margin-top:10px;background-color:#FCDFFF;border-radius:5px;" >'.$student_name." - ".$student_roll.'</div>' ; } } if(isset($_SESSION['user'])&&!empty($_SESSION['user'])&&!empty($roll)&&!empty($std)){ echo "."; $wel="INSERT INTO esha (Professor_id,Student_Name,Student_Roll) VALUES ( '$id','$std','$roll')"; if (mysqli_query($conn, $wel)) { $messag= "New record created successfully"; echo "<script type='text/javascript'>alert('$messag');</script>"; header("Location: admin_login.php");} else { echo "Error: " . $wel . "<br>" . mysqli_error($conn);} } if(isset($_SESSION['user'])&&!empty($_SESSION['user'])&&!empty($rol)&&!empty($stud)){ $log="DELETE FROM esha WHERE `Student_Name`='$stud' AND `Student_Roll`='$rol'"; if (mysqli_query($conn, $log)) { $message="Student has been removed from your list if he/she was present"; echo "<script type='text/javascript'>alert('$message');</script>"; header("Location: admin_login.php"); } else { echo "Error deleting record: " .mysqli_error($conn); } }} else{ header("Location: login.php"); } ?> <html> <head> <link rel="icon" type="image/png" href="pic.png"> <title>Admin Login</title> <style> body{ font-family:"Berlin Sans FB"; background-image: url(reg.png); background-size: cover; } #logout{ font-size: 35px; background-color: #7FB3D5 ; border-radius: 10px; border:black 0px solid; margin-top: 3%; margin-left: 25%; margin-right:25%; padding-top:5%; padding-bottom: 5%; text-align: center; padding-left: 30px; padding-right: 30px; } #w{ color:blue; } #log{ font-size: 30px; text-decoration: none; border:1px black solid; border-radius: 5px; padding:5px; background-color: #e8ebed; text-align:center; margin-left:600px; } #log:hover{ color: #e8ebed; background-color:#6C3483; } form{ color:black; font-family:"Berlin Sans FB"; font-size: 20px; border:black 0px solid; margin-top: 3%; margin-left: 15%; margin-right:15%; padding-left:20px; padding-top: 20px; padding-bottom: 20px; background-color: #7FB3D5 ; border-radius: 10px; } input{ color:black; font-size: 20px; height:35px; background-color:#e8ebed; border:0px black solid; border-radius: 5px; transition:0.5s ease-in-out; padding-left: 5px; } input:focus{ border:1px #e8ebed solid; background-color:white; border-radius: 5px; outline-width: 0px; transition:0.2s ease-in-out; cursor: pointer; } #del{ font-size:30px; text-align:center; } #hi{ font-size: 30px; color:blue; text-align: center;} #remove:hover{ font-size:40px; text-decoration: none; color:white; } #remove{ font-size:40px; } .error{ font-size:15px; color:red; } #submit{ font-size: 30px; color:white; font-family:"Berlin Sans FB"; padding-left:5px; padding-top:5px; padding-right:5px; padding-bottom:5px; height:50px; width: 150px; cursor:pointer; text-align: center; background-color: #6C3483; letter-spacing: 1px;} #submit:hover{ color: #6C3483; background-color: #e8ebed; letter-spacing: 1px; } </style> </head> <body> <div id="hi"> </div> <form action="admin_login.php" method="POST"> Add a student.. <br> Student Name:<input id="s" type="text" name="std"> <span class="error"> <?php echo $std_error;?></span> Student Roll:<input id="r" type="text" name="roll"> <span class="error"> <?php echo $roll_error;?></span> <input type="submit" value="Submit" id="submit" ><br><br> </form> <form method="POST"> Remove a student..<br> Student Name:<input id="s" type="text" name="stud"> Student Roll:<input id="r" type="text" name="rol"> <input type="submit" value="Add" id="submit" ><br><br> </form> <a id="log" href="logout.php">logout</a><br><br> </body> </html><file_sep>/assignment_5/logout.php <?php $servername = "localhost"; $username = "u828165350_esha"; $password = "<PASSWORD>"; $dbname = "u828165350_login"; $conn = mysqli_connect($servername, $username, $password, $dbname); if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } session_start(); $_SESSION = array(); session_destroy(); header("location:login.php"); ?><file_sep>/README.md Spring Fest Summer training Assignments<file_sep>/assignment_5/login.php <?php ob_start(); session_start(); $user=$pass=""; $user_error=$pass_error=""; if($_SERVER["REQUEST_METHOD"]=="POST"){ if(empty($_POST["user"])){ $user_error="*please enter Username"; } else{ $user=($_POST["user"]); } } if($_SERVER["REQUEST_METHOD"]=="POST"){ if(empty($_POST["pass"])){ $pass_error="*please enter password"; } else{ $pass=($_POST["pass"]); $pass_hash=md5($pass); } } if(!empty($user)&&!empty($pass) ){ $servername = "localhost"; $username = "u828165350_esha"; $password = "<PASSWORD>"; $dbname = "u828165350_login"; $conn = mysqli_connect($servername, $username, $password, $dbname); if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } else{ $log="SELECT `Username`,`Password` FROM site WHERE `Username`='$user'AND `Password`='$<PASSWORD>'"; $res=mysqli_query($conn,$log) ; $userRow=mysqli_num_rows($res); if($userRow==0){ $message= "This Username and Password does not exist"; echo "<script type='text/javascript'>alert('$message');</script>"; } else{ $row=mysqli_fetch_array($res); $_SESSION['user'] = $row['Username']; header("Location: welcome.php"); } } } ?> <html> <head> <link rel="icon" type="image/png" href="pic.png"> <title> LOGIN </title> <style> body{ font-family:"Berlin Sans FB"; background-image: url(reg.png); background-size: cover; } form{ color:black; font-family:"Berlin Sans FB"; font-size: 30px; border:black 0px solid; margin-top: 5%; margin-left: 25%; margin-right:25%; padding-left:30px; padding-top: 3px; padding-bottom: 20px; background-color: #7FB3D5 ; border-radius: 10px; } input{ color:black; font-size: 20px; height:45px; background-color:#e8ebed; border:0px black solid; border-radius: 5px; transition:0.5s ease-in-out; padding-left: 5px; } input:focus{ border:1px #e8ebed solid; background-color:white; border-radius: 5px; outline-width: 0px; transition:0.2s ease-in-out; cursor: pointer; } .err{ font-size: 15px; color:red; } #submit{ font-size: 30px; color:white; font-family:"Berlin Sans FB"; padding-left:5px; padding-top:5px; padding-right:5px; padding-bottom:5px; height:50px; width: 150px; cursor:pointer; text-align: center; background-color: #6C3483; letter-spacing: 2px;} #submit:hover{ color: #6C3483; background-color: #e8ebed; letter-spacing: px;} #h,#a{ font-size:45px; text-align: center; letter-spacing: 2px; text-shadow: 2px 2px #D7BDE2; } #p{ margin-left: 40px; } #u{ margin-left: 30px; } #reg,#admin{ text-shadow: none; } #reg:hover,#admin:hover{ color:white; font-size:45px; text-decoration: none; } </style> </head> <BODY> <div id="h"> Do not have an account,connect with us today!<br> <a id="reg" href="register.php">REGISTER</a></div> <form method="POST"> <h4> USER LOGIN</h4> Username:<input id="u" type="text" name="user"> <span class="err"><?php echo $user_error; ?><br><br><br><br></span> Password:<input id="p" type="<PASSWORD>" name="pass"> <span class="err"><?php echo $pass_error; ?><br><br><br><br></span> <input id="submit" type="submit" name="submit" value="Login"> <script type="text/javascript" src="jquery-1.12.4.min.js"></script> </form> <p id="a" > login as an admin.. <a id ="admin" href="admin.php"> ADMIN</a></p> </body> </html><file_sep>/assignment_4/welcome.php <?php ob_start(); session_start(); $servername = "localhost"; $username = "u828165350_esha"; $password = "<PASSWORD>"; $dbname = "u828165350_login"; $conn = mysqli_connect($servername, $username, $password, $dbname); if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } if(isset($_SESSION['user'])&&!empty($_SESSION['user']) ){ echo "."; } else{ header("Location: login.php"); } ?> <html> <head> <link rel="icon" type="image/png" href="pic.png"> <title>Welcome</title> <style> body{ font-family:"Berlin Sans FB"; background-image: url(reg.png); background-size: cover; } #logout{ font-size: 35px; background-color: #7FB3D5 ; border-radius: 10px; border:black 0px solid; margin-top: 3%; margin-left: 25%; margin-right:25%; padding-top:5%; padding-bottom: 5%; text-align: center; padding-left: 30px; padding-right: 30px; } #w{ color:blue; } #log{ font-size: 40px; text-decoration: none; border:1px black solid; border-radius: 5px; padding:5px; background-color: #e8ebed; } #log:hover{ color: #e8ebed; background-color:#6C3483; } </style> </head> <body> <div id="logout"> <?php if(isset($_SESSION['user'])&&!empty($_SESSION['user']) ){ echo "welcome ".$_SESSION['user']; } ?><br><br> You have successfully logged in to our website!<br><br><br> <a id="log" href="logout.php">logout</a> </div> </body> </html> <file_sep>/assignment_4/register.php <?php $user_name=$firstname=$lastname=$email=$pass_word=$re_enter_password=""; $username_error=$lastname_error=$email_error=$password_error=$re_enter_password_error=$firstname_error=""; if($_SERVER["REQUEST_METHOD"]=="POST"){ if(empty($_POST["user_name"])){ $username_error="*please enter Username"; } else{ $user_name=($_POST["user_name"]); } } if($_SERVER["REQUEST_METHOD"]=="POST"){ if(empty($_POST["firstname"])){ $firstname_error="*please enter Firstname"; } else{ $firstname=($_POST["firstname"]); } } if($_SERVER["REQUEST_METHOD"]=="POST"){ if(empty($_POST["pass_word"])){ $password_error="*please enter Password"; } else{ $pass_word=($_POST["pass_word"]); } } if($_SERVER["REQUEST_METHOD"]=="POST"){ if(empty($_POST["re_enter_password"])){ $re_enter_password_error="*please re enter password"; } else{ $re_enter_password=($_POST["re_enter_password"]); } } if($_SERVER["REQUEST_METHOD"]=="POST"){ if(empty($_POST["lastname"])){ $lastname_error="*please enter Lastname"; } else{ $lastname=($_POST["lastname"]); } } if($_SERVER["REQUEST_METHOD"]=="POST"){ if(empty($_POST["email"])){ $email_error="*please enter mail id"; } else{ $email=($_POST["email"]); if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $email_error = "*Invalid email format"; $email=NULL; } } } if(!empty($user_name)&&!empty($pass_word)&&!empty($firstname)&&!empty($lastname)&&!empty($email)&&!empty($re_enter_password)){ if($pass_word!=$re_enter_password){ $message="passwords do not match,please try again!"; echo "<script type='text/javascript'>alert('$message');</script>"; } else{ $servername = "localhost"; $username = "u828165350_esha"; $password = "<PASSWORD>"; $dbname = "u828165350_login"; $conn = mysqli_connect($servername, $username, $password,$dbname); if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } else{ $log="SELECT `Username` FROM site WHERE `Username`='$user_name'"; $res=mysqli_query($conn,$log) ; $userRow=mysqli_num_rows($res); if($userRow==1){ $message="this username already exist"; echo "<script type='text/javascript'>alert('$message');</script>"; } else{ $pass_hash=$re_enter_password=md5($pass_<PASSWORD>); $sql = "INSERT INTO site (Username,First_Name,Last_Name,Password,Re_Enter_Password,E_mail) VALUES ('$user_name','$firstname','$lastname','$pass_hash','$pass_hash','$email' )"; if (mysqli_query($conn, $sql)) { $messag= "New record created successfully"; echo "<script type='text/javascript'>alert('$messag');</script>";} else { echo "Error: " . $sql . "<br>" . mysqli_error($conn);} mysqli_close($conn); $user_name=$firstname=$lastname=$email=$pass_word=$re_enter_password=""; $user_name_error=$lastname_error=$email_error=$password_error=$re_enter_password_error=$firstname_error="";} } } } ?> <html> <head> <link rel="icon" type="image/png" href="pic.png"> <title> Register </title> <style> body{ font-family:"Berlin Sans FB"; background-image: url(reg.png); background-size: cover; } form{ color:black; font-family:"Berlin Sans FB"; font-size: 25px; border:black 0px solid; margin-top: 3%; margin-left: 25%; margin-right:25%; padding-left:30px; padding-top: 20px; padding-bottom: 20px; background-color: #7FB3D5 ; border-radius: 10px; } input{ color:black; font-size: 20px; height:35px; background-color:#e8ebed; border:0px black solid; border-radius: 5px; transition:0.5s ease-in-out; padding-left: 5px; } input:focus{ border:1px #e8ebed solid; background-color:white; border-radius: 5px; outline-width: 0px; transition:0.2s ease-in-out; cursor: pointer; } .error{ font-size:15px; color:red; } #h{ font-size:50px; text-align: center; font-weight: :normal; letter-spacing: 2px; text-shadow: 2px 2px #D7BDE2; } #user{ margin-left:87px; } #f{ margin-left:72px; } #p{ margin-left: 92px; } #e{ margin-left: 122px; } #submit{ font-size: 30px; color:white; font-family:"Berlin Sans FB"; padding-left:5px; padding-top:5px; padding-right:5px; padding-bottom:5px; height:50px; width: 150px; cursor:pointer; text-align: center; background-color: #6C3483; letter-spacing: 1px;} #submit:hover{ color: #6C3483; background-color: #e8ebed; letter-spacing: 1px; } #login{ font-size: 30px; text-align: center; } #l:hover{ font-size:40px; text-decoration: none; color:white; } #l{ font-size:40px; } </style> </head> <body background-image=url("reg.png")> <div id="h">GET STARTED TODAY! CREATE A FREE ACCOUNT</div> <form action="register.php" method="POST"> Username: <input id="user" type="text" name="user_name" value="<?php echo $user_name; ?>"> <span class="error"> <?php echo $username_error;?></span> <br><br> First_Name: <input id="f" type="text" name="firstname" value="<?php echo $firstname; ?>"> <span class="error"> <?php echo $firstname_error;?></span> <br><br> Last_Name: <input id="f" type="text" name="lastname" value="<?php echo $lastname; ?>"> <span class="error"> <?php echo $lastname_error;?></span> <br><br> Password: <input id="p" type="<PASSWORD>" name="pass_<PASSWORD>"> <span class="error"> <?php echo $password_error;?></span> <br><br> ReEnter_Password: <input id="r" type="<PASSWORD>" name="re_enter_password"> <span class="error"> <?php echo $re_enter_password_error;?></span> <br><br> E_mail: <input id="e" type="text" name="email" value="<?php echo $email; ?>"> <span class="error"> <?php echo $email_error;?></span> <br><br> <input id="submit" type="submit" name="submit" value="Register"> </form> <div id="login">Already have an account? <a id="l" href="login.php">LOGIN</a></div> <script type="text/javascript" src="jquery-1.12.4.min.js"></script> </body> </html> <file_sep>/assignment_5/adminpage.php <?php ob_start(); session_start(); $user=""; $user_error=""; if($_SERVER["REQUEST_METHOD"]=="POST"){ if(empty($_POST["user"])){ $user_error="*please enter Username"; } else{ $user=($_POST["user"]); } } $servername = "localhost"; $username = "u828165350_esha"; $password = "<PASSWORD>"; $dbname = "u828165350_login"; $conn = mysqli_connect($servername, $username, $password, $dbname); if (!$conn) { die("Connection failed: " . mysqli_connect_error());} $log="SELECT `First_Name`,`Last_Name`,`Username` FROM site"; $res=mysqli_query($conn,$log) ; $userRow=mysqli_num_rows($res); if($userRow==0){ $message= "no professor has yet created an account"; echo $message; } else{ echo '<div style="font-size:40px;text-align:center" >'."LIST OF PROFESSORS ".'</div>'; while($query_row=mysqli_fetch_assoc($res) ) { $first_name=$query_row['First_Name']; $last_roll=$query_row['Last_Name']; $id= $query_row['Username']; // $id= $_SESSION['user']; echo '<div style="font-size:25px;text-align:center;color:PURPLE;border:0px solid black;margin-left:300px;margin-right:300px;padding:5px;margin-top:10px;background-color:#FCDFFF;border-radius:5px;" >'.$first_name." ".$last_roll.'<br>'.'('.$id.')'.'</div>'; }} if(!empty($user)){ $log="SELECT `Username`,`Password` FROM site WHERE `Username`='$user'"; $res=mysqli_query($conn,$log) ; $userRow=mysqli_num_rows($res); if($userRow==0){ $message= "This Username does not exist"; echo "<script type='text/javascript'>alert('$message');</script>"; } else{ $row=mysqli_fetch_array($res); $_SESSION['user'] = $row['Username']; header("Location: admin_login.php"); }} ?> <html> <head> <link rel="icon" type="image/png" href="pic.png"> <title> ADMIN PAGE </title> <style> body{ font-family:"Berlin Sans FB"; background-image: url(reg.png); background-size: cover; } form{ color:black; font-family:"Berlin Sans FB"; font-size: 25px; border:black 0px solid; margin-top: 3%; margin-left: 25%; margin-right:25%; height:120px; padding-left:30px; padding-top: 40px; padding-bottom: 20px; background-color: #7FB3D5 ; border-radius: 10px; } input{ color:black; font-size: 20px; height:35px; background-color:#e8ebed; border:0px black solid; border-radius: 5px; transition:0.5s ease-in-out; padding-left: 5px; } input:focus{ border:1px #e8ebed solid; background-color:white; border-radius: 5px; outline-width: 0px; transition:0.2s ease-in-out; cursor: pointer; } .err{ font-size: 15px; color:red; } #submit{ font-size: 25px; color:white; font-family:"Berlin Sans FB"; padding-left:2px; padding-top:2px; padding-right:2px; padding-bottom:2px; height:40px; width: 120px; cursor:pointer; text-align: center; background-color: #6C3483; letter-spacing: 1px;} #submit:hover{ color: #6C3483; background-color: #e8ebed; letter-spacing: px;} #log{ font-size: 30px; text-decoration: none; border:1px black solid; border-radius: 5px; padding:5px; background-color: #e8ebed; text-align:center; margin-left:600px; } #log:hover{ color: #e8ebed; background-color:#6C3483; } </style> </head> <body> <script type="text/javascript" src="jquery-1.12.4.min.js"></script> <form method="POST"> Please enter the username of the professor<br><br> Username:<input id="u" type="text" name="user"> <input id="submit" type="submit" name="submit" value="Login"><br><br> <span class="err"><?php echo $user_error; ?></span> <script type="text/javascript" src="jquery-1.12.4.min.js"></script> </form> <a id="log" href="logout.php">logout</a><br><br> </body></html>
b940d748e5d1be6154e20516f024bd4c13697b03
[ "JavaScript", "Markdown", "PHP" ]
11
PHP
elath03/SpringFest_assignments
462f8f9ecaac8cb14f7299c566a90153635db812
0492214cf5848b30f773a314933f408ac7ec637d
refs/heads/master
<file_sep>package edu.westga.kenjiokamotoinvestmentcalculator.model; import java.text.DecimalFormat; public class InvestmentCalculator { public static String getFutureValue(double payment, double rate, int years) { if (years < 0) { throw new IllegalArgumentException("Years must not be negative"); } double endValue; if (rate == 0) { endValue = years * payment; } else { double numerator = Math.pow( (1 + rate), years ) - 1; endValue = payment * numerator / rate; } return "$" + new DecimalFormat("#,###.##").format(endValue); } }
889085c376c1077bb6e88ed9b28d29a5a06d0770
[ "Java" ]
1
Java
kokamot1/KenjiOkamotoInvestmentCalculator
70a8277ef94dffa6d2af0b15d812a560cbdcc4ba
20f2f73cfc69558faf68c6af92e0f2258de2da0e
refs/heads/master
<file_sep>const greeting: string = 'heelo'; const dotenv = require('dotenv'); dotenv.config(); const numbers: number[] = [1,2,3]; import express, {Application, Request, Response, NextFunction} from 'express'; import bodyParser from 'body-parser'; const MongoClient = require('mongodb').MongoClient; const port = process.env.PORT; const twit = require('twit'); const users = []; // const twitter = new twit({ // consumer_key: process.env.TWITTER_CONSUMER_KEY, // consumer_secret: process.env.TWITTER_CONSUMER_SECRET, // access_token: process.env.TWITTER_ACCESS_TOKEN_KEY, // access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET // }) console.log(process.env.TWITTER_CONSUMER_KEY); console.log(process.env.TWITTER_ACCESS_TOKEN_SECRET); const cors = require('cors'); const app: Application= express(); app.use(bodyParser.json()); app.use(cors()); app.use(express.urlencoded({extended: false})); const tweets: string[] = ['tweet1', 'MAMAMAMA', 'asdasdasdasd']; app.get('/tweet', (req: Request, res: Response) => { res.send(tweets); }); app.listen(port, () => console.log(`Server started on PORT ${port}`));
e8b7c52a5eb400cfbe20afa14bc6c6153177c947
[ "TypeScript" ]
1
TypeScript
trovoltino/comedy-backend
d8ddd7c1db6063cf8c525bc798e17cbd7af7f7cf
cb44e8dcc51a81f2e21aa758fd450737917770ce
refs/heads/main
<file_sep>const baseURL = 'http://localhost:3000' const mobileHost = 'https://jun3290.cn1.utools.club' export { baseURL, mobileHost }<file_sep>import { mobileHost } from './config' // 发送Ajax请求 export default (options) => { return new Promise((resolve, rejects) => { wx.request({ url: mobileHost + options.url, data: options.data || {}, method: options.method || 'GET', header: { cookie: wx.getStorageSync('cookies') ? wx.getStorageSync('cookies').find(item => item.indexOf('MUSIC_U') !== -1) : '' }, success: (res) => { if (options.data.isLogin) { //此为登录请求 // 将用户的cookie存入本地 wx.setStorage({ data: res.cookies, key: 'cookies', }) } resolve(res.data) }, fail: (err) => { rejects(err) } }) }) }
88c82aeafdf71472d3673524b2085b8f52d1be8c
[ "JavaScript" ]
2
JavaScript
JUN-1999/WY-Music
3322b324cdf42f14048fcc55290d28ea420e87e7
d1c4fdc283332a7ab9375bb5aa8caf0ae84a286b
refs/heads/master
<file_sep>package jp.techacademy.yuka.satou.originalapp; import java.io.Serializable; import java.util.Date; import io.realm.RealmObject; import io.realm.annotations.PrimaryKey; public class Report extends RealmObject implements Serializable { private String start; //出勤時刻 private String end; //退勤時刻 private Date date; //日時 // id をプライマリーキーとして設定 @PrimaryKey private int id; public String getStart() { return start; } public void setStart(String start) { this.start = start; } public String getEnd() { return end; } public void setEnd(String end) { this.end = end; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public int getId() { return id; } public void setId(int id) { this.id = id; } } <file_sep>package jp.techacademy.yuka.satou.originalapp; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class SettingActivity extends AppCompatActivity implements View.OnClickListener { EditText mEditText; private final String mailaddress = "mailaddress"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_setting); setTitle("設定"); Button changeButton = (Button) findViewById(R.id.changeButton); changeButton.setOnClickListener(this); mEditText = (EditText) findViewById(R.id.editText); SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); String mail = sp.getString(mailaddress, ""); mEditText.setText(mail); } @Override public void onClick(View v) { String mail = mEditText.getText().toString(); SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); SharedPreferences.Editor editor = sp.edit(); editor.putString(mailaddress, mail); editor.commit(); finish(); } }
4a4b3546046eaeec820f27d8322e35fb0d2ea96b
[ "Java" ]
2
Java
yuka1228/OriginalApp
832065924fc3adc10d4f13391f889fbf9b4fd478
64c1d5b930de62ae002d0e21635eefe2f59d345f
refs/heads/master
<repo_name>icql/icql-java<file_sep>/icql-java-datastructure/src/main/java/work/icql/java/datastructure/list/stack/LinkedStack.java package work.icql.java.datastructure.list.stack; import work.icql.java.datastructure.list.List; import work.icql.java.datastructure.list.Stack; import work.icql.java.datastructure.list.linked.DoubleLinkedList; public class LinkedStack<E> implements Stack<E> { private List<E> linkedList = new DoubleLinkedList<>(); @Override public void push(E e) { linkedList.add(e); } @Override public E pop() { int lastIndex = linkedList.size() - 1; E last = linkedList.get(lastIndex); linkedList.remove(last); return last; } } <file_sep>/icql-java-designpattern/src/main/java/work/icql/java/designpattern/behavioral/template/AbstractClass.java package work.icql.java.designpattern.behavioral.template; public abstract class AbstractClass { public final void templateMethod() { //... method1(); //... method2(); //... } protected abstract void method1(); protected abstract void method2(); } <file_sep>/icql-java-algorithm/src/main/java/work/icql/java/algorithm/链表/链表_0155_最小栈.java package work.icql.java.algorithm.链表; import java.util.Stack; public class 链表_0155_最小栈 { /** * 辅助栈的作用:每次push都在辅助栈push一个当前栈中的最小值 */ static class MinStack1 { private Stack<Integer> stack; private Stack<Integer> minStack; public MinStack1() { stack = new Stack<>(); minStack = new Stack<>(); } public void push(int val) { if (stack.size() == 0) { stack.push(val); minStack.push(val); } else { Integer min = minStack.peek(); if (val < min) { minStack.push(val); } else { minStack.push(min); } stack.push(val); } } public void pop() { if (stack.size() == 0) { return; } stack.pop(); minStack.pop(); } public int top() { return stack.peek(); } public int getMin() { return minStack.peek(); } } static class MinStack2 { private Stack<Integer> stack; private int min; public MinStack2() { stack = new Stack<>(); } public void push(int val) { if (stack.isEmpty()) { min = val; } else { int diff = val - min; stack.push(diff); if (val < min) { min = val; } } } public void pop() { if (stack.isEmpty()) { return; } stack.pop(); if (stack.isEmpty()) { return; } int top = top(); if (top < min) { min = top; } } public int top() { Integer diff = stack.peek(); return diff + min; } public int getMin() { return min; } } public static void main(String[] args) { work.icql.java.algorithm.链表.MinStack minStack = new work.icql.java.algorithm.链表.MinStack(); System.out.println(); } } <file_sep>/icql-java-algorithm/src/main/java/work/icql/java/algorithm/链表/LRUCache.java package work.icql.java.algorithm.链表; import java.util.LinkedHashMap; import java.util.Map; public class LRUCache { private LRU<Integer, Integer> lru; public LRUCache(int capacity) { lru = new LRU<>(capacity); } public int get(int key) { Integer result = lru.get(key); if (result == null) { return -1; } lru.put(key, lru.remove(key)); return result; } public void put(int key, int value) { Integer result = lru.get(key); if (result == null) { lru.put(key, value); return; } lru.remove(key); lru.put(key, value); } private static class LRU<K, V> extends LinkedHashMap<K, V> { private int capacity; public LRU(int capacity) { super(capacity); this.capacity = capacity; } @Override protected boolean removeEldestEntry(Map.Entry<K, V> eldest) { return super.size() > capacity; } } public static void main(String[] args) { LRUCache obj = new LRUCache(2); obj.put(2, 1); obj.put(1, 1); obj.put(2, 3); obj.put(4, 1); obj.get(1); obj.get(2); System.out.println(obj); } } <file_sep>/icql-java-designpattern/src/main/java/work/icql/java/designpattern/behavioral/state/impl_1/SuperMarioState.java package work.icql.java.designpattern.behavioral.state.impl_1; public class SuperMarioState implements IMarioState { private MarioStateMachineContext stateMachine; public SuperMarioState(MarioStateMachineContext stateMachine) { this.stateMachine = stateMachine; } @Override public void obtainMushRoom() { } @Override public void obtainFireFlower() { } @Override public void meetMonster() { } } <file_sep>/icql-java-algorithm/src/main/java/work/icql/java/algorithm/搜索/OrderedSearch.java package work.icql.java.algorithm.搜索; /** * @author icql * @version 1.0 * @date 2019/1/21 9:18 * @intitle 有序表查找算法 * @Description OrderedSearch */ public class OrderedSearch { /** * 二分查找 * * @param arr * @param num * @return */ public static int binarySearch(int[] arr, int num) { int low = 0; int high = arr.length - 1; while (low <= high) { int mid = (high + low) / 2; if (arr[mid] < num) { low = mid + 1; } else if (arr[mid] > num) { high = mid - 1; } else return mid; } return -1; } /** * 插值查找 * 在二分查找的基础上,改进mid计算公式 * 二分查找 mid = (high + low) / 2 = low + 1/2 *(high - low); * 改进 1/2 系数 为 (key - datastructureold[low]) / (datastructureold[high] - datastructureold[low]) **/ public static int InsertValueSearch(int[] arr, int num) { int low = 0; int high = arr.length - 1; while (low <= high) { int mid = Math.round(low + ((num - arr[low]) / (arr[high] - arr[low])) * (high - low)); if (arr[mid] < num) { low = mid + 1; } else if (arr[mid] > num) { high = mid - 1; } else return mid; } return -1; } //斐波那契查找 } <file_sep>/icql-java-designpattern/src/main/java/work/icql/java/designpattern/creational/factory/abstractfactory/object/ObjectC1.java package work.icql.java.designpattern.creational.factory.abstractfactory.object; import work.icql.java.designpattern.creational.factory.abstractfactory.IObjectC; public class ObjectC1 implements IObjectC { } <file_sep>/icql-java-designpattern/src/main/java/work/icql/java/designpattern/behavioral/chain/linked/HandlerChain.java package work.icql.java.designpattern.behavioral.chain.linked; public class HandlerChain { private Handler head = null; private Handler tail = null; public void addHandler(Handler handler) { handler.setSuccessor(null); if (head == null) { head = handler; tail = handler; return; } tail.setSuccessor(handler); tail = handler; } public void handle(Object o) { if (head != null) { head.handle(o); } } }<file_sep>/icql-java-datastructure/src/main/java/work/icql/java/datastructure/list/Queue.java package work.icql.java.datastructure.list; public interface Queue<E> { void add(E e); E remove(); } <file_sep>/icql-java-designpattern/src/main/java/work/icql/java/designpattern/structural/bridge/color/RedColor.java package work.icql.java.designpattern.structural.bridge.color; public class RedColor implements Color { @Override public void printColor() { System.out.println("红色"); } } <file_sep>/icql-java-designpattern/src/main/java/work/icql/java/designpattern/behavioral/strategy/ConcreteStrategyA.java package work.icql.java.designpattern.behavioral.strategy; /** * 具体的策略A */ public class ConcreteStrategyA implements Strategy { @Override public void operation() { System.out.println("具体的策略A"); } } <file_sep>/icql-java-designpattern/src/main/java/work/icql/java/designpattern/behavioral/observer/ConcreteObserver1.java package work.icql.java.designpattern.behavioral.observer; import java.util.Observable; import java.util.Observer; /** * 具体的观察者1 */ public class ConcreteObserver1 implements Observer { @Override public void update(Observable o, Object arg) { System.out.println("观察者1-收到消息:" + arg); } } <file_sep>/icql-java-designpattern/src/main/java/work/icql/java/designpattern/behavioral/visitor/README.md ## 访问者模式 允许一个或者多个操作应用到一组对象上,解耦操作和对象本身 很难理解,https://www.jianshu.com/p/1f1049d0a0f4 <file_sep>/icql-java-designpattern/src/main/java/work/icql/java/designpattern/creational/singleton/EnumSingleton.java package work.icql.java.designpattern.creational.singleton; /** * 单例:枚举 */ public enum EnumSingleton { INSTANCE } <file_sep>/icql-java-designpattern/src/main/java/work/icql/java/designpattern/behavioral/chain/linked/HandlerB.java package work.icql.java.designpattern.behavioral.chain.linked; public class HandlerB extends Handler { @Override protected boolean doHandle(Object o) { boolean handled = false; //... return handled; } }<file_sep>/icql-java-util/src/main/java/work/icql/java/util/Application.java package work.icql.java.util; import work.icql.java.util.pdf.PdfMergeUtils; public class Application { public static void main(String[] args) throws Exception { PdfMergeUtils.merge("C:\\Users\\Casstime\\Desktop\\test", "C:\\Users\\Casstime\\Desktop\\test11"); } }<file_sep>/icql-java-designpattern/src/main/java/work/icql/java/designpattern/structural/decorator/ConcreteComponent1.java package work.icql.java.designpattern.structural.decorator; /** * 具体的构件1 */ public class ConcreteComponent1 implements Component { @Override public void operation() { System.out.println("具体的构件1"); } } <file_sep>/icql-java-designpattern/src/main/java/work/icql/java/designpattern/structural/bridge/shape/CircleShape.java package work.icql.java.designpattern.structural.bridge.shape; import work.icql.java.designpattern.structural.bridge.color.Color; public class CircleShape extends Shape { public CircleShape(Color color) { super(color); } @Override public void printShape() { color.printColor(); System.out.println("圆形"); } }<file_sep>/icql-java-designpattern/src/main/java/work/icql/java/designpattern/creational/factory/factorymethod/IObject.java package work.icql.java.designpattern.creational.factory.factorymethod; public interface IObject { } <file_sep>/icql-java-agent/src/main/java/work/icql/java/agent/transformer/handler/AppPropHandler.java package work.icql.java.agent.transformer.handler; public class AppPropHandler extends AbstractHandler { private static final String MYSQL_IP = "127.0.0.1"; private static final String MYSQL_PORT = "3306"; private static final String MYSQL_USERNAME = "root"; private static final String MYSQL_PASSWORD = "<PASSWORD>"; private static final String REDIS_IP = "127.0.0.1"; private static final String REDIS_PORT = "6379"; public AppPropHandler(String agentArgs) { super(agentArgs); handleClassName = "org.springframework.boot.env.OriginTrackedPropertiesLoader"; } @Override public byte[] actualHandle(byte[] classfileBuffer) { String mysqlIp = handleConfMap.getOrDefault("mysqlIp", MYSQL_IP).toString(); String mysqlPort = handleConfMap.getOrDefault("mysqlPort", MYSQL_PORT).toString(); String mysqlUsername = handleConfMap.getOrDefault("mysqlUsername", MYSQL_USERNAME).toString(); String mysqlPassword = handleConfMap.getOrDefault("mysqlPassword", MYSQL_PASSWORD).toString(); String redisIp = handleConfMap.getOrDefault("redisIp", REDIS_IP).toString(); String redisPort = handleConfMap.getOrDefault("redisPort", REDIS_PORT).toString(); return consumerMethod(classfileBuffer, handleClassName, "loadValue", ctMethod -> ctMethod.setBody("{" + " String key = $1.toString();\n" + " \n" + " $1.setLength(0);\n" + " while ($2.isWhiteSpace() && !$2.isEndOfLine()) {\n" + " $2.read();\n" + " }\n" + " org.springframework.boot.origin.TextResourceOrigin.Location location = $2.getLocation();\n" + " while (!$2.isEndOfLine() && !($3 && $2.isListDelimiter())) {\n" + " $1.append($2.getCharacter());\n" + " $2.read();\n" + " }\n" + " org.springframework.boot.origin.Origin origin = new org.springframework.boot.origin.TextResourceOrigin($0.resource, location);\n" + " \n" + " String value = $1.toString();\n" + " if (key.endsWith(\"jdbc-url\")) {\n" + " String[] split = value.split(\"/\");\n" + " split[2] = \"" + mysqlIp + ":" + mysqlPort + "\";\n" + " value = String.join(\"/\", split);\n" + " } else if (key.endsWith(\"username\")) {\n" + " value = \"" + mysqlUsername + "\";\n" + " } else if (key.endsWith(\"password\")) {\n" + " value = \"" + mysqlPassword + "\";\n" + " } else if (key.endsWith(\"spring.redis.host\")) {\n" + " value = \"" + redisIp + "\";\n" + " } else if (key.endsWith(\"spring.redis.port\")) {\n" + " value = \"" + redisPort + "\";\n" + " }\n" + " \n" + " return org.springframework.boot.origin.OriginTrackedValue.of(value, origin);" + "}"), "处理应用配置(db/redis等)"); } } <file_sep>/icql-java-designpattern/src/main/java/work/icql/java/designpattern/behavioral/mediator/README.md ## 中介模式 定义了一个单独的(中介)对象,来封装一组对象之间的交互。将这组对象之间的交互委派给与中介对象交互,来避免对象之间的直接交互<file_sep>/icql-java-designpattern/src/main/java/work/icql/java/designpattern/structural/flyweight/FlyweightClient.java package work.icql.java.designpattern.structural.flyweight; public class FlyweightClient { public static void main(String[] args) { FlyweightFactory flyweightFactory = new FlyweightFactory(); Flyweight test1 = flyweightFactory.getFlyweight("test1"); Flyweight test2 = flyweightFactory.getFlyweight("test1"); test1.operation("外部"); } } <file_sep>/icql-java-algorithm/src/main/java/work/icql/java/algorithm/搜索/SequentialSearch.java package work.icql.java.algorithm.搜索; /** * @author icql * @version 1.0 * @date 2019/1/12 16:32 * @Title 顺序表查找算法 * @Description SequentialSearch */ public class SequentialSearch { public static Object search(Object[] array, Object obj) { for (Object item : array) { if (item.equals(obj)) { return obj; } } return null; } } <file_sep>/icql-java-designpattern/src/main/java/work/icql/java/designpattern/creational/factory/abstractfactory/object/ObjectC2.java package work.icql.java.designpattern.creational.factory.abstractfactory.object; import work.icql.java.designpattern.creational.factory.abstractfactory.IObjectC; public class ObjectC2 implements IObjectC { } <file_sep>/icql-java-designpattern/src/main/java/work/icql/java/designpattern/creational/factory/factorymethod/ObjectFactory.java package work.icql.java.designpattern.creational.factory.factorymethod; public interface ObjectFactory { IObject createObject(String type); } <file_sep>/icql-java-algorithm/src/main/java/work/icql/java/algorithm/链表/链表_0141_环形链表.java package work.icql.java.algorithm.链表; import java.util.HashSet; import java.util.Objects; import java.util.Set; public class 链表_0141_环形链表 { static class ListNode { int val; ListNode next; ListNode() { } ListNode(int val) { this.val = val; } public void traverse() { System.out.println(); System.out.print("开始 -> "); ListNode pointer = this; while (Objects.nonNull(pointer)) { System.out.print(pointer.val + " -> "); pointer = pointer.next; } System.out.print("结束"); } } public boolean hasCycle(ListNode head) { if (Objects.isNull(head)) { return false; } ListNode pointer = head; Set<ListNode> nodeSet = new HashSet<>(); while (Objects.nonNull(pointer)) { if (nodeSet.contains(pointer)) { return true; } nodeSet.add(pointer); pointer = pointer.next; } return false; } public static void main(String[] args) { 链表_0141_环形链表 link = new 链表_0141_环形链表(); ListNode l1 = new ListNode(3); l1.next = new ListNode(2); l1.next.next = new ListNode(0); l1.next.next.next = new ListNode(-4); l1.next.next.next.next = l1.next; boolean ret = link.hasCycle(l1); System.out.println(); } } <file_sep>/icql-java-designpattern/src/main/java/work/icql/java/designpattern/structural/facade/README.md 门面模式为子系统提供一组统一的接口,定义一组高层接口让子系统更易用 简而言之,就是聚合一些细粒度的接口或方法组装成一个面向用户用例的接口,提高易用性,解决一致性,以及一些性能问题<file_sep>/README.md # icql-java ``` icql-java ├──agent (java代理) ├──algorithm (算法) ├──datastructure (数据结构) ├──designpattern (设计模式) ├──util (常用工具) ```<file_sep>/icql-java-designpattern/src/main/java/work/icql/java/designpattern/structural/composite/filesystem/Directory.java package work.icql.java.designpattern.structural.composite.filesystem; import java.util.ArrayList; import java.util.List; public class Directory extends FileSystemNode { private final List<FileSystemNode> subNodes = new ArrayList<>(); public Directory(String path) { super(path); } @Override public int countNumOfFiles() { int numOfFiles = 0; for (FileSystemNode node : subNodes) { numOfFiles += node.countNumOfFiles(); } return numOfFiles; } @Override public long countSizeOfFiles() { long sizeOfFiles = 0; for (FileSystemNode node : subNodes) { sizeOfFiles += node.countSizeOfFiles(); } return sizeOfFiles; } public void addSubNode(FileSystemNode node) { subNodes.add(node); } public void removeSubNode(FileSystemNode node) { subNodes.remove(node); } } <file_sep>/icql-java-algorithm/src/main/java/work/icql/java/algorithm/搜索/IndexSearch.java package work.icql.java.algorithm.搜索; /** * @author icql * @version 1.0 * @date 2019/1/27 17:23 * @Title 索引查找 * @Description IndexSearch */ public class IndexSearch { //稠密索引:每个索引项对应一条记录 //分块索引:一个索引项对应多条记录 //倒排索引:将内容 分词 作为索引项,保存查询内容的地址等内容 } <file_sep>/icql-java-designpattern/src/main/java/work/icql/java/designpattern/structural/adapter/AdapterClient.java package work.icql.java.designpattern.structural.adapter; import work.icql.java.designpattern.structural.adapter.adaptee.Adaptee1; import work.icql.java.designpattern.structural.adapter.adaptee.Adaptee2; import work.icql.java.designpattern.structural.adapter.clazz.ClazzAdaptor; import work.icql.java.designpattern.structural.adapter.object.ObjectAdaptor; public class AdapterClient { public static void main(String[] args) { ITarget target1 = new ClazzAdaptor(); target1.operationA(); target1.operationB(); ITarget target2 = new ObjectAdaptor(new Adaptee1(), new Adaptee2()); target2.operationA(); target2.operationB(); } } <file_sep>/icql-java-designpattern/src/main/java/work/icql/java/designpattern/structural/proxy/a_interfaces/UserServiceImpl.java package work.icql.java.designpattern.structural.proxy.a_interfaces; public class UserServiceImpl implements UserService { @Override public void action() { System.out.println("被代理类-action方法 执行了。。。"); } } <file_sep>/icql-java-designpattern/src/main/java/work/icql/java/designpattern/behavioral/state/impl_1/IMarioState.java package work.icql.java.designpattern.behavioral.state.impl_1; /** * 马里奥状态 */ public interface IMarioState { //以下是 所有状态 公共的事件 /** * 获得蘑菇事件 */ void obtainMushRoom(); /** * 获得火焰花事件 */ void obtainFireFlower(); /** * 接触怪兽事件 */ void meetMonster(); } <file_sep>/icql-java-designpattern/src/main/java/work/icql/java/designpattern/behavioral/state/impl_2/Fsm.java package work.icql.java.designpattern.behavioral.state.impl_2; public class Fsm { } <file_sep>/icql-java-designpattern/src/main/java/work/icql/java/designpattern/behavioral/chain/array/IHandler.java package work.icql.java.designpattern.behavioral.chain.array; public interface IHandler { boolean handle(Object o); }<file_sep>/icql-java-designpattern/src/main/java/work/icql/java/designpattern/creational/factory/abstractfactory/factory/ObjectBFactory.java package work.icql.java.designpattern.creational.factory.abstractfactory.factory; import work.icql.java.designpattern.creational.factory.abstractfactory.IObject; import work.icql.java.designpattern.creational.factory.abstractfactory.ObjectFactory; import work.icql.java.designpattern.creational.factory.abstractfactory.object.ObjectB1; import work.icql.java.designpattern.creational.factory.abstractfactory.object.ObjectB2; public class ObjectBFactory implements ObjectFactory { @Override public IObject createObject1(String type) { //复杂的创建逻辑 return new ObjectB1(); } @Override public IObject createObject2(String type) { //复杂的创建逻辑 return new ObjectB2(); } } <file_sep>/icql-java-designpattern/src/main/java/work/icql/java/designpattern/structural/flyweight/FlyweightFactory.java package work.icql.java.designpattern.structural.flyweight; import java.util.HashMap; import java.util.Map; public class FlyweightFactory { /** * 享元池 */ private final Map<String, Flyweight> flyweights = new HashMap<>(); public Flyweight getFlyweight(String key) { Flyweight flyweight = flyweights.get(key); if (flyweight == null) { //如果对象不存在,先创建一个新的对象添加到享元池中,然后返回 Flyweight fw = new ConcreteFlyweight(key); flyweights.put(key, fw); return fw; } else { //如果对象存在,则直接从享元池获取 return flyweight; } } } <file_sep>/icql-java-designpattern/src/main/java/work/icql/java/designpattern/creational/factory/simplefactory/IObject.java package work.icql.java.designpattern.creational.factory.simplefactory; public interface IObject { } <file_sep>/icql-java-designpattern/src/main/java/work/icql/java/designpattern/structural/proxy/b_dynamic/UserService.java package work.icql.java.designpattern.structural.proxy.b_dynamic; public interface UserService { void action(); } <file_sep>/icql-java-designpattern/src/main/java/work/icql/java/designpattern/creational/factory/factorymethod/factory/ObjectAFactory.java package work.icql.java.designpattern.creational.factory.factorymethod.factory; import work.icql.java.designpattern.creational.factory.factorymethod.ObjectFactory; import work.icql.java.designpattern.creational.factory.factorymethod.IObject; import work.icql.java.designpattern.creational.factory.factorymethod.object.ObjectA; public class ObjectAFactory implements ObjectFactory { @Override public IObject createObject(String type) { //复杂的创建逻辑 return new ObjectA(); } } <file_sep>/icql-java-designpattern/src/main/java/work/icql/java/designpattern/structural/flyweight/ConcreteFlyweight.java package work.icql.java.designpattern.structural.flyweight; public class ConcreteFlyweight extends Flyweight { public ConcreteFlyweight(Object intrinsicState) { super(intrinsicState); } @Override public void operation(Object extrinsicState) { System.out.println("内部状态:" + intrinsicState + "外部状态:" + extrinsicState); } } <file_sep>/icql-java-designpattern/src/main/java/work/icql/java/designpattern/behavioral/interpreter/README.md ## 解释器模式 解释器模式的代码实现比较灵活,没有固定的模板。我们前面也说过,应用设计模式主要是 应对代码的复杂性,实际上,解释器模式也不例外。它的代码实现的核心思想,就是将语法 解析的工作拆分到各个小类中,以此来避免大而全的解析类。一般的做法是,将语法规则拆 分成一些小的独立的单元,然后对每个单元进行解析,最终合并为对整个语法规则的解析<file_sep>/icql-java-designpattern/src/main/java/work/icql/java/designpattern/behavioral/template/TemplateClient.java package work.icql.java.designpattern.behavioral.template; /** * 模板方法模式 */ public class TemplateClient { public static void main(String[] args) { AbstractClass demo1 = new ConcreteClass1(); demo1.templateMethod(); AbstractClass demo2 = new ConcreteClass2(); demo2.templateMethod(); } } <file_sep>/icql-java-designpattern/src/main/java/work/icql/java/designpattern/behavioral/memento/README.md 备忘录模式,也叫快照(Snapshot)模式,存储副本以便后期恢复<file_sep>/icql-java-util/src/main/java/work/icql/java/util/pdf/PdfMergeUtils.java package work.icql.java.util.pdf; import com.itextpdf.text.Document; import com.itextpdf.text.pdf.PdfCopy; import com.itextpdf.text.pdf.PdfImportedPage; import com.itextpdf.text.pdf.PdfReader; import com.itextpdf.text.pdf.SimpleBookmark; import java.io.File; import java.io.FileOutputStream; import java.nio.file.Files; import java.nio.file.Paths; import java.util.*; public class PdfMergeUtils { private PdfMergeUtils() { } public static void merge(String inPath, String outPath) throws Exception { if (!Files.isDirectory(Paths.get(inPath)) || !Files.isDirectory(Paths.get(outPath))) { throw new IllegalArgumentException("参数inPath和outPath必须为文件夹"); } File[] inPdfFileArray = new File(inPath).listFiles(f -> f.getName().endsWith(".pdf")); if (inPdfFileArray == null || inPdfFileArray.length < 2) { throw new IllegalArgumentException("inPath文件夹内pdf文件数量至少为2个"); } //按照文件名排序 List<File> inPdfFiles = Arrays.asList(inPdfFileArray); inPdfFiles.sort(Comparator.comparing(File::getPath)); String outFile = Paths.get(outPath, "00_" + (System.currentTimeMillis() + "_输出.pdf")).toString(); Document outPdf = new Document(); PdfCopy outPdfWriter = new PdfCopy(outPdf, new FileOutputStream(outFile)); outPdf.open(); int pageOffset = 0; List<HashMap<String, Object>> allBookmarks = new ArrayList<>(); for (File pdfFile : inPdfFiles) { PdfReader reader = new PdfReader(pdfFile.getPath()); reader.consolidateNamedDestinations(); int pages = reader.getNumberOfPages(); //处理内容 for (int pageNum = 0; pageNum < pages; pageNum++) { PdfImportedPage page = outPdfWriter.getImportedPage(reader, pageNum + 1); outPdfWriter.addPage(page); } //处理书签 HashMap<String, Object> firstPage = new HashMap<>(3); firstPage.put("Action", "GoTo"); firstPage.put("Color", "0 0 0"); firstPage.put("Title", pdfFile.getName()); firstPage.put("Page", (pageOffset + 1) + " FitH " + reader.getPageSize(1).getHeight()); allBookmarks.add(firstPage); List<HashMap<String, Object>> bookmarks = SimpleBookmark.getBookmark(reader); if (bookmarks != null && bookmarks.size() > 0) { SimpleBookmark.shiftPageNumbers(bookmarks, pageOffset, null); allBookmarks.addAll(bookmarks); } pageOffset += pages; } outPdfWriter.setOutlines(allBookmarks); outPdf.close(); } } <file_sep>/icql-java-designpattern/src/main/java/work/icql/java/designpattern/creational/factory/factorymethod/object/ObjectB.java package work.icql.java.designpattern.creational.factory.factorymethod.object; import work.icql.java.designpattern.creational.factory.factorymethod.IObject; public class ObjectB implements IObject { } <file_sep>/icql-java-datastructure/src/main/java/work/icql/java/datastructure/tree/MaxHeap.java package work.icql.java.datastructure.tree; import java.util.ArrayList; import java.util.List; public class MaxHeap { private List<Integer> data; public MaxHeap() { data = new ArrayList<>(); } //堆化,将数组堆化,O(n),一个一个add,O(nlogn) public MaxHeap(int[] arr) { data = new ArrayList<>(); for (int i = parent(arr.length - 1); i >= 0; i--) { siftDown(i); } } //向堆中添加元素 //添加到数组尾部,上浮堆尾 public void add(int e) { data.add(e); siftUp(data.size() - 1); } private void siftUp(int k) { int parent = parent(k); while (k > 0 && data.get(parent) < data.get(k)) { swap(k, parent); k = parent; } } //看堆中的最大元素 public int findMax() { if (data.size() == 0) { throw new IllegalArgumentException(); } return data.get(0); } //取出堆中最大元素 //交换堆顶和尾部,删除堆尾,下沉堆顶 public int removeMax() { int ret = findMax(); swap(0, data.size() - 1); data.remove(data.size() - 1); siftDown(0); return ret; } private void siftDown(int k) { while (leftChild(k) < data.size()) { //在此轮循环中,data[k]和data[j]交换位置 int j = leftChild(k); if (j + 1 < data.size() && data.get(j + 1) > data.get(j)) { j++; } //data[j] 是 leftChild 和 rightChild 中的最大值 if (data.get(k) >= data.get(j)) { break; } swap(k, j); k = j; } } private void swap(int a, int b) { int aVal = data.get(a); int bVal = data.get(b); data.set(a, bVal); data.set(b, aVal); } private int parent(int index) { if (index == 0) { throw new IllegalArgumentException(); } return (index - 1) / 2; } private int leftChild(int index) { return index * 2 + 1; } private int rightChild(int index) { return index * 2 + 2; } } <file_sep>/icql-java-datastructure/src/main/java/work/icql/java/datastructure/list/linked/DoubleLinkedList.java package work.icql.java.datastructure.list.linked; import work.icql.java.datastructure.list.List; import java.util.Objects; public class DoubleLinkedList<E> implements List<E> { private Node<E> head; private Node<E> tail; private int size; public DoubleLinkedList() { } public DoubleLinkedList(E e) { head = new Node<>(e, null, null); tail = head; size++; } @Override public void add(int index, E e) { checkIndex(index); if (head == null) { head = new Node<>(e, null, null); tail = head; } else { Node<E> old = node(index); old.next = new Node<>(e, old, old.next); if (index == size - 1) { tail = old.next; } } size++; } @Override public void add(E e) { int index = size - 1; if (index < 0) { index = 0; } add(index, e); } @Override public void remove(int index) { checkIndex(index); Node<E> node = node(index); Node<E> next = node.next; if (next != null) { node.data = next.data; node.next = next.next; } else { tail = node.prev; tail.next = null; } size--; } @Override public void remove(E e) { int index = index(e); if (index != -1) { remove(index); } } @Override public void set(int index, E e) { checkIndex(index); Node<E> node = node(index); node.data = e; } @Override public E get(int index) { checkIndex(index); return node(index).data; } @Override public int size() { return size; } @Override public void traversal() { } @Override public String toString() { StringBuilder stringBuilder = new StringBuilder("DoubleLinkedList"); Node<E> node = head; for (int i = 0; i < size; i++) { stringBuilder.append("\n"); stringBuilder.append(i); stringBuilder.append(": "); stringBuilder.append(node); node = node.next; } return stringBuilder.toString(); } private void checkIndex(int index) { if (index < 0 || (size > 0 && index >= size) || (size == 0 && index > 0)) { throw new IllegalArgumentException("索引越界"); } } private Node<E> node(int index) { int midIndex = size >> 1; Node<E> node; if (index < midIndex) { node = head; for (int i = 0; i < index; i++) { node = node.next; } } else { node = tail; for (int i = size - 1; i > index; i--) { node = node.prev; } } return node; } private int index(E e) { Node<E> node = head; for (int index = 0; index < size; index++) { if (Objects.equals(node, e)) { return index; } node = node.next; } return -1; } private static class Node<E> { private E data; private Node<E> prev; private Node<E> next; public Node(E data, Node<E> prev, Node<E> next) { this.data = data; this.prev = prev; this.next = next; } @Override public String toString() { return data.toString(); } } } <file_sep>/icql-java-algorithm/src/main/java/work/icql/java/algorithm/排序/isN/RadixSort.java package work.icql.java.algorithm.排序.isN; /** * 基数排序: * 1)算法思想 * 比较数据的每一位,比如对手机号进行排序,可以先比较第一位,再比较第二位,以此类推 * 2)平均时间复杂度:O(n) */ public class RadixSort { private RadixSort() { } } <file_sep>/icql-java-designpattern/src/main/java/work/icql/java/designpattern/creational/singleton/InnerClassSingleton.java package work.icql.java.designpattern.creational.singleton; /** * 单例:内部类-懒加载 */ public final class InnerClassSingleton { private InnerClassSingleton() { } private static class SingletonHolder { public static final InnerClassSingleton INSTANCE = new InnerClassSingleton(); } public static InnerClassSingleton getInstance() { return SingletonHolder.INSTANCE; } } <file_sep>/icql-java-designpattern/src/main/java/work/icql/java/designpattern/structural/adapter/clazz/ClazzAdaptor.java package work.icql.java.designpattern.structural.adapter.clazz; import work.icql.java.designpattern.structural.adapter.adaptee.Adaptee1; import work.icql.java.designpattern.structural.adapter.ITarget; /** * 类适配器:缺陷,只能适配一个适配者 */ public class ClazzAdaptor extends Adaptee1 implements ITarget { @Override public void operationA() { //不需要修改,直接返回 super.operation1A(); } @Override public void operationB() { //需要修改,重新实现 super.operation1B(); } } <file_sep>/icql-java-designpattern/src/main/java/work/icql/java/designpattern/creational/factory/abstractfactory/Factory.java package work.icql.java.designpattern.creational.factory.abstractfactory; import work.icql.java.designpattern.creational.factory.abstractfactory.factory.ObjectAFactory; import work.icql.java.designpattern.creational.factory.abstractfactory.factory.ObjectBFactory; import work.icql.java.designpattern.creational.factory.abstractfactory.factory.ObjectCFactory; import java.util.HashMap; import java.util.Map; /** * 抽象工厂模式 */ public class Factory { private static final Map<String, ObjectFactory> FACTORY_BY_TYPE = new HashMap<>(); static { FACTORY_BY_TYPE.put("A", new ObjectAFactory()); FACTORY_BY_TYPE.put("B", new ObjectBFactory()); FACTORY_BY_TYPE.put("C", new ObjectCFactory()); } public static ObjectFactory createObject(String type) { if (type == null || type.isEmpty()) { return null; } return FACTORY_BY_TYPE.get(type.toUpperCase()); } } <file_sep>/icql-java-algorithm/src/main/java/work/icql/java/algorithm/链表/MinStack.java package work.icql.java.algorithm.链表; import java.util.Stack; public class MinStack { private Stack<Integer> stack; private Integer min; /** * initialize your data structure here. */ public MinStack() { stack = new Stack<>(); } public void push(int x) { if (min == null || x < min) { min = x; } stack.push(x); } public void pop() { Integer pop = stack.pop(); if (pop.equals(min)) { min = null; if (stack.size() == 0) { return; } for (int i = 0; i < stack.size(); i++) { Integer integer = stack.get(i); if (min == null || integer < min) { min = integer; } } } } public int top() { return stack.peek(); } public int getMin() { System.out.println(min); return min; } public static void main(String[] args) { // ["MinStack","push","push","push","top","pop","getMin","pop","getMin","pop","push","top","getMin","push","top","getMin","pop","getMin"] // [[],[2147483646],[2147483646],[2147483647],[],[],[],[],[],[],[2147483647],[],[],[-2147483648],[],[],[],[]] MinStack stack = new MinStack(); stack.push(2147483646); stack.push(2147483646); stack.push(2147483647); stack.top(); stack.pop(); stack.getMin(); stack.pop(); } } <file_sep>/icql-java-agent/README.md # icql-java-agent ## 简介 目前支持的功能有: ```text 1) 处理应用配置(db/redis等) 替换 springboot 配置文件中的 mysql,redis 等的 ip、账号密码,目前仅处理 .properties 配置文件 ``` ## 使用方法 ### 1) icql-java-agent.jar mvn package ### 2) 服务配置 ``` shell 服务vm参数: -javaagent:[agent.jar绝对路径]=[配置参数文件绝对路径] 示例: -javaagent:/icql-java-agent-0.1.0-SNAPSHOT-jar-with-dependencies.jar=/agentArgs.json ``` ### 3) 配置参数 #### (1) 参数说明 配置参数文件绝对路径:为空时,默认开启所有代理,on 字段用于是否开启该处理器 #### (2) 参数文件 agentArgs.json ``` json { "AppPropHandler": { "on": true, "mysqlIp": "127.0.0.1", "mysqlPort": "3306", "mysqlUsername": "root", "mysqlPassword": "<PASSWORD>", "redisIp": "127.0.0.1", "redisPort": "6379" } } ``` <file_sep>/icql-java-algorithm/src/main/java/work/icql/java/algorithm/排序/isnotN/InsertionSort.java package work.icql.java.algorithm.排序.isnotN; /** * 插入排序: * 1)稳定排序 * 2)算法思想 * 数据分为两个区间,已排序区间和未排序区间 * 插入算法的核心思想是取未排序区间中的元素,在已排序区间中找到合适的插入位置将其插入,并保证已排序区间数据一直有序 * 重复这个过程,直到未排序区间中元素为空 * 3)平均时间复杂度:O(n^2),平均空间复杂度:O(1) */ public class InsertionSort { private InsertionSort() { } public static void sort1(int[] data) { int count = data.length; for (int i = 1; i < count; i++) { //已排序区间的最后一个元素 int orderedIndex = i - 1; int current = data[i]; while (orderedIndex >= 0 && current < data[orderedIndex]) { data[orderedIndex + 1] = data[orderedIndex]; orderedIndex--; } data[orderedIndex + 1] = current; } } public static void sort2(int[] data) { int count = data.length; for (int i = 1; i < count; i++) { //已排序区间的最后一个元素 int orderedIndex = i - 1; int current = data[i]; for (; orderedIndex >= 0; orderedIndex--) { int prev = data[orderedIndex]; if (current < prev) { data[orderedIndex + 1] = prev; } else { break; } } data[orderedIndex + 1] = current; } } } <file_sep>/icql-java-designpattern/src/main/java/work/icql/java/designpattern/creational/singleton/LazySingleton.java package work.icql.java.designpattern.creational.singleton; /** * 单例:懒汉模式——延迟加载 * 同步范围过大(锁对象为类Class对象),性能不佳 */ public final class LazySingleton { private static LazySingleton INSTANCE; private LazySingleton() { } public synchronized static LazySingleton getInstance() { if (INSTANCE != null) { INSTANCE = new LazySingleton(); } return INSTANCE; } }<file_sep>/icql-java-designpattern/src/main/java/work/icql/java/designpattern/structural/composite/CompositeFileSystemClient.java package work.icql.java.designpattern.structural.composite; import work.icql.java.designpattern.structural.composite.filesystem.Directory; import work.icql.java.designpattern.structural.composite.filesystem.File; public class CompositeFileSystemClient { public static void main(String[] args) { Directory rootDir = new Directory("/"); Directory dir1 = new Directory("/dir1"); rootDir.addSubNode(dir1); dir1.addSubNode(new File("/dir1/234.txt")); rootDir.addSubNode(new File("/123.txt")); System.out.println(rootDir.countNumOfFiles()); } } <file_sep>/icql-java-designpattern/src/main/java/work/icql/java/designpattern/creational/factory/abstractfactory/object/ObjectB2.java package work.icql.java.designpattern.creational.factory.abstractfactory.object; import work.icql.java.designpattern.creational.factory.abstractfactory.IObjectB; public class ObjectB2 implements IObjectB { } <file_sep>/icql-java-designpattern/src/main/java/work/icql/java/designpattern/structural/composite/filesystem/FileSystemNode.java package work.icql.java.designpattern.structural.composite.filesystem; public abstract class FileSystemNode { protected String path; public FileSystemNode(String path) { this.path = path; } public String getPath() { return path; } public abstract int countNumOfFiles(); public abstract long countSizeOfFiles(); @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof FileSystemNode)) { return false; } FileSystemNode that = (FileSystemNode) o; return path.equals(that.path); } @Override public int hashCode() { return path.hashCode(); } } <file_sep>/icql-java-algorithm/src/main/java/work/icql/java/algorithm/排序/SortClient.java package work.icql.java.algorithm.排序; import java.util.Arrays; public class SortClient { public static void main(String[] args) throws Exception { // int dataCount = 100000; // int[] data = new int[dataCount]; // Random random = new Random(); // for (int i = 0; i < dataCount; i++) { // data[i] = random.nextInt(dataCount); // } // int[] data = new int[]{3, 2, 4, 5, 1}; int[] data = new int[]{6, 4, 7, 1, 9, 0, 2}; long start = System.currentTimeMillis(); //冒泡排序第一版 //BubbleSort.sort1(data); //冒泡排序第二版 //BubbleSort.sort2(data); //冒泡排序第三版 //BubbleSort.sort3(data); //插入排序第一版 //InsertionSort.sort1(data); //插入排序第二版 //InsertionSort.sort2(data); //选择排序 //SelectionSort.sort(data); //归并排序 //MergeSort.sort(data); //快速排序 //QuickSort.sort(data); sort3(data, 0, data.length - 1); long end = System.currentTimeMillis(); System.out.println(Arrays.toString(data) + "" + (end - start) + "ms"); } public static void sort1(int[] data) { for (int i = 0; i < data.length - 1; i++) { for (int j = 0; j < data.length - 1 - i; j++) { int a = data[j]; int b = data[j + 1]; if (a > b) { data[j] = b; data[j + 1] = a; } } } } public static void sort2(int[] data, int left, int right) { if (left >= right) { return; } int mid = (left + right) / 2; sort2(data, left, mid); sort2(data, mid + 1, right); merge(data, left, right, mid); } private static void merge(int[] data, int left, int right, int mid) { int[] arr = Arrays.copyOfRange(data, left, right + 1); int leftIndex = 0; int leftIndexEnd = mid - left; int rightIndex = leftIndexEnd + 1; int rightIndexEnd = arr.length - 1; //遍历重新设置 原数组 [left,right] 的值使之有序 for (int k = left; k <= right; k++) { //左边元素已经处理完 if (leftIndex > leftIndexEnd) { data[k] = arr[rightIndex]; rightIndex++; continue; } //右边元素已经处理完 if (rightIndex > rightIndexEnd) { data[k] = arr[leftIndex]; leftIndex++; continue; } //如果左边所指元素 <= 右边所指元素 if (arr[leftIndex] <= arr[rightIndex]) { data[k] = arr[leftIndex]; leftIndex++; continue; } //如果左边所指元素 > 右边所指元素 data[k] = arr[rightIndex]; rightIndex++; } } public static void sort3(int[] data, int left, int right) { if (left >= right) { return; } int partition = partition(data, left, right); sort3(data, left, partition - 1); sort3(data, partition + 1, right); } private static int partition(int[] data, int left, int right) { //选取分区点,右边界 int pivotIndex = right; int pivotValue = data[pivotIndex]; int boarderIndex = left; int borderValue = data[boarderIndex]; //遍历一遍 for (int i = left; i <= right; i++) { int current = data[i]; //当游标值小于分区点值时,交换边界点和游标值 if (current < pivotValue) { data[i] = borderValue; data[boarderIndex] = current; //更新边界点和边界索引 boarderIndex++; borderValue = data[boarderIndex]; } } data[right] = borderValue; data[boarderIndex] = pivotValue; pivotIndex = boarderIndex; return pivotIndex; } } <file_sep>/icql-java-agent/src/main/java/work/icql/java/agent/transformer/handler/DefaultHandler.java package work.icql.java.agent.transformer.handler; public class DefaultHandler extends AbstractHandler { public DefaultHandler(String agentArgs) { super(agentArgs); } @Override public byte[] actualHandle(byte[] classfileBuffer) { return classfileBuffer; } } <file_sep>/icql-java-algorithm/src/main/java/work/icql/java/algorithm/链表/链表_0061_旋转链表.java package work.icql.java.algorithm.链表; import java.util.Objects; public class 链表_0061_旋转链表 { static class ListNode { int val; ListNode next; ListNode(int x) { val = x; } public void traverse() { System.out.println(); System.out.print("开始 -> "); ListNode pointer = this; while (Objects.nonNull(pointer)) { System.out.print(pointer.val + " -> "); pointer = pointer.next; } System.out.print("结束"); } } public ListNode rotateRight(ListNode head, int k) { if (k < 0 || head == null) { return head; } //遍历第1遍拿到size int size = 1; ListNode cursor = head; while (cursor.next != null) { size++; cursor = cursor.next; } //计算最小的k int minK = k % size; if (minK == 0) { return head; } //两个需要处理的结点 //1)原链表的最后一个结点 //2)返回链表的最后一个结点 ListNode originLastNode = cursor; int resultEndIndex = size - minK - 1; ListNode resultEndNode = null; cursor = head; for (int index = 0; index < size; index++) { if (index == resultEndIndex) { resultEndNode = cursor; break; } cursor = cursor.next; } ListNode newHead = resultEndNode.next; resultEndNode.next = null; originLastNode.next = head; return newHead; } public static void main(String[] args) { 链表_0061_旋转链表 link = new 链表_0061_旋转链表(); ListNode l1 = new ListNode(3); l1.next = new ListNode(9); l1.next.next = new ListNode(6); l1.next.next.next = new ListNode(1); l1.next.next.next.next = new ListNode(4); ListNode ret = link.rotateRight(l1, 2); ret.traverse(); System.out.println(); } } <file_sep>/icql-java-designpattern/src/main/java/work/icql/java/designpattern/creational/factory/abstractfactory/factory/ObjectAFactory.java package work.icql.java.designpattern.creational.factory.abstractfactory.factory; import work.icql.java.designpattern.creational.factory.abstractfactory.IObject; import work.icql.java.designpattern.creational.factory.abstractfactory.ObjectFactory; import work.icql.java.designpattern.creational.factory.abstractfactory.object.ObjectA1; import work.icql.java.designpattern.creational.factory.abstractfactory.object.ObjectA2; public class ObjectAFactory implements ObjectFactory { @Override public IObject createObject1(String type) { //复杂的创建逻辑 return new ObjectA1(); } @Override public IObject createObject2(String type) { return new ObjectA2(); } }
997d1e6951d31fb8beda337b89c85c4105d33248
[ "Markdown", "Java" ]
63
Java
icql/icql-java
df4e1125a625a1c8c61d792975026282ea35bf63
af5784e200cd287b9703b2029a80f2a263746b6d
refs/heads/master
<repo_name>gansw/AWSLambdaFunctions<file_sep>/validate-phone-number/index.js 'use strict'; /** * This sample demonstrates an implementation of the Lex Code Hook Interface * in order to serve a sample bot which manages orders for flowers. * Bot, Intent, and Slot models which are compatible with this sample can be found in the Lex Console * as part of the 'OrderFlowers' template. * * For instructions on how to set up and test this bot, as well as additional samples, * visit the Lex Getting Started documentation */ // --------------- Helpers to build responses which match the structure of the necessary dialog actions ----------------------- function elicitSlot(sessionAttributes, intentName, slots, slotToElicit, message, responseCard) { return { sessionAttributes, dialogAction: { type: 'ElicitSlot', intentName, slots, slotToElicit, message, responseCard, }, }; } function close(sessionAttributes, fulfillmentState, message, responseCard) { return { sessionAttributes, dialogAction: { type: 'Close', fulfillmentState, message, responseCard, }, }; } function delegate(sessionAttributes, slots) { return { sessionAttributes, dialogAction: { type: 'Delegate', slots, }, }; } function buildValidationResult(isValid, violatedSlot, messageContent) { return { isValid, violatedSlot, message: { contentType: 'PlainText', content: messageContent }, }; } function validatePhoneNumber(intentRequest, callback) { console.log('Inside validatePhoneNumber'); const source = intentRequest.invocationSource; const outputSessionAttributes = intentRequest.sessionAttributes || {}; if (source === 'DialogCodeHook') { console.log( ' Inside Code Hook '); const slots = intentRequest.currentIntent.slots; console.log('Intent Name : ' + intentRequest.currentIntent.name ); console.log(' Intent Request '+ JSON.stringify(intentRequest)); var inputNumber = ''; if( slots.CallBackNumber != null && ( typeof(outputSessionAttributes.CallbackPhoneNumber) === 'undefined' || ( typeof(outputSessionAttributes.CallbackPhoneNumber) !== 'undefined' && outputSessionAttributes.CallbackPhoneNumber == 'InValid' ) ) ) { // Callback number validation inputNumber = slots.CallBackNumber; if( inputNumber.length == 10) { inputNumber = '+1'+inputNumber; outputSessionAttributes.CallbackPhoneNumber = inputNumber; console.log(' Output '+JSON.stringify(outputSessionAttributes)); callback( elicitSlot( outputSessionAttributes, intentRequest.currentIntent.name, slots, 'NumberConfirmation', { contentType: 'SSML', content: '<speak> Okay, we will call you back at <say-as interpret-as="telephone">'+slots.CallBackNumber+'</say-as>. is that correct? </speak>'}, null ) ); return; } else { if(typeof(outputSessionAttributes.RetryCounter) !== 'undefined') { outputSessionAttributes.RetryCounter = parseInt(outputSessionAttributes.RetryCounter) + 1; }else { outputSessionAttributes.RetryCounter = 1; } if(outputSessionAttributes.RetryCounter === 2){ outputSessionAttributes.CallbackPhoneNumber = 'InValid'; callback(close(outputSessionAttributes, 'Failed', { contentType: 'PlainText', content: 'Sorry, we are having trouble understanding you.'})); return; } callback( elicitSlot( outputSessionAttributes, intentRequest.currentIntent.name, slots, 'CallBackNumber', { contentType: 'PlainText', content: 'The phone number you entered is invalid. Please provide the number you would like us to call you back on'}, null ) ); return; } } else if( typeof(outputSessionAttributes.CallbackPhoneNumber) !== 'undefined' && outputSessionAttributes.CallbackPhoneNumber != 'InValid' && slots.NumberConfirmation != null ) { // Yes No Confirmation console.log("inside yesNo slot"); var yesNo = slots.NumberConfirmation; if(yesNo.toLowerCase() == "no" || yesNo.toLowerCase() == "nope" || yesNo.toLowerCase() == "cancel") { console.log("inside NO"); outputSessionAttributes.CallbackPhoneNumber = 'InValid'; if(typeof(outputSessionAttributes.RetryCounter) !== 'undefined') { outputSessionAttributes.RetryCounter = parseInt(outputSessionAttributes.RetryCounter) + 1; }else { outputSessionAttributes.RetryCounter = 1; } if( outputSessionAttributes.RetryCounter > 1 ){ callback(close(outputSessionAttributes, 'Failed', { contentType: 'PlainText', content: 'Sorry, we are having trouble understanding you.'})); return; } callback( elicitSlot( outputSessionAttributes, intentRequest.currentIntent.name, slots, 'CallBackNumber', { contentType: 'PlainText', content: 'Okay. Kindly specify phone number again.'}, null ) ); return; } else { callback(close(outputSessionAttributes, 'Fulfilled', { contentType: 'PlainText', content: 'Okay'})); return; } } else { // Retry if(typeof(outputSessionAttributes.RetryCounter) !== 'undefined') { outputSessionAttributes.RetryCounter = parseInt(outputSessionAttributes.RetryCounter) + 1; }else { outputSessionAttributes.RetryCounter = 1; } if(outputSessionAttributes.RetryCounter > 1 ){ outputSessionAttributes.CallbackPhoneNumber = 'InValid'; callback(close(outputSessionAttributes, 'Failed', { contentType: 'PlainText', content: 'Sorry, we are having trouble understanding you.'})); return; } callback( elicitSlot( outputSessionAttributes, intentRequest.currentIntent.name, slots, 'CallBackNumber', { contentType: 'PlainText', content: 'Okay. Kindly specify phone number again.'}, null ) ); return; } } console.log( 'Outside code hook '); } // --------------- Intents ----------------------- /** * Called when the user specifies an intent for this skill. */ function dispatch(intentRequest, callback) { console.log(`dispatch userId=${intentRequest.userId}, intentName=${intentRequest.currentIntent.name}`); return validatePhoneNumber(intentRequest, callback); } // --------------- Main handler ----------------------- // Route the incoming request based on intent. // The JSON body of the request is provided in the event slot. exports.handler = (event, context, callback) => { try { console.log(`event.bot.name=${event.bot.name}`); // Print Event JSON passed from ContactFlow/Event var passedEventData = JSON.stringify(event); console.log( ' EventData : '+passedEventData); dispatch(event, (response) => callback(null, response)); } catch (err) { callback(err); } };
8d2b77e52b9c6dbe53e4597c1effc9367e5e6e29
[ "JavaScript" ]
1
JavaScript
gansw/AWSLambdaFunctions
822174598d187fc4a71025d2465771019ee669b6
3f856efc2afd2857491c29ab53a0c706d5991c2e
refs/heads/master
<repo_name>bonyaminsany1/listed-blue<file_sep>/db/seeds.rb # This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # items = [{:category => 'Furniture', :title => 'New Sofa', :description => 'I would like to sell my new sofa', :price => 100, :post_date => '18-10-2017'}, {:category => 'Books', :title => 'IT484 TextBook SaaS', :description => 'This book was used in IT484 during Fall 2017', :price => 35, :post_date => '17-10-2017'}, {:category => 'Books', :title => 'Sample', :description => 'Sample 1', :price => 0.01, :post_date => '17-10-2017', :contact => '<EMAIL>'}, ] items.each do |item| Item.create!(item) end <file_sep>/Readme.md Hello world! This is the another unofficial version of Craigslist. Don't know who the heck is Craig, and this app won't change the way it is, but it's fun to make things like this. <file_sep>/app/models/item.rb class Item < ActiveRecord::Base @all_categories = ['Appliances', 'Automotive', 'Baby/Kid', 'Beauty/Health', 'Bikes', 'Books', 'Camping', 'Clothes', 'Computers', 'Crafts', 'Electronics', 'Farm/Garden', 'Furniture', 'Gaming', 'General', 'Household', 'Jewelry', 'Music', 'Parts', 'Photo/Video', 'Sporting', 'Tools', 'Toys/Games'] def self.all_categories return @all_categories end end <file_sep>/app/controllers/items_controller.rb class ItemsController < ApplicationController def item_params params.require(:item).permit(:category, :title, :description, :price, :post_date, :contact) end def show id = params[:id] # retrieve item ID from URI route @item = Item.find(id) # look up item by unique ID # will render app/views/items/show.<extension> by default end def index @items = Item.all @all_categories = Item.all_categories @sort_by = params[:sort_by] ? params[:sort_by] : (session[:sort_by] || "id") @hilite = params[:sort_by] @filtered_categories = (params[:categories] and params[:commit] == 'Refresh') ? params[:categories].keys : (session[:categories] || @all_categories) if params[:sort_by] != session[:sort_by] or params[:categories] != session[:categories] session[:categories] = @filtered_categories session[:sort_by] = @sort_by flash.keep redirect_to items_path :sort_by => @sort_by, :categories => @filtered_categories end @items = Item.order(@sort_by).where(category: @filtered_categories) end def new # default: render 'new' template end def create @item = Item.new(item_params) @item.post_date = Time.now @item.save! flash[:notice] = "#{@item.title} was successfully created." redirect_to items_path end def edit @item = Item.find params[:id] end def update @item = Item.find params[:id] @item.update_attributes!(item_params) flash[:notice] = "#{@item.title} was successfully updated." redirect_to item_path(@item) end def destroy @item = Item.find(params[:id]) @item.destroy flash[:notice] = "Item '#{@item.title}' deleted." redirect_to items_path end end
8a041c5544049ddfa06eb0f83db44bcd1d03839a
[ "Markdown", "Ruby" ]
4
Ruby
bonyaminsany1/listed-blue
4c0e34a86debc3a87ab5e0153ebdecdb809de6fb
b66eb3c9fb0ab4ec2adf10f41f32b65da5ed0620
refs/heads/main
<file_sep># <EMAIL> Personal site. Built with Next.js, TypeScript, MDX and Tailwind CSS.<file_sep>--- title: Fóram date: "2022-05-14" description: "A fullstack discussion forum app with a React frontend, Scala REST API, and PostgreSQL database. Includes authentication, user roles, and test suites." slug: foram repoUrl: https://github.com/gerhynes/foram-rest-api siteUrl: "" tags: ["Scala", "Akka", "React", "PostgreSQL"] image: /images/projects/foram/foram.png --- ### Project Purpose and Goal Part of my Higher Diploma (HDip) in Software Design and Development involved building a fullstack app over 12 weeks and writing up detailed design and testing documentation for it. The best part about the project was that the app would be built with input from the company I was going to do my internship with. This ensured that the technologies used and skills learned would be directly relevant to working in industry after I completed my studies. The company asked me to build a REST API in Scala that persisted data to a PostgreSQL database. I asked to build the frontend in React and use JSON Web Tokens (JWTs) for authentication, and we agreed on this architecture. Before this project, I had built a few fullstack Node.js apps (from tutorials and courses) but had never worked with Scala or connected a React frontend to a custom REST API. Needless to say, I was both excited and nervous to learn a new language and build an ambitious project with it. I had been using online forums extensively while learning to code and wanted to see if I could build a stripped down version of [Discourse](https://www.discourse.org/), but in React and Scala instead of Ember.js and Ruby on Rails. An app where users would be able to create accounts, read threads and posts, and add their own. Admins would be able to create new subforums and update or delete any content. The company gave me a lot of freedom about the functionality of the app and made it clear that their priority was that I learned relevant skills and good software development habits. ### Tech Stack I had initially planned to build the project with Java and the Spring Framework, since the HDip really focused on Java and it's so widely used in industry. But the company recommended that I use Scala since that's the language I'd be working with in my internship. This was a bit stressful as I had to spend the first 3 of my 12 weeks learning the language and its ecosystem as quickly as I could. I settled on the [Akka](https://akka.io/) toolkit for routing and business logic (in part simply because there were more learning resources for it than for other Scala libraries). Akka's actor system initially required a bit of a mental shift but ultimately helped me to get my head around concurrent programming. I chose [Slick](https://scala-slick.org/) for interacting with the database, since it let me work with records as if they were Scala collections, benefit from static type checking, and compose functions together. The company gave me the option of using PostgreSQL or Cassandra for the database. I went with PostgreSQL since I wanted to get more experience working with relational databases, having mostly used MongoDB up to that point. For the frontend, I chose Next.js and Tailwind CSS as I wanted to maintain my skills with these technologies while I learned Scala. For authentication, I selected JSON Web Tokens as it was a technology I had wanted to learn for some time, and figured that writing authentication "from scratch" would be a valuable learning opportunity. ### Problems and Thought Process #### 1 - Documentation and Learning Resources for Scala ![Official Scala docs](/images/projects/foram/official-scala-docs.png) Finding good resources for Scala was a challenge throughout the project. Compared to JavaScript or Python, Scala is pretty niche. This means there are far fewer resources for learning it, less active forums when asking for help, and fewer questions that have already been asked and answered in GitHub issues or on Stack Overflow. Also, a lot of Scala documentation just isn't great. Don't get me wrong, the official docs for Scala are excellent. They're detailed, well-written, and accessible. But the docs for many popular Scala libraries are lacking. They use technical terms and don't define them, have broken links, provide examples that use outdated APIs, and don't demonstrate important features, especially when it comes to testing. Early on, I found as many tutorials and learning resources as I could ([collected here](https://gerardhynes.com/resources-for-learning-scala/)) to quickly get up to speed with Scala and Akka. As the project progressed, I worked my way through the docs, explored Scala projects on GitHub, and started asking questions on the Scala and Lightbend forums. #### 2 - Marshalling JSON ![Custom JSON format](/images/projects/foram/custom-json-format.png) Working with JSON was a surprising challenge, since it had been pretty straightforward in JavaScript frameworks like Express.js. I used the `spray-json` library to convert, or "marshall", requests and responses into JSON and got used to providing JSON formats for every custom class. But unfortunately `spray-json` doesn't have built-in support for UUIDs or `OffsetDateTime`. Since I used these in my database schema, I had to research and write custom Scala implicits (values that Scala functions will look for if they have not been explicitly passed as a parameter) to tell `spray-json` how to handle them. Having to think about how to map data to and from other data formats, and how Scala functions can look outside themselves for implicit arguments, gradually gave me an appreciation for Scala as a language, and the programming paradigms it can support. #### 3 - Asynchronous Programming ![Asynchronous code in routes](/images/projects/foram/async-code-in-routes.png) Akka is designed for concurrent and asynchronous programming and I made extensive use of Scala Futures (placeholder objects for values that may not yet exist) throughout the project. For the API routes, I had to learn how to use pattern matching to handle successful and unsuccessful Futures. When testing the database queries, I learned how to chain Futures to ensure they ran in a specific order so they would reset the database and seed sample data before running each test suite. I already had experience writing asynchronous JavaScript with promises and the async/await syntax and was able to transfer some of this knowledge when working with Scala Futures. Where Scala differed, I studied the documentation and other learning resources to find the idiomatic Scala way to handle these situations. Working with Scala Futures gave me a greater insight into asynchronous programming, which I have been able to apply when working with asynchronous JavaScript, in the frontend of this app and in other projects. ### Lessons Learned ![Test suite passing](/images/projects/foram/test-suite-passing.png) Before I started the project, I asked the company for advice on good habits to develop and they recommended three things: version control, test-driven development, and agile practices. By the end of the project I had done my best to put each of these into practice and learned a lot in the process. I was already using Git and GitHub for all my personal projects but I made a conscious effort to adopt better practices, such as using feature branches, committing more often and using more descriptive commit messages. Agile was something I had practically no experience with at the outset of this project. There are plenty of “A Day in the Life of a Software Developer” videos on YouTube but hardly any of them talk about the process of developing software. <NAME>'s [What DOES a SOFTWARE DEVELOPER actually do?](https://youtu.be/2M66pchjzDw) is a welcome exception. I tried tracking the steps of this project using Trello but struggled to use it as more than a todo list. Once I started my internship and got to see a team use Agile in action, I learned much more about how Agile works, how teams collaborate, and how projects get managed. I also had very limited experience with testing before this project and learned a lot, both in terms of writing tests and in refactoring my code to make it more testable. This led me to learn about related topics like dependency injection and mocking. By the end of the project, I had written unit tests for every route and Akka actor, as well as integration tests for all the classes that queried the database. Writing and debugging tests helped me to reconsider the code I had already written. For example, the tests for the `findLatest` method on the `TopicsDao` class would inconsistently fail. This method should return a list of up to 10 topics ordered by their `created_at` field. Initially the test asserted that a specific sequence of sample topics would be returned from the database. While debugging I uncovered that the problem was caused if two sample topics were created with the exact same datetime, and so the precise order of the sequence could not be guaranteed. The solution was to update the test to check that the `created_at` field on a topic was greater than or equal to the next topic in the sequence (and to anticipate such possibilities in advance in future). Building the app was both challenging and rewarding, and was a period of concentrated learning. I'm proud that I managed to deliver all the requirements of the project, write detailed documentation, and start to build good software development practices that I trust will serve me well in the future. <file_sep>import fs from "fs"; import { join } from "path"; import matter from "gray-matter"; export type Post = { content: string; data: { [key: string]: any; }; }; export type Project = { content: string; data: { [key: string]: any; }; }; const postsDirectory = join(process.cwd(), "posts"); const projectsDirectory = join(process.cwd(), "projects"); export function getPostSlugs(): string[] { return fs.readdirSync(postsDirectory); } export function getProjectSlugs(): string[] { return fs.readdirSync(projectsDirectory); } export function getPostBySlug(slug: string): string { const realSlug = slug.replace(/\.mdx$/, ""); const fullPath = join(postsDirectory, `${realSlug}.mdx`); const fileContents = fs.readFileSync(fullPath, "utf8"); return fileContents; } export function getProjectBySlug(slug: string): string { const realSlug = slug.replace(/\.mdx$/, ""); const fullPath = join(projectsDirectory, `${realSlug}.mdx`); const fileContents = fs.readFileSync(fullPath, "utf8"); return fileContents; } export function getAllPostSlugs(): string[] { const slugs = fs.readdirSync(postsDirectory); const realSlugs = slugs.map((slug) => slug.replace(/\.mdx$/, "")); return realSlugs; } export function getAllProjectSlugs(): string[] { const slugs = fs.readdirSync(projectsDirectory); const realSlugs = slugs.map((slug) => slug.replace(/\.mdx$/, "")); return realSlugs; } export function getAllPosts(): Post[] { const slugs = getAllPostSlugs(); const postFiles = slugs.map((slug) => getPostBySlug(slug)); const posts = postFiles.map((post) => { const { content, data } = matter(post); return { content, data, }; }); const sortedPosts = posts.sort( (post1, post2) => new Date(post2.data.date).getTime() - new Date(post1.data.date).getTime() ); return sortedPosts; } export function getAllProjects() { const slugs = getAllProjectSlugs(); const projectFiles = slugs.map((slug) => getProjectBySlug(slug)); const projects = projectFiles.map((project) => { const { content, data } = matter(project); return { content, data, }; }); const sortedProjects = projects.sort((project1, project2) => project1.data.date > project2.data.date ? -1 : 1 ); return sortedProjects; } <file_sep>--- title: "Resources for Learning Scala" linkText: "learning Scala" date: "2022-04-07" slug: resources-for-learning-scala description: "Learning Scala can be challenging but there are resources for beginners. Here are a few I found helpful." isPublished: true tags: ["Scala"] image: /images/posts/resources-for-learning-scala/resources-for-learning-scala.png --- Recently, I've been learning Scala and when I first searched for resources for learners I was a bit worried by how few came up, and how many of them weren't very good. There were barely any YouTube tutorials, many of the blog posts were years old, and some of the conference talks required way more Mathematics than I had. Compared to languages like JavaScript or Python, or even Java, Scala is much more niche, with far less material for beginners. It also has its own quirks and a steeper learning-curve than some other programming languages, but Scala is definitely worth learning, and there are good resources out there. ### Why learn Scala? A multi-paradigm language, Scala combines features of both object-oriented and functional programming. It runs on the Java Virtual Machine (JVM), and so can be used anywhere Java can run (it can even use Java libraries), but has a much more concise and “human readable” syntax. It's statically typed, so you'll catch more errors before you ship your code, and most of the time the compiler will infer the types for you so you don't need type annotations everywhere. Scala is especially used for high-performance distributed systems and large-scale data processing. Scala powers Twitter, DisneyPlus and The Guardian. Netflix, Spotify, and Amazon all use it for data analytics. If you want to learn Scala, here are some resources that I've found helpful. None of these links are affiliates, they're just resources that helped me on my learning journey. ### Video Resources #### Scala at Light Speed ![Scala at Lightspeed](/images/posts/resources-for-learning-scala/scala-at-lightspeed.png) Link: [Scala at Lightspeed](https://youtu.be/-8V6bMjThNo) A two hour crash course introduction to the language by <NAME> from [RocktheJVM](https://rockthejvm.com/) that will give you a feel for whether you want to dive deeper into Scala. It does assume you have some familiarity with languages like Java, but Daniel's explanations are clear and the short course will quickly give you a good overview of the language, from the basic syntax to futures, pattern matching and higher order functions. From there, Daniel has many more videos on more advanced features of Scala, as well as tools and libraries like Akka, Cats and Doobie. #### Effective Programming in Scala ![Effective Programming in Scala](/images/posts/resources-for-learning-scala/effective-programming-in-scala.png) Link: [coursera.org/learn/effective-scala](https://www.coursera.org/learn/effective-scala) If you'd like a more thorough course with a college-semester like structure, this is a good option. Provided by the École Polytechnique Fédérale de Lausanne (which operates the [Scala Center](https://scala.epfl.ch/) open source foundation), this Coursera course regularly opens for new enrollments and doesn't cost anything to audit. The lectures are clear and concise, explaining concepts in bite-sized stages. While the assignments can be a bit of a jump compared to the lecture content, the regular quizzes will help you retain what you're learning. The course uses Scala 3 (which is still very new) but the instructors give examples in Scala 2 where the syntax is different. The course also forms the first part of Coursera's [Functional Programming in Scala Specialization](https://www.coursera.org/specializations/scala), so if you want to take your learning further, there's a clear curriculum ahead of you. ### Written Resources #### The Official Scala Docs ![The official Scala docs](/images/posts/resources-for-learning-scala/scala-docs.png) Link: [docs.scala-lang.org](https://docs.scala-lang.org/) The official documentation for languages isn't always accessible for learners, but the Scala docs are genuinely great: detailed, well-designed and written in pretty accessible language. The [Scala Book](https://docs.scala-lang.org/overviews/scala-book/introduction.html) provides a friendly introduction and overview of the language in about 50 lessons. #### <NAME>, Get Programming with Scala ![Get Programming with Scala](/images/posts/resources-for-learning-scala/get-programming-with-scala.png) Link: [manning.com/books/get-programming-with-scala](https://www.manning.com/books/get-programming-with-scala) Too many Scala resources assume two things: that you are already an experienced Java developer and that you are comfortable with university-level mathematics. <NAME>'s excellent book assumes neither. It's written in a very accessible style with short chapters, exercises and projects to practice what you're learning. It's also very comprehensive, covering everything from getting started with sbt, the Scala build tool, and going over object-oriented and functional programming, to setting up a HTTP server, handling concurrency, serializing JSON and testing with ScalaTest. #### This Week in Scala ![This Week in Scala](/images/posts/resources-for-learning-scala/this-week-in-scala.png) Link: [medium.com/disney-streaming/tagged/scala](https://medium.com/disney-streaming/tagged/scala) This newsletter by <NAME>, Principal Engineer at Disney Streaming, aims to share the latest news from the world of Scala. While it does recommend learning resources, it's mostly a handy way to keep an eye on developments in the Scala ecosystem and learn about how the language is used in industry. ### Practice #### Exercism ![Exercism Scala Track](/images/posts/resources-for-learning-scala/exercism-scala-track.png) Link: [exercism.org/tracks/scala](https://exercism.org/tracks/scala) There aren't a lot of resources that let you practice your Scala skills with exercises, which makes Exercism's Scala track particularly valuable. There are more than 90 challenges, which you solve locally, run tests on, and push your solutions to Exercism to share with other learners. The difficulty levels ramps up quite quickly from “Hello World” to solving tricky mathematical problems by making use of the ins and outs of the language. The ability to look at solutions by other learners is especially helpful, often revealing a much simpler or more efficient solution than the one you came up with. I haven't used their volunteer mentoring feature yet but the opportunity to give and receive one-on-one feedback sounds really promising. ### Forums #### Scala Users ![Scala Users](/images/posts/resources-for-learning-scala/scala-users.png) Link: [users.scala-lang.org](https://users.scala-lang.org/) The official Scala forum. It's mostly used by experienced Scala developers but I've found the community to be generally quite friendly and willing to answer questions from learners. #### Scala Subreddit ![Scala subreddit](/images/posts/resources-for-learning-scala/scala-subreddit.png) Link: [reddit.com/r/scala](https://www.reddit.com/r/scala/) As with any subreddit, this can have its share of strong opinions and arguments about things that really aren't important, but you can also find useful recommendations and sometimes answers to your very specific problems. If you're learning Scala, good luck and I hope you find these resources helpful. <file_sep>--- title: "How to Overcome CORS with Serverless Functions" linkText: "overcoming CORS" date: "2021-09-01" slug: how-to-overcome-cors-with-serverless-functions description: "Get rid of that dreaded CORS message using serverless functions with Netlify." isPublished: true tags: ["CORS", "Serverless"] image: /images/posts/how-to-overcome-cors-with-serverless-functions/cors-serverless-header.png --- ### The Problem Recently I was working on a [Frontend Mentor challenge](https://www.frontendmentor.io/challenges/ip-address-tracker-I8-0yYAH0), an app where you can input an IP address or url and fetch and display information about it. ![Screenhot of IP Address app](/images/posts/how-to-overcome-cors-with-serverless-functions/ip-app-screenshot.png) Things were going well. I got the layout sorted, I set up a custom map using React Leaflet and Mapbox. When it was time to fetch the data from the API, however, I ran into problems. Frontend Mentor had suggested using the [IP Geolocation API by IPify](https://geo.ipify.org/) to get information based off an IP address or domain. If you sign up for a free account with IPify and paste `https://geo.ipify.org/api/v1?apiKey=YOUR_API_KEY` into your url bar, it'll send back JSON with information about your IP address, your location, and your ISP provider. But if you try to make a HTTP request to this API from your client-side code, you'll get a message about CORS. ![CORS message](/images/posts/how-to-overcome-cors-with-serverless-functions/cors-message.png) ### What is CORS? [CORS (Cross Origin Resource Sharing)](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) is a mechanism that uses HTTP headers to give a browser permission to access resources from a server that's different from the server of the website making the request. It exists for a very good reason: **security**. You don't want some random website to be able to ping your server and get sensitive data from it. To prevent this, browsers restrict cross-origin HTTP requests initiated from client-side scripts by default. You need to specify which urls can access data from your server by making sure the correct CORS headers get sent with each request. But you can't just change the CORS settings on someone else's server because that would defeat the whole point of CORS as a security layer. ### CORS Proxies The solution that most resources recommended is to use a proxy, another server that will receive the request from your browser, pass it on to the server you're trying to access, and then pass that server's response back to you. This way the entire request response process occurs server-side and isn't subject to CORS. There are a number of CORS proxies you can use, such as [crossorigin.me](https://corsproxy.github.io/) or [CORS Anywhere](https://cors-anywhere.herokuapp.com/corsdemo). But I didn't want to rely on a third-party proxy. After all, they can see all the data that you pass to them and could stop working at any time. I also didn't want to run and manage my own Node app just to act as a proxy. While doing some research, I came across a blog post by <NAME> about [setting up a CORS proxy with Netlify](https://blog.jim-nielsen.com/2020/a-cors-proxy-with-netlify/) that promised to solve CORS issues using Netlify redirects without having to run your own proxy server or rely on some random one. ### Redirects Using redirect rules to proxy to an external service is something that Netlify actively supports. For example, you can set things up so that any requests to `/api/search` will be redirected to `https://api.example.com/search`. The [Netlify docs](https://docs.netlify.com/routing/redirects/rewrites-proxies/) explain how to do it. You can set redirect rules in a `_redirects` file: ``` /api/* https://api.example.com/:splat 200 ``` Or you can include them in your `netlify.toml` file which sets the configuration for your entire app on Netlify. ``` [[redirects]] from = "/api/*" to = "https://api.example.com/:splat" status = 200 force = true ``` If you want to test this out locally before deploying it, [Netlify Dev](https://www.netlify.com/products/dev/) lets you run Netlify locally on your machine. Armed with this information, I added the redirects rules to my `netlify.toml` file, ran the `netlify dev` command and it worked! Relieved to be making progress, I deployed the app to Netlify... and ran into a new issue. Everything worked locally but once the app was deployed I kept getting a [502 Bad Gateway](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/502) response, meaning that the proxy server received an invalid response from the server it was proxying to. ![Developer tools with 502 response message](/images/posts/how-to-overcome-cors-with-serverless-functions/error-response.png) Netlify have really great [Support Forums](https://answers.netlify.com/) and the good people there pointed me to potential solutions - setting specific headers on my redirects, checking for differences between my local environment and the build environment on Netlify. But none of this made a difference. A Netlify engineer was able to confirm that the problem was that the API was not responding to the request within 30 seconds. For proxy rewrites, Netlify closes the connection in 30 seconds and since the request wasn't complete by then, it returns a 502. They suggested I move my code into a serverless function and see if that would resolve the issue. ### Solution - Serverless Functions Serverless functions let you write server-side code that can work like an API endpoint, run automatically in response to events, or process complex jobs in the background, all without managing your own server. [Netlify Functions](https://www.netlify.com/products/functions/) make setting up and running serverless functions pretty straightforward. You create a `functions` directory in the root of your project and, inside that, a javascript file with the name of your function. ``` base-directory/ |- package.json |- node_modules |- functions/ hello.js ``` In the function's file, you export an async handler function which returns a status code and a body. These functions can carry out tasks such as fetching data from an API, sending automated emails, or validating user input, before sending back a response. ```js exports.handler = async (event, context) => { return { statusCode: 200, body: JSON.stringify({ message: "Hello World" }) }; }; ``` By default, to call a serverless function you make a request to `.netlify/functions/your-serverless-function`. But you can also use redirects in your `netlify.toml` to make this more concise. ``` [build] functions = "functions" [[redirects]] from = "/api/*" to = "/.netlify/functions/:splat" status = 200 ``` Now, requests to `/api/hello` will be the same as `.netlify/functions/hello`. ### Customizing Requests I moved the API request into a serverless function, ran Netlify Dev, and was immediately able to get back IP information. But for this particular project, I needed to be able to vary the requests I sent to the API. A request to `https://geo.ipify.org/api/v1?apiKey=YOUR_API_KEY` will send back information about the IP address that sent the request. On the other hand, a request to `https://geo.ipify.org/api/v1?apiKey=YOUR_API_KEY&ipAddress=SOME_IP_ADDRESS` will return information about the specified IP address. And finally, a request to `https://geo.ipify.org/api/v1?apiKey=YOUR_API_KEY&domain=SOME_DOMAIN` will return information about that domain. But how was I going to pass this data to the serverless function? Well, thankfully, <NAME> has a helpful tutorial on [customizing the request with serverless functions](https://explorers.netlify.com/learn/up-and-running-with-serverless-functions/customizing-the-request-with-serverless-functions). Basically, I used fetch to make a POST request to the serverless function, passing the search input's value as the body of the request. ```js // App.js const res = await fetch(`/api/getIpInfo`, { method: "POST", body: JSON.stringify({ searchTerm: ipAddress, }), }); const ipInfo = await res.json(); ``` Then in the serverless function, I extracted the search term from the body, used [validator.js](https://github.com/validatorjs/validator.js/) to check if it was an IP address or domain, and appended it to the API endpoint. ```js // getIpInfo.js const fetch = require("node-fetch"); const validator = require("validator"); exports.handler = async (event, context) => { const eventBody = JSON.parse(event.body); // Check for IP Address or domain let extension = ""; if (eventBody.searchTerm) { const { searchTerm } = eventBody; if (validator.isIP(searchTerm)) { extension = `&ipAddress=${searchTerm}`; } else if (validator.isURL(searchTerm)) { const domain = new URL(searchTerm); extension = `&domain=${domain.hostname}`; } } try { const res = await fetch(`${API_ENDPOINT}${extension}`); const data = await res.json(); return { statusCode: 200, body: JSON.stringify({ data }) }; } catch (error) { console.log(error); return { statusCode: 500, body: JSON.stringify({ error: "Failed fetching data" }), }; } }; ``` Success! Thanks to serverless functions, my app can now make requests to the IP Geolocation API from the browser without running into any CORS issues. ### Try It Yourself If you are running into CORS issues when making HTTP requests from the browser, try proxying via redirects and, if that doesn't work for you, there's never been a better time to learn about serverless functions. <NAME>'s [Up and Running with Serverless Functions](https://explorers.netlify.com/learn/up-and-running-with-serverless-functions) is a great place to get started. The code for my project is available on [GitHub](https://github.com/gerhynes/ip-address-tracker). You can also try out the [deployed app](https://goofy-spence-1d3ac9.netlify.app/). ### Further Resources - <NAME>, [Create your first Netlify Serverless Function!](https://www.youtube.com/watch?v=n_KASTN0gUE) - YouTube - <NAME>, [Up and Running with Serverless Functions](https://explorers.netlify.com/learn/up-and-running-with-serverless-functions) - Jamstack Explorers - [Cross-Origin Resource Sharing (CORS)](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) - MDN Web Docs - <NAME>, [Setup a CORS Proxy With Netlify](https://blog.jim-nielsen.com/2020/a-cors-proxy-with-netlify/) - jim-nielsen.com - <NAME>, [Exploring Netlify Redirects](https://explorers.netlify.com/learn/exploring-netlify-redirects) - Jamstack Explorers <file_sep>--- title: NASA Astronomy Picture of the Day date: "2020-10-06" description: "An app which displays daily images and videos from NASA's APOD API. Built as a present for my NASA-loving wife." slug: nasa-apod repoUrl: https://github.com/gerhynes/nasa-apod siteUrl: https://julie-nasa.netlify.app/ tags: ["React", "Gatsby", "APIs", "PWA"] image: /images/projects/nasa-apod/nasa-apod.png --- ### Project Purpose and Goal This project came about because two things coincided. I was looking to practice working with APIs in React and I wanted to make an app for my wife. Since my wife is a huge NASA fan (she has the ISS Tracker on her phone), I decided to use NASA's [Astronomy Picture of the Day API](https://api.nasa.gov/) to make her an app to view some of NASA's stunning photography. ### Tech Stack I chose to build the app with [Gatsby](https://www.gatsbyjs.com/) since it's a technology I want to get better at and it builds in certain performance wins such as code splitting. For the sake of reliability and accessibility, I decided to use an established third-party React component, [react-datepicker](https://github.com/Hacker0x01/react-datepicker) to select dates. I used [Axios](https://github.com/axios/axios) instead of the fetch API to make requests to NASA's API as it made error handling more straightforward. ### Problems and Thought Process Sometimes the Astronomy Picture of the Day would be a video, so I created a `Video` component and conditionally rendered different components depending on the media type returned from the API. When the date input changes, it can take a moment for the API to return the new data and render it to the page, especially the new image or video. To convey a sense of progress and prevent a mismatch between new text and an older image, I implemented a custom Skeleton loading component. ![Skeleton components while API data loads](/images/projects/nasa-apod/skeleton-screen.png) ### Lessons Learned By the end of this project I had a better understanding of working with `useEffect` and promises to fetch data from an API, especially in terms of parsing data and error handling. I also developed a better appreciation of the importance of UX in terms of communicating what the app was currently doing and ensuring the UI updated in a coherent manner. <file_sep>import { useState, useEffect } from "react"; // Custom hook to format dates on client side only // Formatting dates serverside can cause hydration issues const useFormattedDate = (date: string) => { const [formattedDate, setFormattedDate] = useState(""); useEffect(() => setFormattedDate(new Date(date).toLocaleDateString()), []); return formattedDate; }; export default useFormattedDate; <file_sep>--- title: "How to Get Unstuck When Following a Programming Tutorial" linkText: "getting unstuck" date: "2021-07-28" slug: get-unstuck-following-a-tutorial description: "Figure out where you went wrong and how you're going to fix it." isPublished: true tags: ["Learning"] image: /images/posts/get-unstuck-following-a-tutorial/get-unstuck-header.png --- You know the feeling, right? You're following a programming tutorial, pouring new knowledge and skills into your head. Life is good. And then, suddenly, it's not. Something breaks. Your screen is covered in a less-than-helpful error message, your terminal is printing warnings about things you've never heard of, and your code has fallen over in a heap. Even with the most well-paced and clear tutorials, you will get stuck. I still do, all the time. It's frustrating, but it's not the end of the world. It might not feel like it, but it can be a great opportunity to learn. With experience, I've gotten better at getting unstuck, and I'd like to share a few methods I've collected for pushing through these challenges and getting back on track. ### Read, Search, Ask I've learned debugging tips from a wide range of sources but the foundation of my process for getting unstuck comes from freeCodeCamp's [Read, Search, Ask methodology](https://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck-coding/19514). When you get stuck, their advice is to: - Read the documentation or error - Search Google - Ask your friends for help This is a good strategy for three reasons: 1. It will minimize the amount of time you spend stuck, 2. It will maximize your chance of learning from the problem, 3. It will help you to be respectful of other people's time when you ask them for help. This is still the core of my process for getting unstuck but I want to expand on what exactly I do when I **Read**, **Search** and **Ask**. ### 1. Read #### Read the Error Message ![An error message from a Node app with Mongoose](/images/posts/get-unstuck-following-a-tutorial/node-mongoose-error.png) Is there an error message yelling at you? Great! It might not seem it, but error messages are there to help you. It would be worse if your code just failed silently and left you none the wiser. Yes, sometimes error messages will be totally unhelpful, giving you no more information than "something went wrong". But other times the error message will point you on your way. If you see `TypeError: Cannot read property 'length' of undefined`, check the variable that's showing up as undefined. Look at the filename and line number and see what's going on there. But, bear in mind, where your code crashed is where the error happened, not necessarily where the problem was first introduced. Maybe the error happened in your `getUsers()` function, but the problem started in a `checkAuthentication()` function that then called `getUsers()`. Follow the call stack and see how far you can get. If the error message contains things you don't understand, don't panic, that's when you turn to Google (more on this below). #### Read Your Code Sometimes it feels like 90% of bugs are caused by one character being wrong; a typo in a variable or function name, a missing closing parentheses or bracket. Look for these. Extensions like [Bracket Pair Colorizer](https://marketplace.visualstudio.com/items?itemName=CoenraadS.bracket-pair-colorizer) can make this easier to spot. If the code you can see looks ok, try to surface the values that aren't immediately visible. Maybe a value is updating in the UI but isn't getting saved to the database. Drop a `console.log()` into both your frontend and backend code. If the value changed, or failed to change, at some point, work backwards and try to find where the disconnect happened. #### Read the Instructor's Code It's always helpful when an instructor provides a GitHub repo or includes downloadable files. If you have this, open it up and start comparing your code and theirs. Download their code and open it in your editor. Sometimes seeing their code with the same syntax highlighting as yours can help to make the differences stand out. [Diffchecker](https://www.diffchecker.com/) is also useful when you're comparing two versions of the same code line by line. Narrow down the amount of code you need to read. Comment out all the code you just wrote. Uncomment it step by step and see when it breaks again. If you're working with components, comment out every component and gradually reintroduce them. Maybe it was the `Header` rather than the `RegistrationForm` that was causing the problem. #### Read the Documentation ![Node.js Documentation](/images/posts/get-unstuck-following-a-tutorial/nodejs-documentation.png) When you're learning a technology for the first time, going from a tutorial to the docs can feel like diving into the deep end. Not all docs are well written or organized. Not all docs have good search functionality. But this is where a lot of your learning will happen. Reading the docs forces you to try to understand the technology you're using rather than just passively copying the tutorial. This is harder but also much more beneficial. The docs are a lifesaver when the syntax or the API has changed since the tutorial was created. You could have banged your head on the keyboard for hours but it turns out that you just need to change `if (process.browser)` to `if (typeof window !== "undefined")`. Check which version of a library or framework the tutorial was using. If version 3.0 has replaced version 2.0, look for a **migration guide** to help you get your code up to date. Now you'll not just have a working project again, but you'll have a better understanding of the underlying tools and technologies. ### 2. Search ![Google search for "Why isn't my code working?"](/images/posts/get-unstuck-following-a-tutorial/google-search-code-not-working.png) Ok, you've read your code, the instructor's code and the docs. Time to turn to Google. Thankfully, you are almost certainly not the first person to run into this specific problem. If a technology has existed long enough for there to be tutorials, then other people have already run into problems with it and written questions and answers that you can find. Don't feel guilty about googling. Every developer does it, from newbies to veterans. <NAME> has a great video on [The Google History of a High-Paid Senior Engineer](https://www.youtube.com/watch?v=LW9pT246LrI) which shows how often skilled and knowledgeable engineers google even basic concepts. Googling is a skill that you will develop with time and practice. There's a useful post from <NAME> on [how to get better at googling as a developer](https://betterprogramming.pub/11-tricks-to-master-the-art-of-googling-as-a-software-developer-2e00b7568b7d). Here, I'll focus on four ways to search more effectively: 1. Be as specific as possible 2. Include the error messages 3. Limit it to the last year or two 4. Search within specific sites #### Be as specific as possible ![Google search for ruby, excluding jewellery](/images/posts/get-unstuck-following-a-tutorial/google-search-ruby.png) You're following a tutorial on a specific technology. Put that at the start of your search. If you're using just JavaScript, start your search with "JavaScript". If you're using React or Vue, start with them. If you're using Next or Nuxt, put them as your first keyword. Be specific. One pattern I've seen is to structure your search like this: `LANGUAGE/FRAMEWORK VERB KEYWORDS`. This seems to provide better autocomplete suggestions from Google. If you're having an issue with a font not loading in a Gatsby site that uses styled-components, search for something like `styled-components Gatsby load fonts`. If you're getting irrelevant results, you can use `-` to remove unwanted terms from your search: `KEYWORD -UNWANTED_WORD`. For example, if you're stuck on a Ruby tutorial, include `-jewellery`, or `-jewelry` if you prefer, in your search to filter out results about the precious stone rather than the programming language. #### Include the error message ![Google search for React error message](/images/posts/get-unstuck-following-a-tutorial/google-search-react-error.png) If you got an error message and it wasn't enough to tell you what was wrong with your code, it might still prove useful in helping you find a resource that can help you. Now, error messages will often include a lot of information that is specific to your application or your machine. Remove this or it might prevent you from finding similar results. Don't copy the entire error message with the stack trace. <NAME> offerd [this advice](https://twitter.com/james_roe/status/948706229785739264): > error code -> error message -> language -> library -> syntax would be my general guide, in descending order of usefulness with other keywords. I would recommend including the library/framework you are working with. For example, Node.js is used in a lot of build tools and you might get similar looking error messages even though you're using different technologies on top of Node. Search for `Nextjs ERROR_MESSAGE` rather than just `ERROR_MESSAGE`. Say you get this error message from a React app: ``` Uncaught Invariant Violation: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops. ``` I would search for `React Uncaught Invariant Violation: Maximum update depth exceeded.` The rest of the error message and the stack trace is React helping you to debug your code but it's too much detail to make for a good Google search. #### Limit it to the last year or two Programming resources go out of date fast and material from a couple of years ago might no longer be helpful to you. Using `:before` and `:after` in your search will limit the results to before of after a specific date: `KEYWORD after:DATE` I usually limit my searches to the last two years and sometimes just to the last month to check if some recent change to the library of framework may be causing the issue. #### Search within specific sites ![Google search within Mongoose.js documentation](/images/posts/get-unstuck-following-a-tutorial/google-search-mongoose.png) You can use Google to search within a specific site even if that site doesn't have a built-in search feature: `KEYWORD site:WEBSITE_URL`. This can be handy if you're trying to search through documentation. If the tutorial is on a site with comments (such as YouTube, Medium or Dev.to), look there. Several times I've crossed my fingers and scrolled down, hoping someone else had already run into the same issue and gotten an answer. If the learning resource you're using has a forum, Slack or Discord, search them. Include the section or video title in your search terms. These will also be great places to ask questions (more below). I've found GitHub issues to be particularly useful when I run into problems with libraries and frameworks. If you're experiencing a problem with React, Angular or Vue, someone else likely has too. That said, when you find your exact problem in an open GitHub issue, with no sign of being resolved, it can be a bit demoralizing, so your mileage may vary. ### 3. Ask ![freeCodeCamp forum](/images/posts/get-unstuck-following-a-tutorial/freecodecamp-forum.png) Asking for help can be intimidating. You're exposing yourself to the scrutiny of others. Maybe you're worried about wasting someone else's time or worried about looking foolish if the solution turns out to be "obvious" in hindsight. Imposter syndrome can rear its head here. If you're intimidated to post a question online, try [Rubber Duck Debugging](https://en.wikipedia.org/wiki/Rubber_duck_debugging) first. Explain your code line by line out loud to your cat, a desk lamp or the ceiling. Sometimes, explaining a problem can jolt your brain into offering a solution. Remember, if you've made a genuine effort to understand a problem before asking for help, you have no reason to feel embarassed or guilty. Some sites - I'm thinking of Stack Overflow and Reddit - can be hostile, but there are others that are much friendlier for learners. If you're looking for a safe place to ask questions, head to the places where other learners are. Learning resources often have a forum - [freeCodeCamp](https://www.freecodecamp.org/), [Treehouse](https://teamtreehouse.com/), and [Codecademy](https://www.codecademy.com/#) all do - and I can speak from experience that there are plenty of people there who are happy to help you get unstuck with those courses. If you're following a tutorial on YouTube, Dev.to or Medium, post your question in the comments. If the instructor doesn't get back to you, one of the other learners might. I have to admit, I'm often reluctant to ask questions online. I don't want to look inept or to annoy anyone. So when I do ask questions, I try to do the following: 1. Include specific details 2. Share what you've tried 3. Make your code available #### Include specific details Don't write "My app's not working. Help!". Try something more like "I've gotten to the part of the tutorial where we add the ability to update todos. I can mark a todo as completed in the app interface but when I reload the page it shows it as not completed. I've looked at the React developer tools and the state is updating so I think the problem is that the data's not getting saved to the database. It might be an issue with my updateTodo function. Has anyone else run into this?" I try to follow the pattern: - Here's what's meant to be happening. - Here's what's going wrong. - Here's what I've tried to fix it. #### Share what you've tried Sharing the steps you've tried is important for two reasons: 1. It shows that you're not wasting people's time by asking for help without having done any work yourself 2. It gives other people an idea of what you've already ruled out People will be much more likely to pitch in and help you if you show that you've given the problem your best and aren't expecting them to solve it for you. Sharing your steps will also help them to get up to speed with your code and save them from having to ask you several basic questions. #### Make your code available ![Codepen landing page](/images/posts/get-unstuck-following-a-tutorial/codepen.png) It will be much easier for someone to help you if they can see your code for themselves. By all means focus on the part of the code where you think the problem is, but also give them a link to the full project so they can read your code in context. There are so many services that let you share your code for free. Provide a link to a [Codepen](https://codepen.io/), [repl](https://replit.com/), [CodeSandbox](https://codesandbox.io/), or [GitHub](https://github.com/) repo so they can view it for themselves. If you're having issues with a build on Netlify or Vercel, give them the full error message and stack trace as well as a link to your project. It can also be really helpful to include clear screenshots of the problem, whether that's the error message or the weird layout problem you're encountering. The more context you can provide, the easier it will be for someone else to understand your code and offer help. ### Getting Stuck is Normal, and Can Be Beneficial Being frustrated is a natural part of programming and of learning any topic. If you never run into an issue, how do you know you're not just copying code without actually learning? It might be more enjoyable to follow a tutorial and have everything work first time, but you will learn the topic much more effectively and thoroughly if you are forced to think about what you are doing. Have a look at the theory of [deliberate practice](https://jamesclear.com/beginners-guide-deliberate-practice) to find out more about this. When you get stuck, it's ok to get frustrated, but don't stay frustrated. Take a break, go for a walk and clear your head. When you come back, work the problem. Remember that you have the skills and resources to get yourself unstuck. And remember, too, there are a lot of people who are more than happy to help you if you put the work in first. I hope this post was helpful. Best of luck with the next topic you're learning. ### Further Resources - <NAME>, [How to Get Unstuck When You Hit a Programming Wall](https://www.freecodecamp.org/news/how-to-get-unstuck/) - freeCodeCamp - <NAME>, [How to Google Search Error Messages](https://www.youtube.com/watch?v=1OX-mns8UJw&t=64s) - YouTube - <NAME>, [Read, Search, (Don't Be Afraid to) Ask](https://www.freecodecamp.org/news/read-search-dont-be-afraid-to-ask-743a23c411b4/) - freeCodeCamp - <NAME>, [How to Ask Effective Questions: A Practical Guide for Developers](https://www.freecodecamp.org/news/asking-effective-questions-a-practical-guide-for-developers/) - freeCodeCamp - <NAME>, [The Google History of a High-Paid Sr. Engineer](https://www.youtube.com/watch?v=LW9pT246LrI) - YouTube - <NAME>, [11 Tricks To Master the Art of Googling as a Software Developer](https://betterprogramming.pub/11-tricks-to-master-the-art-of-googling-as-a-software-developer-2e00b7568b7d) - BetterProgramming - Swyx, [How To Google Your Errors](https://dev.to/swyx/how-to-google-your-errors-2l6o) - Dev.to <file_sep>--- title: "How to Connect a Node App to MongoDB Atlas" linkText: "connecting to MongoDB Atlas" date: "2021-03-27" slug: connect-node-app-to-mongodb-atlas description: "A quick guide to getting your Node app talking to a cloud-based MongoDB database." isPublished: true tags: ["Node", "MongoDB"] image: /images/posts/connect-node-app-to-mongodb-atlas/node-mongodb-header.png --- MongoDB is a popular NoSQL database choice for Node apps. There's a reason that the acronyms MERN stack, MEAN stack and even MEVN stack exist to describe an app built on MongoDB, Express, a JavaScript framework (whether React, Angular or Vue), and Node. If you're learning how to work with MongoDB and Node, setting up a database on your own computer can be a little bit of a headache. Thankfully, MongoDB offer a cloud-based database platform, [MongoDB Atlas](https://www.mongodb.com/cloud/atlas). I recently built a few projects with Node and MongoDB Atlas and felt it might be useful to write up a quick guide to how to get the two to talk to each other. ### Step 1 - Set up your MongoDB Atlas Account and Cluster ![MongoDB Atlas account setup page](/images/posts/connect-node-app-to-mongodb-atlas/mongodb-atlas-account-setup.png) First things first, go to the [MongoDB Atlas website](https://www.mongodb.com/cloud/atlas) and create a free account. You can choose whatever name you want for your organization and project. Choose JavaScript as your preferred language. ![MongoDB Atlas create cluster page](/images/posts/connect-node-app-to-mongodb-atlas/mongodb-atlas-create-cluster.png) Next choose a free shared cluster. This will be enough for demos and small personal projects. When you're invited to create a starter cluster, you can leave the Cloud Provider and Region as the defaults (unless you have strong feelings about them) and click **Create Cluster**. ![MongoDB Atlas dashboard](/images/posts/connect-node-app-to-mongodb-atlas/mongodb-atlas-dashboard.png) You'll now be brought to your admin dashboard. Click on **Create a New Cluster**. This can take a couple of minutes. Once your cluster is ready, click on the **Connect** button in the sandbox. ![MongoDB Atlas IP and user setup](/images/posts/connect-node-app-to-mongodb-atlas/mongodb-atlas-ip-user.png) Allow access from all IP addresses. This would be a terrible idea in production but this is just a demo for learning purposes. Next, create a new user for the database and choose a password. Store these somewhere safe, like your password manager. ![MongoDB Atlas connect modal](/images/posts/connect-node-app-to-mongodb-atlas/mongodb-atlas-connect-modal.png) Now click on **Choose a connection method**. Select **Connect your application** ![MongoDB Atlas database URI selection](/images/posts/connect-node-app-to-mongodb-atlas/mongodb-atlas-connect-cluster.png) Under **Add your connection string into your application code** you'll see a URI with the format `mongodb+srv://<username>:<password>@<cluster-name>.mongodb.net/<db-name>?retryWrites=true&w=majority`. The username, cluster-name and db-name fields will be automatically filled out. Copy this URI to your clipboard. You'll need it in a minute. ### Step 2 - Make a Node App if you don't already have one If you don't have a Node app to hand, you can [download the starter code for a very basic Express app from this repo](https://github.com/gerhynes/node-mongodb-atlas/tree/starter-code). Run `npm install` to install Express, the only dependency. Your `app.js` file should look like this. ```js // app.js const express = require("express"); const port = 3000; const app = express(); app.get("/", (req, res) => { res.send("Hello World!"); }); app.listen(port, () => { console.log(`Your app is listening on port ${port}`); }); ``` In your command line, run `node app.js` and you should see the confirmation message that your app is listening on a particular port. ### Step 3 - Store Environmental Variables Remember your MongoDB Atlas URI? You don't want to just paste that into your code where it could get committed to Git and potentially publicly exposed. Instead, we're going to save it as an environmental variable. Install the [dotenv package](https://www.npmjs.com/package/dotenv) with `npm install dotenv`. Create a `.env` file in the root of your project, paste in your URI, and assign it to a `DB_URI` variable. Make sure your version includes your password as well as your username, cluster name and database name. ```js // .env DB_URI=mongodb+srv://<username>:<password>@<cluster-name>.mongodb.net/<db-name>?retryWrites=true&w=majority ``` ### Step 4 - Configure your Database Connection To keep things organized, I keep my database config in its own file. In the root of your project, create a `db.js` file. This will contain all the configuration for connecting to your database. We're going to use [Mongoose](https://mongoosejs.com/) to handle connecting to our database. Install Mongoose with `npm install mongoose` and import it into `db.js`. Import your database URI as `db` from `process.env.DB_URI`. Create a `connectDB` function. Make sure you mark it as an `async` function as it will take some amount of time to connect to your database. Inside `connectDB`, create a `try-catch` block to handle any errors that occur. In the `try` block, await `mongoose.connect()`. Pass it the `db` variable and a settings object. In the settings object, set `useNewUrlParser` and `useUnifiedTopology` to `true`. This will prevent Mongoose from giving you warnings. Mongoose explains the warnings in their [documentation](https://mongoosejs.com/docs/deprecations.html). It's also a good habit to `console.log` a success message to tell you you've connected to your database. I once spent an hour trying to debug a database connection simply because I wasn't telling myself it was connected. In the `catch` block, `console.error` any error you receive and use `process.exit(1)` to terminate the process if an error occurs. Finally, export the `connectDB` function. Your `db.js` file should now look like this. ```js // db.js const mongoose = require("mongoose"); const db = process.env.DB_URI; async function connectDB() { try { await mongoose.connect(db, { useNewUrlParser: true, useUnifiedTopology: true, }); console.log("MongoDB connected"); } catch (error) { console.error(error.message); process.exit(1); } } module.exports = connectDB; ``` ### Step 5 - Time to Connect to Your Database In your `app.js` file, require `dotenv` and call the `config` method on it. Import the `connectDB` function and call it. ```js // app.js require("dotenv").config(); const express = require("express"); const connectDB = require("./db"); const port = 3000; // Connect to database connectDB(); const app = express(); app.get("/", (req, res) => { res.send("Hello World!"); }); app.listen(port, () => { console.log(`Your app is listening on port ${port}`); }); ``` Congratulations, your Node app is now connected to your MongoDB Atlas cluster. If you run `node app.js`, you'll see two messages printed to your console: that your app is running and that you've connected to your database. From here you can start to write schemas and perform CRUD operations with your data. If you ran into any issues, [the code for this demo app](https://github.com/gerhynes/node-mongodb-atlas) is in this repo. ### More Resources - [MongoDB Atlas Documentation](https://docs.atlas.mongodb.com/) - MongoDB, [Getting Your Free MongoDB Atlas Cluster](https://youtu.be/rPqRyYJmx2g) - YouTube - MongoDB, [MongoDB Atlas Tutorial - How to Get Started](https://www.freecodecamp.org/news/get-started-with-mongodb-atlas/) - freeCodeCamp <file_sep>--- title: "Turning a Personal Site into a Portfolio" linkText: "making a portfolio" date: "2020-10-30" slug: turning-a-personal-site-into-a-portfolio description: "How I rebuilt my personal site to better communicate my abilities." isPublished: true tags: ["Portfolio"] image: /images/posts/turning-a-personal-site-into-a-portfolio/portfolio-header.png --- Personal websites are often neglected. In my case, my site hadn't had a redesign in 2 years 😬. Since then I've built dozens of small projects and learned a number of new technologies. But my site didn't reflect any of that. ### The old site and its problems The old site was a pretty accurate snapshot of my technical abilities at the time. It was a purely static site, with just a little bit of JavaScript for interactions and Sass for styling. I was in the middle of learning CSS Grid and about to start a long period of getting better at JavaScript. I hadn't even touched a frontend framework like React. The main problem was that the site didn't have a clear message. The old landing page said "I'm a self-taught web developer and programmer". That's fine, but it's pretty generic, and doesn't really tell the visitor what I do or where my interests lie. The site also failed the "show, don't tell" rule of writing. I did what everyone else seemed to be doing and listed the technologies I had experience with and linked to some projects. But I failed at properly demonstrating those skills or explaining why these projects mattered, how I had built them, or what I had learned. ![Screenshot of skills section from old site](/images/posts/turning-a-personal-site-into-a-portfolio/old-site-skills.png) ### Fixing these problems After thinking about it, I decided that a portfolio site should quickly convey three things: - Your personality - Your professional interests - Your technical skills In the last year I've fallen down the JavaScript rabbit hole and gotten really interested in the [Jamstack](https://jamstack.org/) as an architecture for building sites and web apps. My new landing page reflects this: "I make fast, modern sites and apps using the Jamstack and fullstack JavaScript". ![Old and new sites side by side](/images/posts/turning-a-personal-site-into-a-portfolio/old-site-new-site.png) When I rebuilt the site I intended for it to better demonstrate my current interests and technical skills, so clearly it should have a much greater focus on JavaScript. I settled on a Jamstack site built with: - [Gatsby](https://www.gatsbyjs.com/) - [MDX](https://mdxjs.com/) - [styled-components](https://styled-components.com/). Gatsby helps make the site fast by default, with built-in code splitting and image optimization. Markdown provides a pretty pleasant writing experience (at least for me), and MDX gives me the option to embed React components if I ever want to include videos, graphs or Codepens. styled-components offer many of the benefits of Sass, such as code organization, nesting and variables, with the added advantage that the CSS is scoped to individual components. Sure, this might be overkill for a personal website, but I took comfort from <NAME>'s post, when he says [You're Allowed to Overengineer Your Blog](https://www.colbyfayock.com/2020/07/youre-allowed-to-overengineer-your-blog/), especially in order to solidify the technologies you're learning. I've also made a concerted effort to update my personal projects from basic detail cards into proper case studies. Here I followed <NAME>'s [advice on making a more effective portfolio](https://joshwcomeau.com/effective-portfolio/), by fleshing out the project's goals, tech stack, any pain points encountered, and the lessons learned. ![Screenshots of old and new project descriptions](/images/posts/turning-a-personal-site-into-a-portfolio/project-comparisons.png) Lastly, in an attempt to write more, I've added this writing section. If you've read <NAME>'s [A Mind for Numbers](https://barbaraoakley.com/books/a-mind-for-numbers/) or taken her excellent course on [Learning how to Learn](https://www.coursera.org/learn/learning-how-to-learn), you'll know that trying to explain concepts clearly in writing is a really effective way to check if you actually understand them and also make those concepts stick. Some of these posts might even prove useful for other people. I've heard that if a podcast can make it past 7 episodes, it'll probably survive. Let's see if I can write more than 7 posts here. <file_sep>--- title: Reading Habit date: "2021-08-16" description: "A fullstack Jamstack app with a serverless database to help me keep track of the books I'm reading." slug: reading-habit repoUrl: https://github.com/gerhynes/reading-habit siteUrl: https://reading-habit.vercel.app/ tags: ["Nextjs", "FaunaDB", "Auth0", "TailwindCSS"] image: /images/projects/reading-habit/reading-habit.png --- ### Project Purpose and Goal For the last few years I've keep track of every book I read in whatever pocket notebook I was using at the time. ![Book lists for 2020 and 2021](/images/projects/reading-habit/book-lists.png) After moving apartment twice and nearly losing the notebooks, I decided I needed a digital back up of my reading list. A spreadsheet would have worked but where's the fun in that. At the same time, I was learning Next.js and wanted to build a fullstack Jamstack app with it. This project was a chance to accomplish both goals at once. I decided to take the app I was making while following James Q Quick's [Fullstack Jamstack](https://www.youtube.com/watch?v=TNKzKtNTjls) course, change the data source from Airtable to FaunaDB, and build on the additional functionality I needed. ### Tech Stack I wanted [Next.js](https://nextjs.org/) as the framework for the app as it combines the responsiveness of React on the frontend with the ability to use serverless functions via Next's API routes. I chose [FaunaDB](https://fauna.com/) as the database since its API-first approach suited the serverless nature of Next.js. [Auth0](https://auth0.com/) had just released a new Next.js SDK and I was eager to see if it really made adding authentication to a Next app as straighforward as it claimed. [Tailwind CSS](https://tailwindcss.com/) made sense for styling as it let me quickly prototype the app but didn't commit me to a particular design system. ### Problems and Thought Process I introduced more than one bug by not keeping better track of the shape of the data being stored in Fauna. When new books were added they didn't have an id and the app's state was out of sync with the database. Importantly, documents in Fauna are stored with a Ref (containing their collection and a unique id) and a timestamp. The document's data is then stored in a nested data object. ```js { "ref": Ref(Collection("books"), "305662176059720261"), "ts": 1628171790980000, "data": { "author": "<NAME>", "title": "Factfulness", "completed": true, "dateCompleted": "2021-07-17", "userId": "google-oauth2|xxxxxxxxxxxxxxxxxxxxx" } } ``` I tackled this problem by using the debugger to track the values of a book as it was created, saved to the database, fetched back from it, and rendered to the UI. It turned out I wasn't extracting the id from the Ref and, additionally, I was saving the edited data into the top level of the document, not the data object. From this I learned more about debugging app state and API requests, as well as manipulating objects. ### Lessons Learned I made this app for my own use but began to think about how usable it would be for other people. This made me consider user experience more fully. I planned out the user flow from the landing page to adding a book and realized I needed to make the following changes: - First, adding a simple landing page explaining the app rather than immediately forcing the user to log in. - On login, redirecting to the current user's book list. - If no books were present, showing a prompt to add a new book. ![App interface when no books have been added](/images/projects/reading-habit/empty-state.png) I also spent time thinking about how to manage the edit flow. I considerd a separate edit page (but this would involve additional API calls to the database to generate these pages) or a modal (which raised accessibility problems). Instead, I incorporated the edit form into the Book component, minimizing context switching for the user. ![Edit form](/images/projects/reading-habit/edit-form.png) I finished this project with a better understanding of the technologies involved, a renewed enthusiasm for building with the Jamstack, and a greater appreciation of the importance of user experience.
dd6036d91b5ce7ddf3fb59ffa8d9eb69dd34f1b8
[ "Markdown", "TypeScript" ]
11
Markdown
GK-Hynes/personal-site
e7f48bbbc2a1112b68d858c10806c60d6208b5ab
46f5a3f598e4e8763310c6115c810a5a0c7421ca
refs/heads/master
<repo_name>zishu-zy/nkyWebServer<file_sep>/controllers/home.go package controllers import ( "nkyWebServer/models" "github.com/astaxie/beego" ) // MainController 主控制 type MainController struct { beego.Controller } // Get 方法 func (c *MainController) Get() { if !checkAccountCookie(c.Ctx) { c.Redirect("/login", 302) return } c.TplName = "home.html" nodes, err := models.GetAllNodes() if err != nil { beego.Error(err) return } c.Data["Nodes"] = nodes nodeDatas, err := models.GetAllNodeData() if err != nil { beego.Error(err) return } c.Data["NodeDatas"] = nodeDatas c.Data["IsHome"] = true } <file_sep>/controllers/login.go package controllers import ( "io" "nkyWebServer/models" "github.com/astaxie/beego" "github.com/astaxie/beego/context" "github.com/astaxie/beego/orm" ) type LoginController struct { beego.Controller } func (c *LoginController) Get() { // 判断是否为退出操作 if c.Input().Get("exit") == "true" { c.Ctx.SetCookie("uname", "", -1, "/") c.Ctx.SetCookie("pwd", "", -1, "/") c.Redirect("/login", 302) return } c.TplName = "login.html" } func (c *LoginController) Post() { uname := c.Input().Get("uname") pwd := c.Input().Get("pwd") autoLogin := c.Input().Get("autoLogin") == "on" beego.Info(uname, pwd, autoLogin) // 验证表单 if models.CheckAccount(uname, pwd) { maxAge := 0 if autoLogin { maxAge = 1<<31 - 1 } c.Ctx.SetCookie("uname", uname, maxAge, "/") c.Ctx.SetCookie("pwd", pwd, maxAge, "/") io.WriteString(c.Ctx.ResponseWriter, "true") return } else { // c.EnableRender = false // c.Redirect("/login", 302) io.WriteString(c.Ctx.ResponseWriter, "账户密码错误") return } // 重定向 // c.Redirect("/", 302) } func checkAccountCookie(ctx *context.Context) bool { ck, err := ctx.Request.Cookie("uname") if err != nil { beego.Error(err) return false } uname := ck.Value ck, err = ctx.Request.Cookie("pwd") if err != nil { return false } pwd := ck.Value o := orm.NewOrm() var dbpwd string err = o.Raw("select f_userPwd from tb_manager where f_userName=?", uname).QueryRow(&dbpwd) if err != nil { beego.Info(err.Error()) return false } if pwd == dbpwd { return true } return false } <file_sep>/routers/router.go package routers import ( "nkyWebServer/controllers" "github.com/astaxie/beego" ) func init() { beego.Router("/", &controllers.MainController{}) beego.Router("/ws", &controllers.WebSocketController{}) beego.Router("/login", &controllers.LoginController{}) beego.Router("/login/ajax", &controllers.LoginAjaxController{}) } <file_sep>/main.go package main import ( "nkyWebServer/models" _ "nkyWebServer/routers" _ "github.com/go-sql-driver/mysql" "github.com/astaxie/beego/orm" "github.com/astaxie/beego/toolbox" "github.com/astaxie/beego" ) func init() { // 注册数据库,最大连接数30 err := orm.RegisterDataBase("default", "mysql", "root:zy0802@tcp(localhost:3306)/db_test?charset=utf8", 30) if err != nil { beego.Error(err) } models.RegisterDB() } func main() { toolbox.StartTask() defer toolbox.StopTask() beego.Run() } <file_sep>/models/model.go package models import ( "github.com/astaxie/beego" "github.com/astaxie/beego/orm" ) type Node struct { ID int `orm:"column(f_nodeID)" json:"NodeID"` Name string `orm:"column(f_nodeName)" json:"NodeName"` } type Data struct { EnvValue float64 `orm:"column(f_value)" json:"EnvValue"` EnvName string `orm:"column(f_envName)" json:"EnvName"` EnvUnit string `orm:"column(f_envUnit)" json:"EnvUnit"` } type NodeData struct { Node `json:"Node"` EnvData []Data `json:"EnvData"` } func RegisterDB() { orm.RegisterModel(new(Node)) } func CheckAccount(uname, pwd string) bool { var dbpwd string o := orm.NewOrm() err := o.Raw("select f_userPwd from tb_manager where f_userName=?", uname).QueryRow(&dbpwd) if err != nil { beego.Info(err.Error()) return false } if pwd == dbpwd { return true } return false } func GetAllNodes() (nodes *[]Node, err error) { nodes = new([]Node) o := orm.NewOrm() _, err = o.Raw("select f_nodeID,f_nodeName from tb_node").QueryRows(nodes) return } func GetAllNodeData() (nodeDatas []*NodeData, err error) { nodes, err := GetAllNodes() nodeDatas = make([]*NodeData, len(*nodes)) o := orm.NewOrm() for index, _ := range nodeDatas { nodeDatas[index] = &NodeData{Node: (*nodes)[index]} _, err = o.Raw(`select tb_vr.f_value,tb_ep.f_envName,tb_ep.f_envUnit from tb_valueRealTime tb_vr, tb_envParameter tb_ep WHERE tb_vr.f_envID=tb_ep.f_envID and tb_vr.f_nodeID=?;`, nodeDatas[index].ID).QueryRows(&(nodeDatas[index].EnvData)) } return } <file_sep>/controllers/loginAjax.go package controllers import ( "io" "github.com/astaxie/beego" ) type LoginAjaxController struct { beego.Controller } func (c *LoginAjaxController) Get() { io.WriteString(c.Ctx.ResponseWriter, "账户密码错误") } <file_sep>/controllers/ws.go package controllers import ( "log" "nkyWebServer/models" "time" "github.com/astaxie/beego" "github.com/gorilla/websocket" ) type WebSocketController struct { beego.Controller } var upgrader = websocket.Upgrader{} var mCH = make(chan bool) func (c *WebSocketController) Get() { c.EnableRender = false ws, err := upgrader.Upgrade(c.Ctx.ResponseWriter, c.Ctx.Request, nil) if err != nil { log.Fatal(err) } defer ws.Close() defer beego.Info("退出ws") realtimeSend(ws) } func realtimeSend(conn *websocket.Conn) { for { time.Sleep(time.Second * 10) nodeDatas, err := models.GetAllNodeData() for _, nodedata := range nodeDatas { if err = conn.WriteJSON(nodedata); err != nil { beego.Error(err) return } } } }
3b968cb40650849c5d7d4d27e461f6789ff3962e
[ "Go" ]
7
Go
zishu-zy/nkyWebServer
7f5c3447576dd13eb4bef13e7d6b2cbd055d154e
d96c5c74fd46c4c52b0645004db695749689b991
refs/heads/master
<repo_name>davidsoloman/crunchbase_women_founders<file_sep>/data_assembly.R #' Extract all data from a specific Crunchbase table get_cb_data <- function(tbl, con, limit = NULL) { sql <- "select * from %s" %>% sprintf(tbl) if (!is.null(limit)) sql <- "%s limit %s" %>% sprintf(sql, limit) df <- suppressWarnings(dbGetQuery(con, sql)) df %>% tbl_df } #' Assemble founders data assemble_founders_data <- function(relationships, people, objects) { # 'Founder' or 'founder' in title founders <- relationships %>% select(person_object_id, relationship_object_id, title, end_at) %>% filter(!is.na(str_match(title, '[fF]ounder'))) # Ensure unique by picking most recent record by end_at founders <- founders %>% mutate(end_at = as.Date(end_at)) %>% group_by(person_object_id) %>% arrange(desc(end_at)) %>% slice(1) %>% ungroup %>% select(-end_at) # Add founder name and company data founders <- founders %>% left_join(people %>% select(object_id, first_name), by = c("person_object_id" = "object_id")) %>% left_join(objects %>% filter(entity_type == 'Company') %>% select(id, company = name, region, founded_at, tag_list), by = c("relationship_object_id" = "id")) # Compute gender data for all first names genders <- gender(founders$first_name %>% unique) # Add gender data back to founders founders <- founders %>% left_join(genders %>% select(name, gender, proportion_female), by = c("first_name" = "name")) founders %>% rename(person_id = person_object_id, company_id = relationship_object_id) } #' Assemble investment rounds data assemble_rounds_data <- function(funding_rounds, investments, objects, years, round_codes) { # Extract investors investors <- objects %>% filter(entity_type == 'FinancialOrg') %>% select(investor_id = id, investor = name) # Join funding to investments and investors rounds <- funding_rounds %>% transmute(funding_round_id, company_id = object_id, funding_date = as.Date(funded_at), funding_year = year(as.Date(funded_at)), funding_round_code) %>% inner_join(investments %>% select(funding_round_id, investor_id = investor_object_id), by = "funding_round_id") %>% inner_join(investors, by = "investor_id") # Filter for specific years and funding round codes rounds <- rounds %>% filter(funding_year %in% years) %>% filter(funding_round_code %in% round_codes) %>% mutate(funding_round_code = factor(funding_round_code, levels = round_codes)) # Remove duplicate investments in funding rounds by taking only the earliest rounds <- rounds %>% group_by(company_id, investor_id, funding_round_code) %>% arrange(funding_date) %>% slice(1) %>% ungroup rounds } #' Summarize gender summarize_gender <- function(df) { df %>% filter(!is.na(gender)) %>% summarize( num_companies = n_distinct(company_id), num_founders = n(), pct_female = mean(gender == 'female') * 100 ) } <file_sep>/README.md # Crunchbase Women Founders An analysis of women founders and the VCs that invest in them from the [Crunchbase © 2013 Snapshot](https://data.crunchbase.com/docs/2013-snapshot) dataset. <file_sep>/crunchbase_female_founders.Rmd --- title: "Get Crunchbase Data" output: html_document: code_folding: hide --- ```{r} needs(tidyverse, RMySQL, dbConnect, gender, lubridate, wordcloud, forcats, viridis, stringr, magrittr, assertr, knitr) source("data_assembly.R") ``` ```{r} # Connect to the local MySQL database with the Crunchbase 2013 data con <- dbConnect(MySQL(), user='root', dbname='mytestdatabase') # Geta all tables used cb_tables <- c("cb_funding_rounds", "cb_investments", "cb_objects", "cb_people", "cb_relationships") data <- cb_tables %>% map(get_cb_data, con) names(data) <- cb_tables # Assemble founders data founders <- assemble_founders_data( data$cb_relationships, data$cb_people, data$cb_objects) # Check that every founder appears only once per company stopifnot(founders %>% nrow == founders %>% select(person_id, company_id) %>% unique %>% nrow) # Assemble rounds data rounds <- assemble_rounds_data( data$cb_funding_rounds, data$cb_investments, data$cb_objects, years = 2009:2013, round_codes = c("seed", "a", "b", "c")) # Check that every investor / company / round appears only once stopifnot(rounds %>% nrow == rounds %>% select(company_id, investor_id, funding_round_code) %>% unique %>% nrow) # Join the two together and filter unknown gender combined <- rounds %>% inner_join(founders, by = "company_id") %>% filter(!is.na(gender)) { "%s founders rows" %>% sprintf(nrow(founders)) %>% writeLines "%s rounds rows" %>% sprintf(nrow(rounds)) %>% writeLines "%s combined rows" %>% sprintf(nrow(combined)) %>% writeLines } ``` ### name confidence ```{r} # Gender analysis confidence founders %>% mutate(confidence = ifelse(is.na(proportion_female), 'missing', ifelse(proportion_female > .95, 'female', ifelse(proportion_female < .05, 'male', 'uncertain')))) %>% group_by(confidence) %>% tally %>% ungroup %>% mutate(pct = n / sum(n)) ``` ### founder names ```{r} # Wordcloud of founder names df <- founders %>% group_by(first_name, gender) %>% tally %>% mutate(color = ifelse( is.na(gender), 'grey', ifelse(gender == 'female', 'green', 'orange'))) %>% ungroup %>% arrange(desc(n)) %>% slice(1:500) %>% mutate(s = sqrt(n)) r <- range(df$s) r <- r / max(r) * 1.5 wordcloud(df$first_name, df$s, colors = df$color, ordered.colors = TRUE, random.order = FALSE, scale = rev(r)) ``` ### Overall ```{r} # Overall summary statistics combined %>% select(investor_id, company_id, person_id, gender) %>% unique %>% # dedupe over rounds summarize( num_investments = n(), num_investments = n(), num_investors = n_distinct(investor_id), num_companies = n_distinct(company_id), num_founders = n_distinct(person_id), pct_female = mean(gender == 'female') * 100 ) ``` ### Number of female founders ```{r} combined %>% filter(!is.na(gender)) %>% select(person_id, gender) %>% unique %>% group_by(gender) %>% tally ``` ### Tags ```{r} tags <- combined %>% filter(!is.na(gender)) %>% mutate(is_female = gender == 'female') %>% group_by(company_id, tag_list) %>% summarize(any_female = any(is_female)) %>% filter(!is.na(tag_list)) split_tags <- function(s) data_frame(tag = str_split(s, ', ')[[1]]) tags <- tags %>% mutate(tags = tag_list %>% map(split_tags)) %>% select(-tag_list) %>% unnest(tags) tags %>% filter(tag != '' & !is.na(tag)) %>% group_by(tag) %>% summarize( num_companies = n(), pct_any_female = mean(any_female) * 100) %>% arrange(desc(num_companies)) %>% slice(1:50) %>% mutate(tag = tag %>% fct_reorder(pct_any_female)) %>% ggplot(aes(pct_any_female, tag)) + geom_segment(aes(xend = 0, yend = tag), colour = 'grey80', alpha = .8) + geom_point(aes(size = num_companies), colour = 'grey20', alpha = .8) + labs(x = "Percent Any Women Founder", y = "Crunchbase Tag", size = "Number of\nCompanies") + theme_minimal() + theme(panel.background = element_blank(), panel.border = element_blank(), panel.grid.major = element_blank(), panel.grid.minor = element_blank(), axis.line = element_blank()) + scale_x_continuous(breaks = seq(0, 60, by = 5)) ``` ### Number of investments in female founders ```{r} combined %>% filter(gender == 'female') %>% summarize_gender() combined %>% summarize_gender() ``` ### VC ```{r, fig.height = 5, fig.width = 8} # Top 100 VCs df_100_vcs <- combined %>% select(investor, company_id, person_id, gender) %>% unique %>% # dedupe over rounds group_by(investor) %>% summarize_gender %>% arrange(desc(num_companies)) %>% slice(1:100) df_100_vcs %>% arrange(desc(pct_female)) %>% mutate(investor = paste0(1:n(), ". ", investor)) %>% mutate(rank = 1:n()) %>% mutate(column = (rank - 1) %/% 20 + 1) %>% group_by(column) %>% arrange(desc(pct_female)) %>% mutate(col_rank = n():1) %>% ggplot(aes(pct_female, col_rank)) + geom_segment(aes(xend = 0, yend = col_rank), color = 'grey70') + geom_point(aes(size = num_companies), color = 'grey70') + geom_text(aes(x = 0, label = investor), adj = 0, nudge_y = .3, size = 2, color = 'grey20') + facet_grid(. ~ column) + theme(legend.position = 'none') + theme(panel.background = element_blank(), panel.border = element_blank(), panel.grid.major = element_blank(), panel.grid.minor = element_blank(), axis.line = element_blank()) + labs(x = "Percent Women Founders") ``` ```{r} "%s min companies" %>% sprintf(df_100_vcs %>% pull(num_companies) %>% min) "%s min founders" %>% sprintf(df_100_vcs %>% pull(num_founders) %>% min) "%s max founders" %>% sprintf(df_100_vcs %>% pull(num_founders) %>% max) ``` Bottom 10 VCs ```{r} df_100_vcs %>% arrange(pct_female) %>% slice(1:10) ``` Top 10 VCs ```{r} df_100_vcs %>% arrange(desc(pct_female)) %>% slice(1:10) ``` Examine examples ```{r} combined %>% filter(investor == 'Sutter Hill Ventures') %>% select(company_id, person_id, first_name, proportion_female, title) %>% unique %>% arrange(company_id, person_id) %>% kable ``` ### region ```{r} df <- combined %>% select(investor_id, company_id, person_id, gender, region) %>% unique %>% # dedupe over rounds group_by(region) %>% summarize_gender df %>% filter(region != 'unknown') %>% arrange(desc(num_companies)) %>% slice(1:15) %>% ggplot(aes(num_companies, pct_female)) + geom_point(aes(size = num_companies), colour = 'grey60') + geom_text(aes(label = region), nudge_y = .5) + scale_x_log10(lim = c(20, 1500)) + annotation_logticks(side = 'b') + theme(legend.position = 'none') + labs(x = "Number of Companies", y = "Percent Women Founders") ``` ### funding round ```{r, fig.height = 2.5, fig.width = 2.5} df <- combined %>% group_by(funding_round_code) %>% summarize_gender df %>% ggplot(aes(funding_round_code, pct_female)) + geom_bar(stat = 'identity', fill = 'grey60') + geom_text(aes(label = pct_female %>% round(1)), nudge_y = .5, colour = 'grey20', size = 3) + geom_text(aes(label = funding_round_code, y = 0), nudge_y = -.5, colour = 'grey20', size = 3) + labs(x = "Funding Round", y = "Percent Women Founders") + theme_minimal() + theme( panel.grid.major = element_blank(), panel.grid.minor = element_blank()) ``` ### year and month ```{r} df <- combined %>% mutate( year = year(funding_date), month = month(funding_date) ) %>% group_by(year, month) %>% summarize_gender df %>% ggplot(aes(month, pct_female, size = num_founders)) + geom_point(colour = 'grey30') + stat_smooth(se = FALSE, formula = y ~ 1, method = 'lm') + labs(x = "Funding Month", y = "Percent Women Founders") + facet_grid(. ~ year) + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()) + theme(legend.position = 'bottom') + scale_y_continuous(lim = c(0, max(df$pct_female))) + scale_x_continuous(breaks = 1:12) + theme(axis.text.x = element_text(size = 6)) ``` ### Top and Bottom 10 VC name distributions ```{r} top_invest <- df_100_vcs %>% arrange(desc(pct_female)) %>% slice(1:5) %>% pull(investor) bot_invest <- df_100_vcs %>% arrange(pct_female) %>% slice(1:5) %>% pull(investor) plot_invest_wordcloud <- function(cobined, invest, max_n) { df <- combined %>% filter(investor %in% invest) %>% select(person_id, first_name, gender) %>% unique %>% # dedupe over investors and rounds group_by(first_name, gender) %>% tally %>% mutate(color = ifelse( is.na(gender), 'grey', ifelse(gender == 'female', 'green', 'orange'))) %>% ungroup %>% arrange(desc(n)) %>% slice(1:500) %>% mutate(s = sqrt(n)) r <- range(df$s) r <- r / sqrt(max_n) * 1.5 wordcloud(df$first_name, df$s, colors = df$color, ordered.colors = TRUE, random.order = FALSE, scale = rev(r), min.freq = 0) } set.seed(1) opar <- par(mfrow = c(1, 2)) plot_invest_wordcloud(combined, top_invest, 12) title("Top 5 VCs", adj = 0.4) plot_invest_wordcloud(combined, bot_invest, 15) title("Bottom 5 VCs", adj = 0.4) par(opar) ```
dccee99f0cbadaccd4fee156f756258a61322391
[ "Markdown", "R", "RMarkdown" ]
3
R
davidsoloman/crunchbase_women_founders
51694d8c1c76fcb6afd1617017ceafcdb9b1c58f
98c4f2816c6c76c078c9c89345a64fb7f47b7c63
refs/heads/master
<repo_name>PedroSiqueira/Sentimentos<file_sep>/www/infoDepressao.html <div class="artigo"> <nav class="navbar navbar-expand navbar-dark bg-success sticky-top"> <a class="navbar-brand abs" href="#">Informações</a> <div class="navbar-nav"> <a class="nav-item nav-link active " onclick="abrir('artigosInfo')"> <i class="fas fa-chevron-left fa-fw"></i> </a> </div> </nav> <div ><h3>Falar de depressão</h3> <p>A depressão, nas suas várias formas clínicas, assume, hoje em dia, proporções inimagináveis. Ou talvez nem tanto, por existirem muitos casos diagnosticados como sendo de depressão, quando, de facto, se trata de outras situações. Ou por existirem muitas pessoas convencidas que sofrem de depressão porque tomam anti-depressivos. Ou pela enorme confusão entre uma tristeza saudável reactiva às situações de vida e uma perturbação do humor com foros de patologia. Ou, ainda, pela absorção de uma evidência cultural moderna que nos impele à eliminação rápida e imediata de qualquer emoção desagradável, definindo essas emoções como doentias.</p> <p>No entanto, e apesar de tudo, permanece o facto de que cada vez mais pessoas se encontram medicadas e em tratamento de uma situação depressiva. As perturbações do humor, onde se incluem depressões major, distimias e bipolaridade exigem, pela sua elevada incidência e, muitas vezes, significativa gravidade, que os psicólogos se mantenham muito actualizados, do ponto de vista científico e focados na procura permanente de soluções mais eficazes, mais rápidas e mais abrangentes.</p> <h3>O que é uma depressão?</h3> <p>A Depressão tem sido uma das perturbações psicológicas mais discutida e avaliada devido à enorme quantidade de pessoas que afectou, afecta… e, não tenha dúvidas sobre o futuro, afectará! São uma em cada quatro pessoas que sofrem de depressão… dá que pensar, não é? Assim, é fácil fazermos contas e percebermos que existem pessoas que passam por situações como esta, com muito sofrimento, e sem perceberem que não se trata apenas de tristeza que persiste em ficar. É importante perceber que para além de tristeza prolongada e desinteresse, a pessoa deprimida fica sem vontade ou prazer em levar a cabo actividades que, anteriormente, considerava como agradáveis e sente-se sem energia ou com cansaço persistente. De uma forma geral, podemos encontrar queixas relacionadas com as funções vitais do seu organismo. Assim, dá-se normalmente uma modificação do apetite (falta ou excesso de apetite), as horas de sono também ficam alteradas (sonolência ou perda de sono) e o desejo sexual diminui gradualmente… atenção a estes sinais que são muito importantes! Ao mesmo tempo que todo o corpo começa a manifestar a presença da depressão, é frequente as pessoas deprimidas sentirem-se inúteis e sem valor, com a auto-estima muito diminuída, terem ideias relacionadas com a morte, sentirem-se incapazes de iniciar tarefas que desenvolviam com facilidade.</p> <p>Se verificar que permanece mais de duas semanas com várias destas queixas a aborrecerem-no(a)… se calhar, este texto já o(a) está a ajudar a compreender que poderá estar a precisar de ajuda especializada.</p> <p>Poderá considerar que já muitas pessoas sentiram algumas destas queixas ocasionalmente, sobretudo depois de terem passado por situações ou acontecimentos que as marcaram negativamente. Está correcto esse pensamento! No entanto, é fundamental estar atento à forma como estas queixas se podem tornar uma constante na sua vida, começando de forma gradual… Assim, ficou a saber que a depressão é diferente das mudanças de humor que todos temos pela permanência dos sintomas que a acompanham. As companhias indesejáveis que, por vezes, tem associadas são: a ansiedade e/ou perturbação de pânico.</p> <p>E, se está a pensar que não tem idade nem tempo para ter depressão informamo-lo(a) desde já: a depressão não escolhe idades e pode durar desde alguns meses a alguns anos (infelizmente, com falta de tratamento adequado é bem possível que a situação se arraste indefinidamente)! De acordo com a sua duração divide-se em episódica, recorrente ou crónica. A importância do tratamento desta perturbação relaciona-se também com uma das suas consequências mais graves: o suicídio. Sabemos que morrem em Portugal, por ano, 1200 pessoas através de suicídio.</p> <p>A depressão é mais comum nas mulheres do que nos homens: a Organização Mundial de Saúde, através de um estudo publicado em 2000 mostrou que 1,9 por cento dos homens tem episódios de depressão unipolar, enquanto nas mulheres o valor sobe para 3,2 por cento.</p> <h3>Sintomas frequentes</h3> <ul> <li>Humor depressivo durante a maior parte do dia, quase todos os dias</li> <li>Diminuição de interesse ou prazer em quase todas as actividades</li> <li>Perda de peso (sem dieta) ou aumento de peso significativo</li> <li>Diminuição ou aumento do apetite quase todos os dias</li> <li>Insónia ou hipersónia (necessidade de dormir muito) quase todos os dias</li> <li>Inibição/lentidão de movimentos</li> <li>Agitação</li> <li>Náuseas, alterações gastro-intestinais</li> <li>Fadiga ou perda de energia quase todos os dias</li> <li>Sentimentos de desvalorização ou culpa excessiva quase todos os dias</li> <li>Pensamentos recorrentes acerca da morte, ideias de suicídio ou tentativas de suicídio</li> </ul> <p>Estar deprimido é algo que cada vez mais frequentemente utilizamos para descrever o nosso estado de tristeza. A depressão é, cada vez mais, vista como o flagelo das sociedades modernas, adquirindo recentemente, e de forma meteórica, o estatuto da constipação da saúde mental, pela sua frequência na nossa população. É amplamente reconhecido pela comunidade psi (profissionais de saúde mental) que a utilização deste termo como rótulo ou descritivo é, de um modo geral, abusiva na forma como as pessoas a utilizam. Surpreendente para muitos será a recente demonstração científica de que este uso abusivo do diagnóstico de depressão estará presente, também, na comunidade de profissionais de saúde mental.</p> <p>Para fazer o diagnóstico de perturbações psicológicas, a maioria destes profissionais apoia-se no DSM-IV TR, o manual psiquiátrico que contém os critérios de diagnóstico para as perturbações psicológicas e psiquiátricas. Quando um cliente reúne um determinado conjunto de critérios, estão criadas as condições para a atribuição de um dado diagnóstico. Embora para algumas perturbações estes critérios sejam considerados por vários profissionais como ambíguos, ou pouco claros, os critérios diagnósticos para a depressão têm encontrado pouca oposição fundamentada cientificamente. Uma investigação conduzida recentemente na Universidade de Nova Iorque veio dar credibilidade a uma corrente de opinião no seio da Psicologia e Psiquiatria que defende que os critérios do DSM-IV TR para a depressão conduzem a demasiados diagnósticos falsos-positivos. Na opinião deste grupo de autores, os critérios do DSM-IV TR estarão elaborados de uma forma insuficientemente específica, o que leva a que que estados normais de tristeza como consequência de perdas na vida (ex. viuvez, desemprego, divórcio) sejam diagnosticados de forma errónea como depressão major.</p> <p>Face a estas críticas, os autores do DSM-IV TR incluíram um conjunto de critérios críticos de diagnóstico para a depressão que, pretendia-se, reduziriam significativamente o número de diagnósticos falso-positivos. O que a investigação recente conduzida na Universidade de Nova Iorque veio demonstrar foi que, na verdade, a presença destes critérios críticos em pouco ou nada veio alterar o número de diagnósticos errados: antes de serem implementados estes critérios, os diagnósticos falsos-positivos rondavam os 30%; depois da sua implementação, cerca de 95% destes diagnósticos falsos-positivos continuavam a ser feitos .</p> <p>Estes resultados têm claras implicações para os intervenientes no contexto da saúde mental: para os profissionais, implica uma reflexão cuidada acerca da forma como diagnosticam e tratam casos de depressão; para o Estado implica uma reflexão sobre o valor anual que se despende em comparticipação de psicofármacos anti-depressivos potencialmente desnecessários.</p> <p>Acima de tudo, para os utentes do Serviço Nacional de Saúde, e de serviços de Psicologia e Psiquiatria privados, convida a alguma precaução na forma como “compramos” os diagnósticos: muitas vezes levamo-los para casa como rótulos que dificilmente descolamos de nós, chegando a falar de nós próprios como pessoas “depressivas”.</p> <p>Nos dias que correm, parece ser uma tendência crescente esquecermo-nos de saber estar tristes. Foi um estado que se demonizou, como se qualquer tipo de tristeza implicasse perturbação mental. Pelo contrário, a capacidade de estar triste é o que existe de mais natural e normal na nossa natureza; fomos dotados desta capacidade como forma de processar as experiências dolorosas. A capacidade de sentir tristeza não é um sinal de depressão. Pelo contrário, muitas vezes, é a incapacidade de a sentir que nos conduz à depressão! Por isso, estejamos tristes quando for caso disso, para noutras alturas podermos estar alegres!</p> <p>Este artigo está disponível <a onclick="window.open('https://www.oficinadepsicologia.com/depressao/', '_system'); return false;" href="#"> Aqui. </a></p> </div> </div> <file_sep>/www/artigoRelaxar60Seg.html <div class="artigo"> <nav class="navbar navbar-expand navbar-dark bg-success sticky-top"> <a class="navbar-brand abs" href="#">Técnica de Relaxamento</a> <div class="navbar-nav"> <a class="nav-item nav-link active " onclick="abrir('tecnicasRelaxamento')"> <i class="fas fa-chevron-left fa-fw"></i> </a> </div> </nav> <h3>Sete técnicas para relaxar em 60 segundos</h3> <p>A rotina agitada e a falta de tempo para descansar abrem cada vez mais espaço para as tensões e para o estresse. Dar prioridade aos momentos de lazer e à prática de exercícios físicos é uma maneira de espantar as preocupações. No dia a dia, pode ser até mais simples. Algumas técnicas ajudam a relaxar em apenas 60 segundos.</p> <p>Toda a vez que passamos por uma situação estressante, muitos sintomas se manifestam fisicamente, causando incômodos, irritações e mal estar. Por isso, técnicas de respiração e concentração, ajudam a controlar os sintomas da ansiedade", diz a psicóloga Adriana de Araújo. A seguir, confira alguns hábitos que ajudam a relaxar em um minuto.</p> <h4>Faça contagem regressiva olhando para cima</h4> <p>Mesmo que seja bastante simples, essa técnica ajuda a relaxar, já que aumenta a concentração em uma tarefa e tira a atenção do que está causando ansiedade. "É preciso se concentrar em algo para relaxar. Fazer contagem regressiva, a partir do 60, bem devagar, vai ajudar", explica a psicóloga Adriana de Araújo.</p> <p>Além disso, olhar para cima estimula sistema nervoso, o que ajuda a reduzir a pressão arterial e diminui o ritmo da respiração, causando a sensação de relaxamento. "Tudo que fizermos para diminuir os batimentos cardíacos ajudará a controlar a ansiedade, inclusive adotar técnicas de postura e concentração", diz explica a psicóloga <NAME>, de Curitiba.</p> <h4>Anote as preocupações em um caderno</h4> <p>Esse método aumenta a concentração, evita distrações e avisa o cérebro que é preciso desacelerar. "Quando fazemos isso, a mente entende que as preocupações estão 'guardadas' e não devem ser resolvidas naquele momento, diminuindo a ansiedade", diz <NAME>.</p> <p>Segundo a psicóloga, anotar as preocupações em um caderno também ajuda a acabar com insônia. "Algumas vezes muitas tarefas que não conseguimos realizar durante o dia nos impedem de relaxar e dormir. Colocar tudo no papel vai ajudar a nos "livrar" daquilo até o dia seguinte", explica Adriana.</p> <h4>Controle a respiração por um minuto</h4> <p>Um dos principais efeitos da ansiedade é o aumento do ritmo cardíaco. "O coração é cheio de terminações nervosas e por isso reage muito facilmente a estímulos cerebrais, que ficam mais intensos em situações de ansiedade e estresse", explica a psicóloga <NAME>.</p> <p>Segundo a psicóloga, algumas técnicas simples de respiração ajudam a controlar o ritmo cardíaco, diminuindo a sensação de ansiedade. "Basta inspirar profundamente com o nariz e segurar o ar por alguns segundos, repetinto esse processo várias vezes", explica. ?Depois, fixe a atenção no peito, na região do coração por 15 segundos?.</p> <h4>Relaxe os músculos</h4> <p>Outra manifestação física da ansiedade é a contração involuntária dos músculos, que causam tensão e muito desconforto. Os músculos que mais sofrem com o estresse são os do pescoço, costas e pernas. "A ansiedade, por mais que seja psicológica, se manifesta fisicamente. É comum cruzar as pernas e deixar os músculos das costas e do pescoço enrijecidos", explica Adriana Araújo.</p> <p>Para desfazer os nós dessas regiões, é importante fazer pequenas seções de alongamento. Aposte em movimentos circulares, realizados lentamente, com o pescoço, pulsos e tornozelos, para aliviar as tensões da musculatura.</p> <h4>Leia um gibi</h4> <p>O hábito da leitura leve, como a de um gibi, é uma boa saída para relaxar em momentos de tensão. "Outras leituras mais complexas e longas podem causar muita distração, o que, após alguns minutos, faz a ansiedade e o estresse voltarem ainda mais intensos", diz Adriana Araújo. Ler uma revista ou notícias curtas de um jornal também ajuda a evitar pensamentos que trazem angústia.</p> <h4>Carregue o lanche certo</h4> <p>Experimente parar para fazer um lanchinho. Nos momentos de ansiedade, a mastigação ajuda a relaxar alguns músculos do pescoço. No entanto, escolher o lanche certo é essencial para afastar a ansiedade e o estresse. "Alimentos bastante práticos e fáceis de transportar, como castanhas e laranja, contém selênio e vitamina C, respectivamente. Esses dois nutrientes melhoraram o funcionamento do sistema nervoso, evitando a ansiedade", explica a nutricionista <NAME>, do Instituto Saúde Plena, em São Paulo.</p> <h4>Bolinha de tênis</h4> <p>Caso esteja em casa, coloque a bolinha de tênis entre as suas costas e uma parede. Inicie a massagem nos pontos em que a tensão é maior. Depois, passe a massagear o ombro e toda a região próxima do pescoço, para relaxar os músculos dessa área.</p> <p>Este artigo está disponível <a onclick="window.open('https://www.minhavida.com.br/bem-estar/materias/14284-sete-tecnicas-para-relaxar-em-60-segundos', '_system'); return false;" href="#"> Aqui. </a></p> </div> <file_sep>/www/js/banco.js var db; function carregarBanco() { if (window.cordova.platformId === 'browser') { //o app esta rodando no browser? db = window.openDatabase('Sentimentos', '1.0', 'Sentimentos', 2 * 1024 * 1024); //se sim, abre o banco de dados do browser console.log('abrindo banco pelo browser'); } else { db = window.sqlitePlugin.openDatabase({name: 'Sentimentos.db', location: 'default'});//senao, abre o banco de dados do android console.log('abrindo banco pelo celular'); } //qualquer comando SQL tem que estar dentro de uma transação db.transaction(function (tx) {//abrindo uma transação tx tx.executeSql("CREATE TABLE IF NOT EXISTS Sentimento ( sentimento TEXT, acontecido TEXT, pensamento TEXT, atitude TEXT, humorometro INTEGER, quando TEXT);"); }, function (error) { console.log('Transaction ERROR: ' + error.message); }, function () { console.log("banco carregado!"); popularTabelas(); abrir("home"); }); } function popularTabelas() { db.transaction(function (tx) { tx.executeSql('SELECT count(*) AS qtd FROM Sentimento', [], function (tx, rs) { if (rs.rows.item(0).qtd === 0) { for (var i = 0; i < 10; i++) { tx.executeSql('INSERT INTO Sentimento (sentimento, acontecido, pensamento, atitude, humorometro, quando) VALUES (?,?,?,?,?,?)', ['sentimento ' + i, 'acontecido ' + i, 'pensamento ' + i, 'atitude ' + i, getRandomIntInclusive(-100, 100), randomDate('2018-10-01', '2019-03-31').toISOString().substr(0, 10)]); } console.log('tabelas populadas!'); } }); }); } function salvar_sentimento() { var sentimento = [$('#sentimento').val(), $('#acontecido').val(), $('#pensamento').val(), $('#atitude').val(), $('#humorometro').val(), $('#quando').val()]; db.transaction(function (transaction) { transaction.executeSql('INSERT INTO Sentimento (sentimento, acontecido, pensamento, atitude, humorometro, quando) VALUES (?,?,?,?,?,?)', sentimento); }, function (error) { console.log('Transaction ERROR: ' + error.message); }, function () { console.log('inserido ' + sentimento + ' no banco!'); carregar_sentimentos(); }); } function carregar_mais_sentimentos() { db.transaction(function (tx) { var limite = 5; var offset = myVue.paginacao ? myVue.paginacao : 0; tx.executeSql("SELECT acontecido, humorometro, quando, rowid FROM Sentimento ORDER BY quando DESC LIMIT ? OFFSET ?;", [limite, offset], function (tx, resultSet) { if (resultSet.rows.length <= 0) return; for (var i = 0; i < resultSet.rows.length; i++) { myVue.sentimentos.push(resultSet.rows.item(i)); } myVue.paginacao += limite; }); }); } function carregar_sentimento(id) { db.transaction(function (tx) { tx.executeSql("SELECT rowid, * FROM Sentimento WHERE rowid = ?;", [id], function (tx, resultSet) { if (resultSet.rows.length) { var s = resultSet.rows.item(0); var o = {sentimento: s.sentimento, acontecido: s.acontecido, pensamento: s.pensamento, atitude: s.atitude, humorometro: s.humorometro, quando: s.quando};//criada uma copia do sentimento abrir('sentimento', {sentimento: s, editando: false, original: o}); } }); }); } function salvar_alteracao() { db.transaction(function (tx) { tx.executeSql("UPDATE Sentimento SET sentimento = ? , acontecido = ? , pensamento = ? , atitude = ? , humorometro = ? , quando = ? WHERE rowid = ?;", [myVue.sentimento.sentimento, myVue.sentimento.acontecido, myVue.sentimento.pensamento, myVue.sentimento.atitude, myVue.sentimento.humorometro, myVue.sentimento.quando, myVue.sentimento.rowid], function (tx, res) { carregar_sentimentos(); }); }); } function apagar_sentimento() { //a funcao modal('hide') é asincrono e serve para fechar o modal //a funcao on('hidden.bs.modal', callback) chama a funcao callback quando o modal terminar de fechar $('#modalApagar').modal('hide').on('hidden.bs.modal', function (e) { //toda vez que apagamos um sentimento, registramos um evento. portanto desregistramos o evento logo apos ele ocorrer, para nao ser disparado multiplas vezes $(this).off('hidden.bs.modal');//gambiarra hidden.bs.modal firing multiple times db.transaction(function (tx) { tx.executeSql("DELETE FROM Sentimento WHERE rowid = ?;", [myVue.sentimento.rowid], function (tx, res) { carregar_sentimentos(); }); }); }); } function carregar_sentimentos_mes(date) { db.transaction(function (tx) { tx.executeSql("SELECT rowid, quando, humorometro FROM Sentimento WHERE quando >= ? AND quando <= ?;", [date + "-01", date + "-31"], function (tx, resultSet) { var sentimentos = []; for (var i = 0; i < resultSet.rows.length; i++) { sentimentos.push(resultSet.rows.item(i)); } preencher_calendario_sentimentos(sentimentos); }); }); } <file_sep>/www/infoAnsiedadeSocial.html <div class="artigo"> <nav class="navbar navbar-expand navbar-dark bg-success sticky-top"> <a class="navbar-brand abs" href="#">Informações</a> <div class="navbar-nav"> <a class="nav-item nav-link active " onclick="abrir('artigosInfo')"> <i class="fas fa-chevron-left fa-fw"></i> </a> </div> </nav> <h3>O que é Ansiedade Social?</h3> <p>A ansiedade social é provavelmente, de entre os problemas de ansiedade, o menos conhecido e o mais negligenciado. Para que possa compreender melhor o que é a ansiedade social e a sua forma mais severa a Fobia Social, torna-se necessário que comecemos por perceber o que é uma situação social. Uma situação social é qualquer situação na qual a pessoa e outras pessoas estão presentes. As situações sociais podem incluir interacção com os outros (o que frequentemente referimos como situações interpessoais) ou situações nas quais a pessoa é o foco de atenção ou que poderá ser reparada por outros (frequentemente referimos como situações de desempenho). Alguns dos seguintes exemplos de situações interpessoais e de desempenho podem ser temidas por pessoas que têm níveis elevados de ansiedade social.</p> <p>Ansiedade social refere-se ao nervosismo ou desconforto em situações sociais, habitualmente devido ao medo que a pessoa tem de poder fazer alguma coisa que possa ser embaraçoso ou ridículo, ou na qual possa causar má impressão, ou que possa ser julgada, criticada ou avaliada negativamente por outras pessoas. Para muitas pessoas, a ansiedade social está limitada a certas situações sociais. Por exemplo, algumas pessoas ficam muito desconfortáveis em situações formais relacionadas com o trabalho, como por exemplo fazer apresentações ou reuniões, mas ficam razoavelmente confortáveis em situações mais casuais, como por exemplo em festas ou a socializar com os amigos. Outras pessoas podem reagir exactamente ao contrário; estão mais confortáveis em situações formais de trabalho do que em situações não estruturadas de encontro social. De facto, não é nada pouco habitual ouvir uma celebridade a dizer que se sente razoavelmente confortável a desempenhar o seu papel em frente a grandes audiências mas que se sente tímida e nervosa quando interage com uma pessoa ou em pequenos grupos em que a intimidade é maior.</p> <p>A intensidade da ansiedade social e a extensão das situações sociais temidas variam de pessoa para pessoa. Por exemplo, algumas pessoas sentem algum receio com que lidam razoavelmente bem, enquanto outras se sentem completamente esmagadas pela intensidade do seu receio. Para algumas pessoas o receio encontra-se limitado a um única situação social (por exemplo, falar em publico), enquanto que para outras pessoas, a ansiedade social surge em quase todas as situações sociais.</p> <p>A ansiedade social está relacionada com diversos factores que poderão incluir estilos e traços de personalidade (por exemplo, introversão, timidez ou perfeccionismo). As pessoas que são tímidas sentem-se frequentemente desconfortáveis em certas situações sociais, em especial aquelas situações que envolvem interagir com outras pessoas e conhecer novas pessoas. As pessoas que são introvertidas tendem a ser mais sossegadas e evitam ou retiram-se mais de situações sociais, podendo preferir estar sozinhas. No entanto, as pessoas introvertidas não são necessariamente ansiosas ou receosas quando socializam. Por último, a disposição para o perfeccionismo está associada à tendência para manter elevadas expectativas para si mesmo que são difíceis ou impossíveis de cumprir. O perfeccionismo pode conduzir a pessoa a sentir-se ansiosa em publico pelo receio que as outras pessoas reparem nas suas “falhas” e os julguem negativamente.</p> <p>Como é que a Ansiedade Social pode interferir nos relacionamentos, no trabalho e na escola, e em outras actividades do dia-a-dia?</p> <p>A ansiedade social pode fazer com que seja difícil para as pessoas estabelecerem e manterem relações saudáveis. Pode afectar todos os níveis de relacionamento, desde o relacionamento com estranhos e conhecidos casuais àqueles com a família e outros significativos. Para muitas pessoas, mesmo a maneira mais simples de interacção social (tal como fazer uma pequena conversa, pedir direcções, cumprimentar um vizinho) são muito difíceis. Para essas pessoas marcar encontros pode estar completamente fora de questão. A ansiedade social pode ser mais fácil de lidar junto de pessoas mais familiares, como amigos e família, mas nem sempre. Para algumas pessoas, a ansiedade pode aumentar à medida que as relações se tornam mais íntimas. A ansiedade social pode ainda interferir com as relações existentes, principalmente se o companheiro(a) de uma pessoa com ansiedade social quiser socializar com outras pessoas. A ansiedade social pode ter um impacto na escolha dos estudos e da profissão. Pode por exemplo afectar o tipo de curso a fazer na faculdade e qual o tipo de emprego que a pessoa pode aceitar. Pode ainda afectar o desempenho no trabalho e o envolvimento na escola. Praticamente qualquer actividade que envolva contacto com outras pessoas pode ser afectada pela ansiedade social.></p> <p>Este artigo disponibiliza um teste que indica se você tem tendências a ter ansiedade social<a onclick="window.open('https://www.oficinadepsicologia.com/test/ansiedade-social/', '_system'); return false;" href="#"> Clique Aqui</a> para realizá-lo.</p </div> <file_sep>/nbproject/project.properties file.reference.Sentimentos-www=www file.reference.www-js=www/js files.encoding=UTF-8 site.root.folder=${file.reference.Sentimentos-www} <file_sep>/www/home.html <nav class="navbar navbar-dark bg-success sticky-top justify-content-center"> <span class="navbar-brand mb-0 h1"> Felling Me</span> </nav> <div class="text-center mt-3"> <div style="margin-top:6em;"> <img data-toggle="modal" data-target="#modalApagar" src="img/tartaruga_9532d00d89589af560f8e84a95908f73.png" width="50%"><br> <button class="btn btn-success mt-4" onclick="novo_registro()">Como você está hoje?</button> </div> </div> <nav class="navbar fixed-bottom navbar-expand border-top border-success" style="background-color: white;"> <div class="navbar-nav text-center justify-content-around"> <a class="nav-item nav-link text-success py-0" href="#" onclick="carregar_sentimentos()"> <i class="far fa-calendar fa-lg"></i> <div class="small">Sentimentos</div> </a> <a class="nav-item nav-link text-success py-0" href="#" onclick="abrir('informacoes');"> <i class="fas fa-info fa-lg"></i> <div class="small">Informações</div> </a> </a> </div> </nav> <div class="modal fade" id="modalApagar" tabindex="-1" role="dialog"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-body" style="text-align:justify;"> Olá! Eu estou aqui em nome de George solitário, ele era uma tartaruga de Galápagos considerado o último de sua espécie e viveu sozinho em uma reserva natural até a sua morte em 2012. Após isso, descobriram que ele não era o último, mas sim um entre vários que seriam resgatados. Você também não está sozinho, existem pessoas que se sentem como você e não é necessário que carregue tudo o que sente sem falar com ninguém :) </div> <div class="modal-footer"> <center><button type="button" class="btn btn-success" style="margin-right:8em;" onclick="fechar_modal();">Ok</button></center> </div> </div> </div> </div> <file_sep>/www/infoDepConceitoEDiagn.html <div class="artigo"> <nav class="navbar navbar-expand navbar-dark bg-success sticky-top"> <a class="navbar-brand abs" href="#">Informações</a> <div class="navbar-nav"> <a class="nav-item nav-link active " onclick="abrir('artigosInfo')"> <i class="fas fa-chevron-left fa-fw"></i> </a> </div> </nav> <h3>Depressão: Conceito e diagnóstico</h3> <h5>Resumo</h5> <p>Este artigo revê o conceito de depressão e a nosologia contemporânea dos estados depressivos e seus diferentes subtipos. São discutidos aspectos relativos ao curso (formas agudas vs crônicas da doença, padrão sazonal), características fenomenológicas (melancolia, quadros psicóticos, quadros atípicos, formas catatônicas) da doença, assim como a importância e o significado das alterações psicomotoras para o diagnóstico das chamadas depressões "endógenas" ou "vitais", de acordo com trabalhos contemporâneos (como os de Parker e Widlöcher). Este trabalho aborda também as fronteiras da depressão com o transtorno bipolar, os transtornos de personalidade, a desmoralização e os estados de luto normal, assim como os limites com outras doenças e estados induzidos por drogas.</p> <h5>Descritores</h5> <p>Depressão; transtornos do humor; melancolia; depressão atípica; padrão sazonal; diagnóstico; nosologia</p> <h5>Significados do termo "depressão"</h5> <p>O termo depressão, na linguagem corrente, tem sido empregado para designar tanto um estado afetivo normal (a tristeza), quanto um sintoma, uma síndrome e uma (ou várias) doença(s).</p> <p>Os sentimentos de tristeza e alegria colorem o fundo afetivo da vida psíquica normal. A tristeza constitui-se na resposta humana universal às situações de perda, derrota, desapontamento e outras adversidades. Cumpre lembrar que essa resposta tem valor adaptativo, do ponto de vista evolucionário, uma vez que, através do retraimento, poupa energia e recursos para o futuro. Por outro lado, constitui-se em sinal de alerta, para os demais, de que a pessoa está precisando de companhia e ajuda. As reações de luto, que se estabelecem em resposta à perda de pessoas queridas, caracterizam-se pelo sentimento de profunda tristeza, exacerbação da atividade simpática e inquietude. As reações de luto normal podem estender-se até por um ou dois anos, devendo ser diferenciadas dos quadros depressivos propriamente ditos. No luto normal a pessoa usualmente preserva certos interesses e reage positivamente ao ambiente, quando devidamente estimulada. Não se observa, no luto, a inibição psicomotora característica dos estados melancólicos. Os sentimentos de culpa, no luto, limitam-se a não ter feito todo o possível para auxiliar a pessoa que morreu; outras idéias de culpa estão geralmente ausentes.</p> <p>Enquanto sintoma, a depressão pode surgir nos mais variados quadros clínicos, entre os quais: transtorno de estresse pós-traumático, demência, esquizofrenia, alcoolismo, doenças clínicas, etc. Pode ainda ocorrer como resposta a situações estressantes, ou a circunstâncias sociais e econômicas adversas.</p> <p>Enquanto síndrome, a depressão inclui não apenas alterações do humor (tristeza, irritabilidade, falta da capacidade de sentir prazer, apatia), mas também uma gama de outros aspectos, incluindo alterações cognitivas, psicomotoras e vegetativas (sono, apetite).</p> <p>Finalmente, enquanto doença, a depressão tem sido classificada de várias formas, na dependência do período histórico, da preferência dos autores e do ponto de vista adotado. Entre os quadros mencionados na literatura atual encontram-se: transtorno depressivo maior, melancolia, distimia, depressão integrante do transtorno bipolar tipos I e II, depressão como parte da ciclotimia, etc.</p> <h5>Descrição clínica</h5> <p>s descrições feitas por Kraepelin, dos estados depressivos e maníacos, na oitava edição de seu tratado, são insuperáveis pela clareza e precisão. Felizmente encontra-se disponível uma reedição recente desse trabalho, em tradução inglesa,1 o que torna sua leitura mais facilmente acessível. De muito interesse é o artigo clássico de Falret, sobre a "folie circulaire", marco na história da doença maníaco-depressiva, datado de 1854 e recentemente republicado pelo American Journal of Psychiatry, com comentários de <NAME>.2 Igualmente interessantes são as descrições de Bleuler, em seu Tratado de Psiquiatria (atualizado por <NAME>), que conta com traduções em espanhol e mesmo em português.3</p> <h5>Aspectos gerais</h5> <p>Embora a característica mais típica dos estados depressivos seja a proeminência dos sentimentos de tristeza ou vazio, nem todos os pacientes relatam a sensação subjetiva de tristeza. Muitos referem, sobretudo, a perda da capacidade de experimentar prazer nas atividades em geral e a redução do interesse pelo ambiente. Freqüentemente associa-se à sensação de fadiga ou perda de energia, caracterizada pela queixa de cansaço exagerado. Alguns autores4,5 enfatizam a importância das alterações psicomotoras, em particular referindo-se à lentificação ou retardo psicomotor. Este tópico será abordado mais detidamente no item referente à conceituação da "melancolia".</p> <p>No diagnóstico da depressão levam-se em conta: sintomas psíquicos; fisiológicos; e evidências comportamentais.</p> <h5>Sintomas psíquicos</h5> <li>Humor depressivo: sensação de tristeza, autodesvalorização e sentimentos de culpa.</li> <p>Os pacientes costumam aludir ao sentimento de que tudo lhes parece fútil, ou sem real importância. Acreditam que perderam, de forma irreversível, a capacidade de sentir alegria ou prazer na vida. Tudo lhes parece vazio e sem graça, o mundo é visto "sem cores", sem matizes de alegria. Em crianças e adolescentes, sobretudo, o humor pode ser irritável, ou "rabugento", ao invés de triste. Certos pacientes mostram-se antes "apáticos" do que tristes, referindo-se muitas vezes ao "sentimento da falta de sentimentos". Constatam, por exemplo, já não se emocionarem com a chegada dos netos, ou com o sofrimento de um ente querido, e assim por diante.</p> <p>O deprimido, com freqüência, julga-se um peso para os familiares e amigos, muitas vezes invocando a morte para aliviar os que o assistem na doença.</p> <p>São freqüentes e temíveis as idéias de suicídio. As motivações para o suicídio incluem distorções cognitivas (perceber quaisquer dificuldades como obstáculos definitivos e intransponíveis, tendência a superestimar as perdas sofridas) e ainda o intenso desejo de pôr fim a um estado emocional extremamente penoso e tido como interminável. Outros ainda buscam a morte como forma de expiar suas supostas culpas. Os pensamentos de suicídio variam desde o remoto desejo de estar simplesmente morto, até planos minuciosos de se matar (estabelecendo o modo, o momento e o lugar para o ato). Os pensamentos relativos à morte devem ser sistematicamente investigados, uma vez que essa conduta poderá prevenir atos suicidas, dando ensejo ao doente de se expressar a respeito.</p> <li>Redução da capacidade de experimentar prazer na maior parte das atividades, antes consideradas como agradáveis. As pessoas deprimidas podem relatar que já não se interessam pelos seus passatempos prediletos. As atividades sociais são freqüentemente negligenciadas, e tudo lhes parece agora ter o peso de terríveis "obrigações".</li> <li>Fadiga ou sensação de perda de energia. A pessoa pode relatar fadiga persistente, mesmo sem esforço físico, e as tarefas mais leves parecem exigir esforço substancial. Lentifica-se o tempo para a execução das tarefas.</li> <li>Diminuição da capacidade de pensar, de se concentrar ou de tomar decisões. Decisões antes quase automáticas parecem agora custar esforços intransponíveis. Um paciente pode se demorar infindavelmente para terminar um simples relatório, pela incapacidade em escolher as palavras adequadas. O curso do pensamento pode estar notavelmente lentificado. Professores experientes queixam-se de não conseguir preparar as aulas mais rotineiras; programadores de computadores pedem para ser substituídos pela atual "incompetência"; crianças e adolescentes têm queda em seus rendimentos escolares, geralmente em função da fatigabilidade e déficit de atenção, além do desinteresse generalizado. </li> <h5>Sintomas fisiológicos</h5> <li>alterações do sono (mais freqüentemente insônia, podendo ocorrer também hipersonolência). A insônia é, mais tipicamente, intermediária (acordar no meio da noite, com dificuldades para voltar a conciliar o sono), ou terminal (acordar mais precocemente pela manhã). Pode também ocorrer insônia inicial. Com menor freqüência, mas não raramente, os indivíduos podem se queixar de sonolência excessiva, mesmo durante as horas do dia.</li> <li>alterações do apetite (mais comumente perda do apetite, podendo ocorrer também aumento do apetite). Muitas vezes a pessoa precisa esforçar-se para comer, ou ser ajudada por terceiros a se alimentar. As crianças podem, pela inapetência, não ter o esperado ganho de peso no tempo correspondente. Algumas formas específicas de depressão são acompanhadas de aumento do apetite, que se mostra caracteristicamente aguçado por carboidratos e doces.</li> <li> redução do interesse sexual</li> <h5>Evidências comportamentais</h5> <li>retraimento social</li> <li>crises de choro</li> <li>comportamentos suicidas</li> <li>Retardo psicomotor e lentificação generalizada, ou agitação psicomotora. Freqüentemente os pacientes se referem à sensação de peso nos membros, ou ao "manto de chumbo" que parecem estar carregando. Em recente revisão da literatura sobre os estados depressivos, o item "retardo psicomotor" foi o denominador comum, em nove sistemas classificatórios, como traço definidor da melancolia. Na Austrália, <NAME> e colaboradores5 propuseram, para o diagnóstico da melancolia, um sistema baseado não em "sintomas" (subjetivos), mas em "sinais" (características objetivas, observáveis): o sistema "core", que tem sido cada vez mais utilizado pelos pesquisadores nessa área. Na França, <NAME> e colaboradores, na Salpêtrière, desenvolveram uma escala especificamente destinada a medir o retardo psicomotor ("échelle de ralentissement dépressif" da Salpêtrière). Deve-se ainda lembrar, no diagnóstico das depressões, que algumas vezes o quadro mais típico pode ser mascarado por queixas proeminentes de dor crônica (cefaléia, dores vagas no tórax, abdome, ombros, região lombar, etc.). A ansiedade está freqüentemente associada. Em idosos, principalmente, as queixas de caráter hipocondríaco costumam ser muito comuns.</li> <h5>Alterações dos rimos circadianos</h5> <p>Muitas funções circadianas encontram-se alteradas nas depressões, a exemplo da regulação da temperatura e do ritmo de produção do cortisol. Entre as alterações mais conspícuas estão aquelas relacionadas ao ritmo do sono. Segundo Akiskal,6 cerca de dois terços dos pacientes deprimidos têm diminuição da latência para o início do sono REM ("Rapid Eyes Movements"). As formas ditas "melancólicas" da depressão caracterizam-se, entre outros aspectos, pela piora matinal e pelo despertar precoce pela manhã.</p> <h5>Características melancólicas</h5> <p>O termo "melancolia" tem sido empregado, nas atuais classificações (como o DSM IV), para designar o subtipo anteriormente chamado de "endógeno", "vital", "biológico", "somático" ou "endogenomorfo" de depressão. Considerado por muitos como o "protótipo" ou síndrome nuclear das depressões, a melancolia – ao contrário de outras formas de depressão – parece constituir-se em um grupo mais homogêneo, que responde melhor a tratamentos biológicos, e para o qual os fatores genéticos seriam os principais determinantes. Parker e cols.5 chamam a atenção para a importância das alterações psicomotoras na melancolia, para eles a principal característica desse quadro nosológico. O conceito de melancolia no DSM-IV foi revisto, em relação ao do DSM-III-R, tornando-se mais preciso e definindo com mais rigor no subgrupo aqui estudado.7 Testes biológicos, como, por exemplo, o teste da supressão do cortisol pela dexametasona, são mais freqüentemente positivos nos quadros melancólicos do que em outros tipos de depressão.</p> <h5>Características psicóticas</h5> <p>Cumpre lembrar que o termo "psicótico", origem de tantas controvérsias em psiquiatria, tem três significados distintos: 1. significado meramente descritivo, quando designa, por exemplo, quadros psiquiátricos onde ocorrem alucinações e delírios; 2. significado etiológico, quando designa quadros endógenos (determinados por tendências constitucionais do indivíduo), em contraposição àqueles determinados por fatores psicogênicos; e 3. significado que alude à gravidade (ou intensidade) do quadro. As atuais classificações, fugindo de preconceitos etiológicos, utilizam o termo psicótico apenas em sentido descritivo. Assim, a expressão designa, nesse contexto, aquelas formas de depressão onde ocorrem delírios e alucinações. Admite-se que essas formas cheguem a 15% dos quadros depressivos. </p> <h5>Depressões catatônicas</h5> <p>Os delírios depressivos considerados congruentes com o humor incluem delírios de culpa, de punição merecida, delírios de ruína e delírios nihilistas (que podem configurar a síndrome de Cotard, quando incluem negação de órgãos e negação da morte). Na depressão delirante as pessoas podem interpretar eventos triviais do cotidiano como evidências de defeitos pessoais, ao tempo em que se culpam de forma indevida e francamente inapropriada. Um paciente, por exemplo, culpava-se pela morte de um desconhecido, cujo féretro passou por sua rua; outra, uma senhora de meia idade, julgava ser a responsável pela paralisação das obras de uma ponte em sua cidade. Mais comumente, no entanto, o paciente recua no tempo, com a finalidade de se acusar por supostos delitos ou atos culposos do passado, remoendo escrúpulos indevidos. Os temas de ruína, quando delirantes, apresentam-se, de acordo com Bleuler,3 como: ruína do corpo (delírios hipocondríacos: a pessoa acredita, por exemplo, estar com o fígado "apodrecido", ou com determinados órgãos "tomados pelo câncer"); ruína espiritual (delírios de culpa, com acusações por faltas ou pecados cometidos); e ruína financeira (delírios que envolvem temas de pobreza e miséria). A "escolha" do tema faz-se, certamente, em consonância com as características da personalidade do paciente. Por outro lado, podem ocorrer temas delirantes, aparentemente sem relação com o humor depressivo.</p> <h5>Características psicóticas</h5> <p>Cumpre lembrar que o termo "psicótico", origem de tantas controvérsias em psiquiatria, tem três significados distintos: 1. significado meramente descritivo, quando designa, por exemplo, quadros psiquiátricos onde ocorrem alucinações e delírios; 2. significado etiológico, quando designa quadros endógenos (determinados por tendências constitucionais do indivíduo), em contraposição àqueles determinados por fatores psicogênicos; e 3. significado que alude à gravidade (ou intensidade) do quadro. As atuais classificações, fugindo de preconceitos etiológicos, utilizam o termo psicótico apenas em sentido descritivo. Assim, a expressão designa, nesse contexto, aquelas formas de depressão onde ocorrem delírios e alucinações. Admite-se que essas formas cheguem a 15% dos quadros depressivos. </p> <p>Os delírios depressivos considerados congruentes com o humor incluem delírios de culpa, de punição merecida, delírios de ruína e delírios nihilistas (que podem configurar a síndrome de Cotard, quando incluem negação de órgãos e negação da morte). Na depressão delirante as pessoas podem interpretar eventos triviais do cotidiano como evidências de defeitos pessoais, ao tempo em que se culpam de forma indevida e francamente inapropriada. Um paciente, por exemplo, culpava-se pela morte de um desconhecido, cujo féretro passou por sua rua; outra, uma senhora de meia idade, julgava ser a responsável pela paralisação das obras de uma ponte em sua cidade. Mais comumente, no entanto, o paciente recua no tempo, com a finalidade de se acusar por supostos delitos ou atos culposos do passado, remoendo escrúpulos indevidos. Os temas de ruína, quando delirantes, apresentam-se, de acordo com Bleuler,3 como: ruína do corpo (delírios hipocondríacos: a pessoa acredita, por exemplo, estar com o fígado "apodrecido", ou com determinados órgãos "tomados pelo câncer"); ruína espiritual (delírios de culpa, com acusações por faltas ou pecados cometidos); e ruína financeira (delírios que envolvem temas de pobreza e miséria). A "escolha" do tema faz-se, certamente, em consonância com as características da personalidade do paciente. Por outro lado, podem ocorrer temas delirantes, aparentemente sem relação com o humor depressivo.</p> <p>Os delírios incongruentes com o humor incluem temas de perseguição, e delírios de estar sendo controlado (estes, comumente associados a fenômenos "schneiderianos" de inserção e irradiação de pensamentos). Quando presentes, esses fenômenos incongruentes com o humor associam-se a um pior prognóstico, avizinhando-se, não raramente, dos estados ditos "esquizoafetivos". </p> <p>As alucinações que acompanham os estados depressivos, quando presentes, são em geral transitórias e não elaboradas. Costumam ser, mais comumente, coerentes com o humor depressivo: vozes que condenam o paciente, imprecações do demônio, choro de defuntos, etc. Mais raramente, ocorrem alucinações não congruentes com o humor (sem relação aparente com os temas depressivos). As formas mais severas de depressão psicótica foram descritas por Kraepelin1 com o nome de "melancolia fantástica". Nessa forma aparecem intensos delírios e alucinações, alternando-se estados de violenta excitação com estados estuporosos, a par de leve obnubilação da consciência (essas formas são hoje dificilmente encontradas).</p> <h5>Depressões catatônicas</h5> <p>Diz-se que uma depressão tem características catatônicas quando o quadro clínico se caracteriza por intensas alterações da psicomotricidade, entre as quais: imobilidade quase completa, atividade motora excessiva, negativismo extremo, mutismo, estereotipias, ecolalia ou ecopraxia, obediência ou imitação automática. A imobilidade motora pode se apresentar como estupor (o chamado "estupor melancólico") ou ainda por catalepsia (flexibilidade cérea). Impõe-se aqui o diagnóstico diferencial cuidadoso, com a catatonia induzida por condição médica geral (por exemplo, encefalopatia hepática), por drogas ou medicamentos, e com a esquizofrenia catatônica. Cumpre notar que, nos tempos atuais, é muito raro encontrar-se um verdadeiro "estupor melancólico". As facilidades de diagnóstico e de tratamento quase sempre impedem a progressão a essas formas mais graves, que ainda em passado recente (particularmente antes da introdução do eletrochoque) ameaçavam a vida dos pacientes. Em pessoas jovens, o aparecimento de acentuada lentificação psicomotora e de formas sutis de estupor é quase sempre indicativo de doença bipolar, que freqüentemente acabará se manifestando mais tarde através de fases maníacas.</p> <h5>Depressões crônicas (distimias)</h5> <p>As depressões crônicas são geralmente de intensidade mais leve que os episódios de depressão maior. Mais que o humor francamente deprimido, os pacientes com depressão crônica (distimia) sofrem por não sentir prazer nas atividades habituais, e por terem suas vidas coartadas por uma espécie de morosidade irritável. </p> <p>As alucinações que acompanham os estados depressivos, quando presentes, são em geral transitórias e não elaboradas. Costumam ser, mais comumente, coerentes com o humor depressivo: vozes que condenam o paciente, imprecações do demônio, choro de defuntos, etc. Mais raramente, ocorrem alucinações não congruentes com o humor (sem relação aparente com os temas depressivos). As formas mais severas de depressão psicótica foram descritas por Kraepelin1 com o nome de "melancolia fantástica". Nessa forma aparecem intensos delírios e alucinações, alternando-se estados de violenta excitação com estados estuporosos, a par de leve obnubilação da consciência (essas formas são hoje dificilmente encontradas). </p> <h5>Depressões atípicas</h5> <p>Originalmente criado na Inglaterra, e posteriormente desenvolvido pelo grupo da Universidade de Columbia, em Nova York, o conceito de depressão "atípíca" refere-se (de modo muito típico) àquelas formas de depressão caracterizadas por: reatividade do humor, sensação de fadiga acentuada e "peso" nos membros, e sintomas vegetativos "reversos" (opostos aos da depressão melancólica), como aumento de peso e do apetite, em particular por carboidratos e hipersonia. Além disso, descreve-se como característica constante das pessoas sujeitas a esse tipo de depressão um padrão persistente de extrema sensibilidade à percepção do que consideram como rejeição por parte de outras pessoas. Episódios com características "atípicas" são mais comuns nos transtornos bipolares (I e II), no transtorno depressivo com padrão sazonal. </p> <h5>Sazonalidade</h5> <p>Especialmente no hemisfério norte, onde as estações do ano são bem definidas, verifica-se com clareza que algumas formas de depressão acentuam-se ou são precipitadas de acordo com um padrão sazonal; mais comumente as depressões desse tipo ocorrem no outono e no inverno. Muitos desses pacientes têm fases hipomaníacas na primavera, sendo classificados como do tipo bipolar II (depressões maiores e hipomania). Freqüentemente esses pacientes apresentam algumas características sobrepostas às da "depressão atípica": fadiga excessiva, aumento do apetite (em particular por carboidratos) e hipersonolência. O DSM-IV inclui o "padrão sazonal" como um especificador do tipo de depressão estudada.</p> <h5>Classificações atuais dos estados depressivos</h5> <b><p>CID-10</p></b> <p>A Classificação Internacional das Doenças, da Organização Mundial da Saúde, em sua décima revisão8, a CID-10, assim apresenta os transtornos do humor, em suas linhas gerais:</p> <li>F30 - Episódio maníaco (usado para episódio único de mania).</li> <li>F31 - Transtorno afetivo bipolar.</li> <p>O transtorno afetivo bipolar pode ser classificado, de acordo com o tipo do episódio atual, em hipomaníaco, maníaco ou depressivo. Os episódios maníacos são subdivididos de acordo com a presença ou ausência de sintomas psicóticos. Os episódios depressivos são classificados de acordo com as regras descritas em F32. O transtorno afetivo bipolar inclui ainda os episódios mistos (F31.6).</p> <li>1 2 F32 - Episódio depressivo (usado para episódio depressivo único).</li> <p>O episódio depressivo pode ser, quanto à intensidade, classificado como: leve, moderado ou grave. Os episódios leves e moderados podem ser classificados de acordo com a presença ou ausência de sintomas somáticos. Os episódios depressivos graves são subdivididos de acordo com a presença ou ausência de sintomas psicóticos.</p> <li>F33 - Transtorno depressivo recorrente (tem as mesmas subdivisões descritas para o episódio depressivo).</li> <li>F34 - Transtornos persistentes do humor: F34.0 - Ciclotimia e F34.1 - Distimia.</li> <p>A CID-10 inclui ainda códigos para "outros" transtornos do humor e para "transtornos não identificados". </p> <b><p>DSM-IV</p></b> <p>A Associação Psiquiátrica Americana, no DSM-IV,9 assim classifica os transtornos do humor:</p> <i><p>Transtornos depressivos:</p></i> <li>296.xx - Transtorno depressivo maior, que é subdividido em episódio único, ou recorrente.</li> <li>300.4 - Transtorno distímico, que pode ser especificado de acordo com o tipo de início (precoce ou tardio), e de acordo com a presença ou ausência de características atípicas.</li> <li>311 - Transtorno depressivo sem outra especificação (SOE).</li> <i><p>Transtornos bipolares:</p></i> <li>296.xx - Transtorno bipolar I.</li> <p>O transtorno bipolar I inclui a ocorrência de episódio maníaco único. O DSM IV pede que se especifique o tipo do episódio mais recente: hipomaníaco, maníaco, depressivo, misto, ou inespecificado.</p> <li>296.89 - Transtorno bipolar II (hipomania associada a pelo menos um episódio depressivo maior). Especificar se o episódio atual (ou mais recente) é hipomaníaco ou depressivo.</li> <li>301.13 - Transtorno ciclotímico</li> <li>296.80 - Transtorno bipolar sem outra especificação (SOE)</li> <li>293.83 - Transtorno do humor devido a condição médica geral</li> <li>___.__ - Transtorno do humor induzido por substâncias (referir os códigos específicos para cada substância).</li> <li>296.90 - Transtorno do humor sem outra especificação (SOE). </li> <p>O DSM IV fornece ainda, em seu apêndice B, conjuntos de critérios para estudos adicionais. No que concerne os transtornos do humor, devem ser lembrados: transtorno depressivo menor, transtorno depressivo breve recorrente, transtorno misto de ansiedade-depressão e transtorno da personalidade depressiva.</p> <h5>Críticas ao conceito de "transtorno depressivo maior"</h5> <p>O conceito de depressão maior, como aparece no DSM-IV, é excessivamente abrangente, e por isso mesmo, pouco preciso. Abarca provavelmente uma gama muito heterogênea de condições, que vão desde as fronteiras da normalidade (reações de luto ou tristeza normal) até aquelas formas mais graves de depressão, para as quais provavelmente concorrem fatores mais biológicos (adquiridos e/ou geneticamente determinados). Para o diagnóstico de "Transtorno Depressivo Maior", de acordo com o DSM-IV, basta que a pessoa apresente "humor deprimido ou perda de interesse ou prazer, durante um período de duas semanas", mais quatro sintomas de uma lista de nove (ou mais três sintomas, se os dois primeiros estiverem presentes). Assim, por exemplo, se uma moça que brigou com o namorado apresentar tristeza e perda de energia por 15 dias, além de mais três sintomas, como insônia, perda de energia e capacidade diminuída de se concentrar, terá preenchido critérios para "Transtorno Depressivo Maior". Um conceito tão amplo certamente não contribui para que se testem hipóteses sobre a etiologia das depressões, resposta a tratamentos biológicos, etc. Não serve tampouco para auxiliar na decisão de se medicar ou não a pessoa que preencha tais critérios. Já o conceito de melancolia é muito mais preciso e, por essa razão, tem maior valor preditivo quanto, por exemplo, à resposta terapêutica a antidepressivos e ao eletrochoque.</p> <h5>Depressão e o espectro dos transtornos bipolares</h5> <p>Assiste-se hoje, indubitavelmente, à redescoberta da obra de Kraepelin.1 Os critérios diagnósticos adotados pela Associação Psiquiátrica Americana (DSM IV) e pela Organização Mundial da Saúde (CID 10) refletem, em suas linhas gerais, a nosologia kraepeliniana. Também no âmbito das afecções do humor (transtornos afetivos) verifica-se, em aspectos fundamentais, o retorno às concepções de Kraepelin. Em 1921, tratando da definição da "insanidade maníaco-depressiva", Kraepelin escreveu:</p> <p>"A insanidade maníaco-depressiva , como descrita nesse capítulo, inclui, por um lado, o domínio completo da chamada insanidade periódica e circular, e por outro lado inclui a mania simples, a maior parte dos estados mórbidos designados como melancolia, e também um número não desprezível de casos de amência. Finalmente, incluímos aqui certos coloridos leves e sutis do humor, alguns dos quais periódicos, outros continuamente mórbidos, os quais , se por um lado podem ser encarados como o rudimento de doenças mais severas, por outro lado passam, sem limites nítidos, para o campo da predisposição pessoal. No curso dos anos eu me tornei mais e mais convencido de que todos os estados acima mencionados representam apenas manifestações de um único processo mórbido."</p> <p>Retomando a abordagem clássica de Kraepelin, Akiskal tem, em diversas publicações,6,10,11 enfatizado a importância do espectro da doença bipolar. Esse espectro incluiria desde as formas típicas da doença bipolar (bipolar I, com pelo menos uma fase maníaca), passando pelas depressões associadas à hipomania (bipolar II) até as depressões recorrentes, sem hipomania espontânea, mas freqüentemente associadas ao temperamento hipertímico e/ou à história de transtorno bipolar na família. Estes últimos casos são chamados de "bipolar III" ou de "pseudo unipolares" , na terminologia de Akiskal. Admite-se hoje, em geral, a existência de numerosas formas de transição entre estados depressivos e maníacos, incluindo suas formas mitigadas, que esbarram na fronteira dos chamados "temperamentos hipertímicos" e "depressivos". Por outro lado, muitos pacientes exaltados, com quadros psicóticos cíclicos, freqüentemente caracterizados por curso bifásico (alguns incluindo características psicóticas incongruentes com o humor) pertencem, na verdade, ao espectro bipolar, o que se depreende pela história familiar (bipolar) e resposta ao tratamento com estabilizadores do humor. De fato, muitos dos pacientes chamados "esquizoafetivos" concentram-se em famílias de pessoas com quadros afetivos bipolares típicos.12</p> <p>O DSM IV tornou "oficial" o conceito de "transtorno bipolar II", incluindo na classificação americana os quadros de hipomania associados a episódios depressivos maiores (um ou mais episódios depressivos maiores, acompanhados pelo menos por um episódio hipomaníaco). Nas versões anteriores do DSM (DSM III e DSM III R), tais quadros – mais freqüentes que os de tipo bipolar I – eram classificados apenas como "transtorno bipolar sem outra especificação- SOE". </p> <p>O temperamento dos pacientes bipolares II e III, quando avaliado fora das crises, é freqüentemente ciclotímico, isto é, caracterizado por leves depressões que se alternam com hipomanias. Nos bipolares III a mudança para a hipomania não é observada espontaneamente. Muitas vezes ocorrem fases hipomaníacas, ou maníacas, em decorrência do uso de antidepressivos ou eletroconvulsoterapia. Cumpre notar que muitos desses pacientes têm história familiar de transtorno bipolar ou temperamento pré-mórbido hipertímico. Considerando-se que muitas vezes é difícil obter história fidedigna quanto a antecedentes familiares de bipolaridade, o diagnóstico basear-se-á, muitas vezes, na presença de temperamento hipertímico ou ciclotímico, associado a depressões recorrentes, para que se inclua o paciente dentro do "soft bipolar spectrum". Observe-se que, entre os ciclotímicos, são relativamente poucos (6%) os que desenvolvem mania. A maioria desenvolverá quadros de depressão maior, aproximando-se dos bipolares de tipo II. Entre as depressões leves e crônicas, a importância do "espectro" é corroborada pelo fato de que um em três pacientes com diagnóstico de "distimia", observados prospectivamente, desenvolvem hipomania, caracteristicamente depois da farmacoterapia com antidepressivos.13 Os episódios depressivos daqueles pertencentes ao "espectro bipolar" tendem a se caracterizar por hipersonolência e hiperfagia, embora a insônia possa ocorrer, sobretudo em episódios mistos.</p> <p>As flutuações do humor observadas nos bipolares II e III freqüentemente dão origem a crises na profissão, na vida familiar e no relacionamento social. Não por acaso, esses pacientes, sujeitos a períodos de exaltação do humor e liberação dos impulsos sexuais e agressivos, são erroneamente classificados como tendo transtornos da personalidade (borderline, narcísico e histriônico). Freqüentemente, o abuso e a dependência do álcool e de outras drogas ocorre como "complicação" das doenças do espectro bipolar, pela freqüência com que essas substâncias são usadas como autotratamento.</p> <h5>Os limites da depressão</h5> <h5>Limites com os transtornos da personalidade</h5> <p>A distinção entre um transtorno psiquiátrico propriamente dito (eixo I do DSM-IV) frente aos transtornos da personalidade (eixo II) reveste-se da maior importância, por suas conseqüências práticas e teóricas. Considerada portadora de uma " doença", a pessoa passa a merecer considerações diagnósticas, tratamento, e cuidados sociais. Rotulada como portadora de um "distúrbio da personalidade", a pessoa passa muitas vezes a ser alvo do nihilismo terapêutico e vítima de preconceitos morais. Na melhor das hipóteses, passa a ser vista simplesmente como "um pessoa bizarra", acautelando-se os demais frente às suas "atuações" e "manipulações", principalmente se o diagnóstico for de um dos seguintes transtornos: " borderline", anti-social, narcísico e histriônico. Segundo Akiskal,14 cerca da metade a dois terços dos pacientes classificados como "borderline" pertenceriam ao grupo das doenças do humor (afetivas), sendo, em sua maioria, integrantes do "espectro bipolar". Muitos desses pacientes caracterizam-se por ter uma biografia assaz tumultuada, cujo traço mais estável é a instabilidade nas relações afetivas, no trabalho, e na vida em geral. Freqüentemente, essas pessoas passam da "calmaria" afetiva à "tempestade" das automutilações e das tentativas de suicídio. O abuso e a dependência de drogas freqüentemente se associam ao quadro.</p> <h5>Limites com outros diagnósticos</h5> <p>O diagnóstico dos estados depressivos deve levar em conta, antes de mais nada, se os sintomas depressivos são primários ou secundários a doenças físicas e/ou ao uso de drogas e medicamentos. O DSM IV contém o item 293.83 - Transtorno do humor devido a uma condição médica geral para descrever esses casos. O DSM IV traz também critérios para o diagnóstico de Transtorno do humor induzido por substância. A tabela 1 enumera alguns agentes farmacológicos e doenças físicas associadas ao desencadeamento de estados depressivos.</p> <p>No campo da nosologia psiquiátrica, além dos transtornos da personalidade (já abordados) devem-se levar em conta, entre outros, os seguintes diagnósticos diferenciais: transtornos de ansiedade; alcoolismo e outras farmacodependências; transtornos esquizofrênicos, quadros esquizofreniformes e a chamada doença esquizo-afetiva; quadros demenciais.</p> <p>As referências e o artigo podem ser encontrados <a onclick="window.open('http://www.scielo.br/scielo.php?script=sci_arttext&pid=S1516-44461999000500003', '_system'); return false;" href="#"> Aqui</a>.</p> </div>
b046a736e01082058300466486049b0583ba96d0
[ "JavaScript", "HTML", "INI" ]
7
HTML
PedroSiqueira/Sentimentos
dff48f79fbe98780cec12ca86c191c090a95228d
eaad2017859b444b36f6773c25e890e28f7e345e
refs/heads/master
<file_sep>package com.example.musicplayer; import androidx.annotation.RequiresApi; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import android.Manifest; import android.content.ComponentName; import android.content.Intent; import android.content.ServiceConnection; import android.content.pm.PackageManager; import android.media.MediaPlayer; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.SeekBar; import android.widget.TextView; import android.widget.Toast; import java.io.File; import java.io.IOException; import java.lang.ref.WeakReference; import java.net.MalformedURLException; import java.net.URL; import java.sql.Date; import java.text.SimpleDateFormat; import java.util.TimerTask; import static android.os.SystemClock.sleep; public class MusicPlayer extends AppCompatActivity implements View.OnClickListener ,SeekBar.OnSeekBarChangeListener{ private static final int UPDATE = 1; private static final int MUSICDURATION = 0; private MediaPlayer mediaPlayer=new MediaPlayer(); private boolean isStop; private String musicName=""; private SeekBar seekBar; private TextView timeNow; private TextView time; private TextView musicNameT; private TextView nowTimeT; private TextView timeT; private int position; private int nowTimeInt=0; private int timeInt=0; private String url; Button play_pause; private boolean isSeekBarChanging; private boolean fileExist=false; private boolean hadPlay=false; private String[] nameList={"","","","",""}; private String[] urlStr={"","","","",""}; private DownloadService.DownloadBinder downloadBinder; private boolean change=false; private ServiceConnection connection = new ServiceConnection() { @Override public void onServiceDisconnected(ComponentName name) { downloadBinder=null; } @Override public void onServiceConnected(ComponentName name, IBinder service) { Log.e("TAG","--downLoadBinder--"); downloadBinder = (DownloadService.DownloadBinder) service; } }; private Handler handler=new Handler(){ @RequiresApi(api = Build.VERSION_CODES.N) @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case MUSICDURATION: seekBar.setMax(mediaPlayer.getDuration()); break; case UPDATE: try { nowTimeInt = mediaPlayer.getCurrentPosition(); nowTimeT.setText(formatTime(nowTimeInt)); seekBar.setProgress((int) (nowTimeInt*100.0/(timeInt*1.0))); } catch (Exception e) { e.printStackTrace(); } handler.sendEmptyMessageDelayed(UPDATE,500); break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.music_player); ImageView last=findViewById(R.id.last); ImageView next=findViewById(R.id.next); ImageView back=findViewById(R.id.back); play_pause=(Button)findViewById(R.id.btn_play_pause); timeNow=findViewById(R.id.music_now_time); time=findViewById(R.id.music_time); seekBar=findViewById(R.id.seekBar); seekBar.setOnSeekBarChangeListener(this); musicNameT=findViewById(R.id.music_name); nowTimeT=findViewById(R.id.music_now_time); timeT=findViewById(R.id.music_time); play_pause.setOnClickListener(this); last.setOnClickListener(this); next.setOnClickListener(this); back.setOnClickListener(this); Intent intent = getIntent(); nowTimeT.setText(formatTime(nowTimeInt)); timeT.setText(formatTime(timeInt)); position=intent.getIntExtra("position",-1); nameList =intent.getStringArrayExtra("nameList"); urlStr = intent.getStringArrayExtra("urlStr"); musicName= nameList[position]; url=urlStr[position]; musicNameT.setText(nameList[position]); if(ContextCompat.checkSelfPermission(MusicPlayer.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){ ActivityCompat.requestPermissions(MusicPlayer.this,new String[]{ Manifest.permission.WRITE_EXTERNAL_STORAGE},1); } else{ initMediaPlayer(); } } private void initMediaPlayer(){ Log.e("TAG","--initMediaPlayer()--"); File file = new File(getFilesDir(), musicName + ".mp3"); if(!hadPlay) { Intent intent = new Intent(MusicPlayer.this, DownloadService.class); startService(intent); // 启动服务 bindService(intent, connection, BIND_AUTO_CREATE); // 绑定服务 if (ContextCompat.checkSelfPermission(MusicPlayer.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(MusicPlayer.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1); } } } public void onRequestPermissionsResult(int requestCode,String[] permissions, int[] grantResults){ switch (requestCode){ case 1: if(grantResults.length>0&&grantResults[0]==PackageManager.PERMISSION_GRANTED){ initMediaPlayer(); }else{ Toast.makeText(this,"拒绝权限将无法使用程序", Toast.LENGTH_SHORT).show(); finish(); } break; default: } } @Override public void onClick(View view) { switch (view.getId()) { case R.id.btn_play_pause: if(mediaPlayer.isPlaying()){ mediaPlayer.pause(); }else{ if (hadPlay == false) { File file = new File(getFilesDir(), musicName + ".mp3"); String filePath = getFilesDir() + "/" + musicName + ".mp3"; if (!file.exists()) { try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } if (downloadBinder != null) { downloadBinder.startDownload(url + ";" + filePath); } } try { mediaPlayer.setDataSource(file.getPath()); mediaPlayer.prepare(); timeInt = mediaPlayer.getDuration(); timeT.setText(formatTime(timeInt)); hadPlay = true; } catch (IOException e) { e.printStackTrace(); hadPlay = false; } } if (!mediaPlayer.isPlaying()) { mediaPlayer.start(); handler.sendEmptyMessage(UPDATE); //发送Message } } if (mediaPlayer.isPlaying()){ play_pause.setBackgroundResource(R.drawable.play); }else play_pause.setBackgroundResource(R.drawable.pause); break; case R.id.last: mediaPlayer.stop(); mediaPlayer.release(); if (mediaPlayer != null){ mediaPlayer = null; } if (position > 0) { Intent intent = new Intent(MusicPlayer.this, MusicPlayer.class); String name = nameList[position - 1]; intent.putExtra("urlStr", urlStr); intent.putExtra("position", position - 1); intent.putExtra("nameList", nameList); startActivity(intent); MusicPlayer.this.finish(); } else if (position == 0) { Intent intent = new Intent(MusicPlayer.this, MusicPlayer.class); int fin = nameList.length - 1; String name = nameList[fin]; intent.putExtra("urlStr", urlStr); intent.putExtra("position", fin); intent.putExtra("nameList", nameList); startActivity(intent); MusicPlayer.this.finish(); } else { Toast.makeText(MusicPlayer.this, "出错,请联系管理员~", Toast.LENGTH_SHORT).show(); } break; case R.id.next: { mediaPlayer.stop(); mediaPlayer.release(); if (position < nameList.length - 1) { mediaPlayer = null; Intent intent = new Intent(MusicPlayer.this, MusicPlayer.class); String name = nameList[position + 1]; intent.putExtra("position", position + 1); intent.putExtra("nameList", nameList); intent.putExtra("urlStr", urlStr); startActivity(intent); MusicPlayer.this.finish(); } else if (position == nameList.length - 1) { mediaPlayer = null; Intent intent = new Intent(MusicPlayer.this, MusicPlayer.class); String name = nameList[0]; intent.putExtra("position", 0); intent.putExtra("nameList", nameList); intent.putExtra("urlStr", urlStr); startActivity(intent); MusicPlayer.this.finish(); } else { Toast.makeText(MusicPlayer.this, "出错,请联系管理员~", Toast.LENGTH_SHORT).show(); } break; } case R.id.back: { try { Intent intent = new Intent(MusicPlayer.this, MainActivity.class); startActivity(intent); MusicPlayer.this.finish(); } catch (Exception e) { e.printStackTrace(); } break; } } } protected void onDestroy() { super.onDestroy(); if(mediaPlayer != null){ mediaPlayer.stop(); mediaPlayer.release(); mediaPlayer = null; } unbindService(connection); } @Override public void onProgressChanged(SeekBar seekBar, int i, boolean b) { if(b==true) { nowTimeInt = (int) (i * 1.0 / 100.0 * timeInt); } nowTimeT.setText(formatTime(nowTimeInt)); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { //nowTimeInt = (int) (seekBar.getProgress() * 1.0 / 100.0 * timeInt); nowTimeT.setText(formatTime(nowTimeInt)); mediaPlayer.seekTo(nowTimeInt); } private String formatTime(int length){ Date date = new Date(length); //时间格式化工具 SimpleDateFormat sdf = new SimpleDateFormat("mm:ss"); String totalTime = sdf.format(date); return totalTime; } }<file_sep>package com.example.musicplayer; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; public class welcome extends AppCompatActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.welcome); final Button welcome = (Button)findViewById(R.id.welcome); welcome.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent=new Intent(welcome.this,MainActivity.class); startActivityForResult(intent,1); welcome.this.finish(); } }); } } <file_sep>package com.example.musicplayer; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.media.MediaPlayer; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.ListView; import android.widget.Toast; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity{ private MediaPlayer mediaPlayer=new MediaPlayer(); private List<String> music_nameList = new ArrayList<>(); private List<String> urlList=new ArrayList<>(); ArrayAdapter simpleAdapter; ListView musicList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ImageView fin = (ImageView)findViewById(R.id.finish); music_nameList.add("Empty Playground"); music_nameList.add("Love is Here"); music_nameList.add("Playing With Shadows"); music_nameList.add("Night Sky"); music_nameList.add("Endless Rivers"); String url1="https://files.freemusicarchive.org/storage-freemusicarchive-org/tracks/RIIGymORSJBaI5Wx9sF8DbZYtYZlaXQhQcugFiIp.mp3?download=1"; String url2="https://files.freemusicarchive.org/storage-freemusicarchive-org/tracks/C8ADQUFFdQX75kEXsoNfx0PL1SYKR5S950Y0Pe1F.mp3?download=1"; String url3="https://files.freemusicarchive.org/storage-freemusicarchive-org/tracks/gJxfWoUaxAjABtqFjHqkcFKuRHy61tCIgp8arQV7.mp3?download=1"; String url4="https://files.freemusicarchive.org/storage-freemusicarchive-org/tracks/kaj3p3avYy3noMSdxYgjiEIACwUYtXt3pJK7K9pZ.mp3?download=1"; String url5="https://files.freemusicarchive.org/storage-freemusicarchive-org/tracks/x1mmRXGoAdIjD0bpFYombfpza2g4aGu4H8Nmt73T.mp3?download=1"; urlList.add(url1); urlList.add(url2); urlList.add(url3); urlList.add(url4); urlList.add(url5); fin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { System.exit(0); } }); simpleAdapter = new ArrayAdapter(MainActivity.this,android.R.layout.simple_list_item_1,music_nameList); //适配器 musicList = findViewById(R.id.list_view); musicList.setAdapter(simpleAdapter); musicList.setOnItemClickListener(new AdapterView.OnItemClickListener(){ //配置ArrayList点击按钮 @Override public void onItemClick(AdapterView<?> parent, View view , int position , long id){ String name = music_nameList.get(position); Intent intent = new Intent(MainActivity.this, MusicPlayer.class); intent.putExtra("position",position); String[] namelist={"","","","",""}; for(int i=0;i<5;i++){ namelist[i]=music_nameList.get(i); } String[] urlStr = {"","","","",""}; for(int i=0;i<5;i++){ urlStr[i]=urlList.get(i); } intent.putExtra("nameList",namelist); intent.putExtra("urlStr",urlStr); startActivity(intent); MainActivity.this.finish(); } }); } }
022efc80f6e7ff57e670d53b746f097eced810a7
[ "Java" ]
3
Java
hello2019-ui/Android_experiment4
73b202277594abcfd47a014cbb5f0f3248364952
75fd09c8fdb43de30543b19cb4acb735aafd6ac8
refs/heads/master
<file_sep>package org.news.dao; import java.sql.SQLException; import org.news.entity.User; public interface UserDao{ //查找是否登录成功 public User findUser(String uname, String password) throws SQLException; }<file_sep>package org.news.dao; import java.util.List; import org.news.entity.Topic; public interface TopicsDao { // 获取所有主题 public List<Topic> getAllTopics(); // 更新主题 public int updateTopic(Topic topic); // 根据名字查找主题 public Topic findTopicByName(String name); // 添加主题 public int addTopic(String name); // 通过tid删除主题 public int deleteTopic(int tid); }<file_sep>package org.news.dao; import java.util.List; import org.news.entity.News; public interface NewsDao{ //获取所有新闻 public List<News> getAllnews(); //获取某主题下的所有新闻 public List<News> getAllnewsByTID(int Tid); //获取某主题下的新闻数量 public int getNewsCountByTID(int Tid); }<file_sep>package org.news.service; import java.sql.SQLException; import java.util.List; import org.news.entity.Comment; public interface CommentsService { // 通过新闻id查找评论 public List<Comment> findCommentsByNid(int nid) throws SQLException; // 添加评论 public int addComment(Comment comment) throws SQLException; }
bcbc29e18d016ac39042e8b54339fee7d0cdba5f
[ "Java" ]
4
Java
a1925860426A/Eclipse
37aa8bec3549dd5a04b04d7f6d909bf450e23581
57777eade080ddc4704cab5649e9ffbe64d04091
refs/heads/master
<repo_name>itsyanik/rocketseat-starter-react<file_sep>/README.md # Rocketseat Starter: ReactJS This project utilizes Rocketseat starter course for internal studying purposes. - GitFlow was used to manage branches - One branch was created for each lesson - After lessons are done, generate a 1.0.0 release - Merge on master # V1.2.0 This version implements TypeScript<file_sep>/src/pages/product/index.js export { default } from './product.tsx'
9682a616262cf691c49767162bd0165b939f7036
[ "Markdown", "JavaScript" ]
2
Markdown
itsyanik/rocketseat-starter-react
d8b37f29f2b098082bd68f083d866b7e4f928681
cc1326326d19ce8558fb0551c2117b84edf56f23
refs/heads/master
<file_sep>const inquirer = require("inquirer"); const generateMarkdown = require("./utils/generateMarkdown"); const fs = require('fs'); const util= require('util'); const writeFileAsync= util.promisify(fs.writeFile); const promptUser = () => { return inquirer .prompt([ { type: "input", name: "title", message: "What is your project title?", default: "Generate a good README.md file" }, { type: "input", name: "description", message: "Please provide your project description-" }, { type: "input", name: "installation", message: "What are the installation instructions?" }, { type: "input", name: "usage", message: "Please describe usage-" }, { type: "list", name: "license", message: "Please select a License-", choices: [ "MIT", "Apache", "GPL", "ISC"] }, { type: "input", name: "contributing", message: "What are the rules for contributing?" }, { type: "input", name: "email", message: "Enter the email address-" }, { type: "input", name: "tests", message: "Provide examples on how to run tests-" }, { type: "input", name: "badge", message: "Input badge code please?" }, { type: "input", name: "question1", message: "Enter the url of your profile picture-" }, { type: "input", name: "question2", message: "Enter the url of your github repository-" } ]); }; const init = async() => { try { const data= await promptUser(); await writeFileAsync("README.md", generateMarkdown(data)); }catch(error){ console.log(error) } }; init();<file_sep># Project Title Generate a good README.md file ## Project Description This is a node.js app that takes user input and creates a good readme.md file for your code repository. ## Table of Contents * [Installation](#installation) * [Usage](#usage) * [Contributing](#contributing) * [Test](#test) * [Questions](#GitHub) * [License](#license) * [Badges](#badges) * [Email](#email) ## Installation Simply clone the code into your repo and install dependencies with ‘npm i’ command in terminal, and then run the program with the command ‘node index.js’. ## Usage First of all, run ‘node index’js’ and answer the all questions then README.md file will be created. ## Contributing Please email me with any issues or if you would like to contribute something to the project. ## Test Test ## Badges ![License](https://img.shields.io/badge/License-MIT-blue.svg "License Badge") ## License: Please click the link below for license- - [License](https://opensource.org/Licenses/MIT) ## Email <EMAIL> ## Profile Picture Please click the link below- - [Profile Picture](https://drive.google.com/file/d/1NpqgzksgSEZZMUt_JVysgiVHqTJRNVYL/view?usp=sharing/[Picture](https://drive.google.com/file/d/1NpqgzksgSEZZMUt_JVysgiVHqTJRNVYL/view?usp=sharing/${data.question1)) ## GitHub Please click the link for github repository- https://github.com/raufun05/Good-README-Generator
d104eab4fb23a7662d840632e471c000d3960897
[ "JavaScript", "Markdown" ]
2
JavaScript
raufun05/Good-README-Generator
9c46ed449573a649ec241fd1bc22915f9c036de1
34b3aaa4a3344c27ecc2c5bbffdcf623438e3828
refs/heads/master
<file_sep>package main import ( "context" "errors" "io/ioutil" "net/http" "sync" log "github.com/sirupsen/logrus" ) const ( url = "https://api.binance.com/api/v3/avgPrice?symbol=ETHBTC" ) func createOrder(ctx context.Context, orderID int, ch chan<- string, ce chan<- error, wg *sync.WaitGroup) { defer wg.Done() log.WithFields(log.Fields{ "orderID": orderID, }).Info("start to create order") select { case <-ctx.Done(): // before start creating the order we check if it was not already cancelled log.WithFields(log.Fields{ "orderID": orderID, }).Warn("cancelled request") return default: // creates the order resp, err := http.Get("https://api.binance.com/api/v3/avgPrice?symbol=ETHBTC") if err != nil { log.WithFields(log.Fields{ "orderID": orderID, }).WithError(err).Error("err handle it") ce <- err return } defer resp.Body.Close() b, err := ioutil.ReadAll(resp.Body) if err != nil { log.WithFields(log.Fields{ "orderID": orderID, }).WithError(err).Error("err handle it") ce <- err return } // forcing the error here just to see the cancellation if orderID == 4 { err := errors.New("invalid order number") log.WithFields(log.Fields{ "orderID": orderID, }).WithError(err).Error("invalid order") ce <- err return } ch <- string(b) log.WithFields(log.Fields{ "orderID": orderID, }).Info("order created") } } func main() { log.Info("started") ctx := context.Background() ctx, cancel := context.WithCancel(ctx) orders := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} log.WithFields(log.Fields{ "orders": orders, }).Info("creating orders") var wg sync.WaitGroup ch := make(chan string) errors := make(chan error) var responses []string // create the orders - all the goroutines will be blocked until someone reads the channel // or someone closes the channel for _, orderID := range orders { wg.Add(1) go createOrder(ctx, orderID, ch, errors, &wg) } // separate goroutine to wait all WaitGroups to finish and close the channels // this is not blocking the Main since it's a separate goroutine go func() { wg.Wait() log.Info("closing channels") close(ch) close(errors) }() // this is where we read the channels and it is a blocking operation too // if there is nothing to read, it will block until this happens // infinity loop until we close the channels or the error happens channelIsOpen := true for channelIsOpen { select { case response, ok := <-ch: if !ok { log.Info("response channel is closed") channelIsOpen = false break } log.WithFields(log.Fields{ "response": response, }).Info("appending response") responses = append(responses, response) case err := <-errors: log.WithError(err).Error("error happened - cancelling") cancel() channelIsOpen = false } } // some final processing with the results - whatever for _, r := range responses { log.WithFields(log.Fields{ "response": r, }).Info("received response") } log.Info("done!") } <file_sep>module github.com/rafarlopes/go-concurrency-test go 1.14 require github.com/sirupsen/logrus v1.5.0 // indirect
352eef1446308802b636e5b7fcd5696a79f766d3
[ "Go Module", "Go" ]
2
Go
rafarlopes/go-concurrency-test
b6eacf6f983876361deff92f410a9ffb3740185e
a9c7d6dd982dbda6b7129a533bf80a3c9713b7bd
refs/heads/master
<file_sep>package com.example.nginxresource; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import java.io.IOException; import java.nio.file.Paths; @SpringBootApplication public class NginxResourceApplication { public static void main(String[] args) throws IOException { startNginx(); SpringApplication.run(NginxResourceApplication.class, args); } private static void startNginx() throws IOException { String nginx_home="G:\\apr\\nginx-resource\\server\\nginx-1.13.7"; ProcessBuilder builder =new ProcessBuilder().directory(Paths.get(nginx_home).toFile()); builder.command("cmd","/c","start.bat"); builder.inheritIO(); builder.start(); } } <file_sep>server.port=10080 security.user.name=admin security.user.password=<PASSWORD>
3d9e228228028a1871427063a39d736314388abe
[ "Java", "INI" ]
2
Java
zscgrhg/nginx-resource
bd0e610ce34fbc8b4a0ca4807a78092d1ec6c22a
02a61b0599064f8ba59ba33f0fca367eb56bc5c6
refs/heads/master
<repo_name>FreifeldRoyi/dockerfiles<file_sep>/2-openliberty/openliberty:19.0.0.7/Dockerfile FROM freifeld/java:12 LABEL Maintainer="<NAME>" ENV RELEASE 2019-07-11_1115 ENV VERSION 192.168.3.11 ENV ARCHIVE_NAME openliberty-${VERSION} ENV INSTALL_DIR /opt/openliberty ENV OPENLIBERTY_HOME ${INSTALL_DIR}/${VERSION} ENV DEFAULT_SERVER_DIR ${OPENLIBERTY_HOME}/usr/servers/defaultServer ENV DEPLOYMENT_DIR ${DEFAULT_SERVER_DIR}/dropins RUN mkdir -p /opt/openliberty/${VERSION} \ && curl -O https://public.dhe.ibm.com/ibmdl/export/pub/software/openliberty/runtime/release/${RELEASE}/${ARCHIVE_NAME}.zip \ && unzip ${ARCHIVE_NAME}.zip -d ${OPENLIBERTY_HOME} \ && mv ${OPENLIBERTY_HOME}/wlp/* ${OPENLIBERTY_HOME} \ && rm -rf ${OPENLIBERTY_HOME}/wlp \ && rm ${ARCHIVE_NAME}.zip ADD server.xml ${DEFAULT_SERVER_DIR}/ WORKDIR ${OPENLIBERTY_HOME} EXPOSE 9080 9443 CMD [ "./bin/server" , "run", "defaultServer"]<file_sep>/README.md # dockerfiles A bunch of useful dockerfiles <file_sep>/build.py import os docker_base_name = "freifeld" ignores = [".git", ".vscode"] all_dirs = sorted([d[0][2:] for d in os.walk(".") if d[1] == [] and [ignore for ignore in ignores if ignore in d[0] or d[0] == "."] == []]) cur_dir = os.getcwd() for d in all_dirs: cwd_dir = os.path.join(os.getcwd(),d) os.chdir(cwd_dir) if os.path.exists("./build.py"): os.system("python3 ./build.py") else: split = d.split(os.sep)[-1] split = split[2:] if len(split) >= 2 and split[0].isdigit() and split[1] == "-" else split os.system(f"docker build -t {docker_base_name}/{split} .") os.chdir(cur_dir)<file_sep>/1-java/java:12/Dockerfile FROM centos:7 LABEL Maintainer="<NAME>" ENV VERSION_MAJOR=12 ENV VERSION_MINOR=0.1 ENV VERSION_FULL=${VERSION_MAJOR}.${VERSION_MINOR} RUN yum update -y \ && mkdir /usr/lib/jvm/ \ && yum -y install unzip \ && curl -O https://download.oracle.com/java/GA/jdk${VERSION_FULL}/69cfe15208a647278a19ef0990eea691/${VERSION_MAJOR}/GPL/openjdk-${VERSION_FULL}_linux-x64_bin.tar.gz \ && tar xvf openjdk-${VERSION_FULL}_linux-x64_bin.tar.gz -C /usr/lib/jvm/ \ && yum clean all \ && rm openjdk-${VERSION_FULL}_linux-x64_bin.tar.gz \ && rm -rf /var/cache/yum ENV JAVA_HOME /usr/lib/jvm/jdk-${VERSION_FULL} ENV PATH "$PATH":/${JAVA_HOME}/bin:.:
10137a82e64093599c2065562ded3b20f50e06ce
[ "Markdown", "Python", "Dockerfile" ]
4
Dockerfile
FreifeldRoyi/dockerfiles
b6f450b32060b32714d82e80dd1a96cec421822a
07729ea1cc8718873f62a9f97bd52b2bccac63ea
refs/heads/master
<file_sep>// This event triggers on page load /*document.addEventListener("DOMContentLoaded", function () { loadSpecials(); });*/ function setUpSpecials() { document.getElementById("contentbody").innerHTML = '<br><h2>Specials</h2></br><table class="table table-striped spaced-table"><thead><tr><th>Name</th><th>Description</th><th>Price</th></tr></thead><tbody id="specialsList"></tbody></table>'; loadSpecials(); } function setUpFeedback() { document.getElementById("contentbody").innerHTML = '<br><h2>Feedback</h2><br><input type="text" id="fname" placeholder="Enter your name"><input type="text" id="fcomment" placeholder="Please give us your feedback"><button onclick="submitFeedback()">Submit</button><table class="table table-striped spaced-table"><thead><tr><th>Name</th><th>Description</th><th>Price</th></tr></thead><tbody id="feedbackList"></tbody></table>'; loadFeedback(); } function loadFeedback() { FeedbackModule.getFeedback(setupFeedbackTable); } function loadSpecials() { // We need a reference to the div/table that we are going to chuck our data into SpecialsModule.getSpecials(setupSpecialsTable); } // This is the callback for when the data comes back in the specialmodule function setupSpecialsTable(specials) { var specialsTable = document.getElementById("specialsList"); console.log(specials); for (i = 0; i < specials.length; i++) { // Create row var row = document.createElement('tr'); // Add the columns in the row (td / data cells) var namecol = document.createElement('td'); namecol.innerHTML = specials[i].name; row.appendChild(namecol); var descriptioncol = document.createElement('td'); descriptioncol.innerHTML = specials[i].description; row.appendChild(descriptioncol); var pricecol = document.createElement('td'); pricecol.innerHTML = specials[i].price; row.appendChild(pricecol); // Append the row to the end of the table specialsTable.appendChild(row); } } function setupFeedbackTable(feedback) { var feedbackTable = document.getElementById("feedbackList"); console.log(feedback); for (i = 0; i < feedback.length; i++) { // Create row var row = document.createElement('tr'); // Add the columns in the row (td / data cells) var namecol = document.createElement('td'); namecol.innerHTML = feedback[i].name; row.appendChild(namecol); var commentcol = document.createElement('td'); commentcol.innerHTML = feedback[i].comment; row.appendChild(commentcol); // Append the row to the end of the table feedbackTable.appendChild(row); } } function submitFeedback() { var name = document.getElementById("fname").textContent; var comment = document.getElementById("fcomment").textContent; var com = new XMLHttpRequest(); com.onreadystatechange = function () { if (com.readyState == 4 && com.status == 200) { setUpFeedback(); } } var sendstring = '{"FeedbackID": 0,"Name": "'+ name +'","Comment": "'+ comment +'"}'; com.open("POST", "~/api/Feedbacks", true); com.setRequestHeader('Content-type', 'application/json'); com.send(JSON.stringify(sendstring)); }<file_sep>var appInsights = window.appInsights || function (config) { function r(config) { t[config] = function () { var i = arguments; t.queue.push(function () { t[config].apply(t, i) }) } } var t = { config: config }, u = document, e = window, o = "script", s = u.createElement(o), i, f; for (s.src = config.url || "//az416426.vo.msecnd.net/scripts/a/ai.0.js", u.getElementsByTagName(o)[0].parentNode.appendChild(s), t.cookie = u.cookie, t.queue = [], i = ["Event", "Exception", "Metric", "PageView", "Trace"]; i.length;) r("track" + i.pop()); return r("setAuthenticatedUserContext"), r("clearAuthenticatedUserContext"), config.disableExceptionTracking || (i = "onerror", r("_" + i), f = e[i], e[i] = function (config, r, u, e, o) { var s = f && f(config, r, u, e, o); return s !== !0 && t["_" + i](config, r, u, e, o), s }), t }({ instrumentationKey: "8a53d9ee-9621-4478-9a04-453dbbfc53e5" }); window.appInsights = appInsights; appInsights.trackPageView(); var SpecialsModule = (function () { // Return anything that you want to expose outside the closure return { getSpecials: function (callback) { $.ajax({ type: "GET", dataType: "json", url: "~/api/Specials", success: function (data) { console.log(data); callback(data); } }); } }; }()); var FeedbackModule = (function () { // Return anything that you want to expose outside the closure return { getFeedback: function (callback) { $.ajax({ type: "GET", dataType: "json", url: "~/api/Feedback", success: function (data) { console.log(data); callback(data); } }); } }; }());<file_sep>using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Web; using System.Data.Entity.Migrations; namespace Nandoso.Models { [DbConfigurationType(typeof(MySql.Data.Entity.MySqlEFConfiguration))] public class NandosoContext : DbContext { // You can add custom code to this file. Changes will not be overwritten. // // If you want Entity Framework to drop and regenerate your database // automatically whenever you change your model schema, please use data migrations. // For more information refer to the documentation: // http://msdn.microsoft.com/en-us/data/jj591621.aspx public NandosoContext() : base("name=NandosoContext") { Database.SetInitializer(new MigrateDatabaseToLatestVersion<NandosoContext, MyConfiguration>()); } public System.Data.Entity.DbSet<Nandoso.Models.Special> Specials { get; set; } public class MyConfiguration : DbMigrationsConfiguration<NandosoContext> { public MyConfiguration() { this.AutomaticMigrationsEnabled = true; } protected override void Seed(NandosoContext context) { var specials = new List<Special> { new Special { Name = "Flame grilled chicken", Description = "3 pieces of juicy flame grilled chicken", Price = 10.00M }, new Special { Name = "Fudge", Description = "Thick and chocolaty fudge", Price = 5.50M }, new Special { Name = "Brownie", Description = "Our renowned chocolate brownie", Price = 6.20M }, new Special { Name = "Chicken burger", Description = "Layers of flame grilled chicken with lettuce and spices between two golden buns", Price = 14.99M }, new Special { Name = "Chicken pizza", Description = "A delicious pizza with chunks of flame grilled chicken generously applied", Price = 13.00M }, new Special { Name = "Cola", Description = "A 1.5L bottle of that black fizzy stuff", Price = 2.70M }, new Special { Name = "<NAME>", Description = "No comment.", Price = 3.30M } }; specials.ForEach(s => context.Specials.AddOrUpdate(p => p.Description, s)); context.SaveChanges(); } } public System.Data.Entity.DbSet<Nandoso.Models.Feedback> Feedbacks { get; set; } } }
25ef5d56d1f8312a717ef84dba32a932f1be7602
[ "JavaScript", "C#" ]
3
JavaScript
pixll/Nandoso
980ac1be31882c4eb0b4f6a6af201740d786196c
54fa549bc6884259a0df6b5e7080cd3b4f20d460
refs/heads/main
<file_sep>#!/usr/bin/env python # coding: utf-8 # In[1]: import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import scipy from scipy.stats import stats import numpy as np from sklearn.linear_model import LogisticRegression,LinearRegression from sklearn.naive_bayes import GaussianNB from sklearn.neighbors import KNeighborsClassifier from sklearn.tree import DecisionTreeClassifier from sklearn.model_selection import cross_val_score,train_test_split,GridSearchCV from sklearn.metrics import accuracy_score,classification_report,confusion_matrix,roc_curve from sklearn.preprocessing import LabelEncoder,StandardScaler # In[2]: df=pd.read_csv('customer_churn.csv') df.head() # In[3]: df.info(verbose=True) # In[4]: df.describe() # In[5]: df['Churn'].value_counts() # In[6]: df['Churn'].value_counts()/len(df['Churn'])*100 # so this is not balanced Data # In[7]: df.isnull().sum() # In[8]: df_n=df.copy() # In[9]: df_n.TotalCharges=pd.to_numeric(df_n.TotalCharges,errors='coerce') df_n.isnull().sum() # In[10]: df_n.loc[df_n['TotalCharges'].isnull()==True] # In[11]: df_n.dropna(how='any',inplace=True) # In[12]: df_n.isnull().sum() # In[13]: print(df_n['tenure'].max()) # In[14]: labels=["{0}-{1}".format(i,i+11) for i in range(1,72,12)] df_n['tenure_group']=pd.cut(df.tenure,range(1,80,12),right=False,labels=labels) # In[15]: df_n['tenure_group'].value_counts() # In[16]: df_n_n=df_n.drop(['customerID','tenure'],axis=1) df_n_n.head() # In[17]: df_n_n['Churn']=np.where(df_n_n.Churn == 'Yes',1,0) # In[18]: for i,var in enumerate(df_n_n.drop(columns=['Churn','TotalCharges','MonthlyCharges'])): plt.figure(i) sns.countplot(data=df_n_n,x=var,hue='Churn') # In[19]: df_dummy=pd.get_dummies(df_n_n) df_dummy.head() # In[20]: sns.lmplot(data=df_dummy,x='MonthlyCharges',y='TotalCharges') # In[21]: kde= sns.kdeplot(data=df_n_n.MonthlyCharges[(df_n_n['Churn']==0)],shade=True,color='blue') kde= sns.kdeplot(data=df_dummy.MonthlyCharges[(df_dummy['Churn']==0)],shade=True,color='red') # In[22]: plt.figure(figsize=(20,15)) df_dummy.corr()['Churn'].sort_values(ascending=False).plot(kind='bar') # In[23]: plt.figure(figsize=(30,25)) sns.heatmap(df_dummy.corr(),annot=True,cmap=None) # In[24]: pd.pandas.set_option('display.max_columns',None) pd.pandas.set_option('display.max_rows',None) df_dummy.head() # In[25]: #creating X and Y Variables # In[26]: x = df_dummy.drop(['Churn'],axis=1) y = df_dummy['Churn'] # In[27]: x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.25,random_state=101) # In[28]: dc=DecisionTreeClassifier(criterion='gini',random_state=101) dc.fit(x_train,y_train) # In[29]: pred = dc.predict(x_test) pred # In[30]: classification_report(y_test,pred,labels=[0,1]) # In[31]: confusion_matrix(y_test,pred) # In[32]: from imblearn.combine import SMOTEENN # In[33]: sm=SMOTEENN() x_resampled,y_resampled= sm.fit_resample(x,y) # In[34]: xr_train,xr_test,yr_train,yr_test=train_test_split(x_resampled,y_resampled,test_size=0.25,random_state=101) # In[35]: dc_sm=DecisionTreeClassifier(criterion='gini',random_state=101) dc_sm.fit(xr_train,yr_train) # In[36]: pred_y_sm=dc_sm.predict(xr_test) pred_y_sm # In[37]: confusion_matrix(yr_test,pred_y_sm) # In[38]: classification_report(yr_test,pred_y_sm) Now we weill check on RANDOMFOREST # In[39]: from sklearn.ensemble import RandomForestClassifier rfc= RandomForestClassifier(n_estimators=100,criterion='gini',max_leaf_nodes=None) rfc.fit(x_train,y_train) pred_rfc=rfc.predict(x_test) print(classification_report(y_test,pred_rfc)) print(confusion_matrix(y_test,pred_rfc)) # In[42]: sm=SMOTEENN() x_resampled,y_resampled= sm.fit_resample(x,y) # In[44]: xrr_train,xrr_test,yrr_train,yrr_test=train_test_split(x_resampled,y_resampled,test_size=0.25,random_state=101) # In[48]: from sklearn.ensemble import RandomForestClassifier rfc_sm= RandomForestClassifier(n_estimators=100,criterion='gini',max_leaf_nodes=None) rfc_sm.fit(xrr_train,yrr_train) pred_rfc_sm=rfc_sm.predict(x_test) print(classification_report(y_test,pred_rfc_sm)) print(confusion_matrix(y_test,pred_rfc_sm)) # In[49]: import pickle filename='model.sav' pickle.dump(rfc_sm,open(filename,'wb')) # In[51]: load_model=pickle.load(open(filename,'rb')) # In[60]: load_model.score(xrr_test,yrr_test) # In[ ]:
41fcf0ef34248b36d9fa61a579f413b9fd948ebf
[ "Python" ]
1
Python
abhishekgupta31/Customchurner_
1e65810b2c639a4efd774864d673824c4a2c2224
5904dafbcf0e726687ff695502abdfb831b7dfa7
refs/heads/master
<file_sep><?php $title = 'Oska Aroma Diffuser'; $android_url = 'https://play.google.com/store/apps/details?id=net.erabbit.aromadiffuser.oska';//'app-release.apk'; $ios_url = 'https://itunes.apple.com/us/app/madebyzen-oska-aroma-diffuser/id1188964652?&ls=1&mt=8'; $app_logo_url = '../images/app_logo_oska.png'; ?> <html> <head> <meta charset="utf-8"> <title><?php echo $title; ?></title> <style type="text/css"> body{background: url(<?php echo $app_logo_url; ?>) #FFF no-repeat center;} .button{ display: inline-block; position: relative; margin: 10px; padding: 20 40px; text-transform: uppercase; text-align: center; text-decoration: none; text-shadow: 1px 1px 1px rgba(255,255,255,.22); font: bold 40px/45px Arial, sans-serif; -webkit-border-radius: 30px; -moz-border-radius: 30px; border-radius: 30px; -webkit-box-shadow: 1px 1px 1px rgba(0,0,0,.29), inset 1px 1px 1px rgba(255,255,255,.44); -moz-box-shadow: 1px 1px 1px rgba(0,0,0,.29), inset 1px 1px 1px rgba(255,255,255,.44); box-shadow: 1px 1px 1px rgba(0,0,0,.29), inset 1px 1px 1px rgba(255,255,255,.44); -webkit-transition: all 0.15s ease; -moz-transition: all 0.15s ease; -o-transition: all 0.15s ease; -ms-transition: all 0.15s ease; transition: all 0.15s ease; color: #19667d; background: #70c9e3; /* Old browsers */ background: -moz-linear-gradient(top, #70c9e3 0%, #39a0be 100%); /* FF3.6+ */ background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#70c9e3), color-stop(100%,#39a0be)); /* Chrome,Safari4+ */ background: -webkit-linear-gradient(top, #70c9e3 0%,#39a0be 100%); /* Chrome10+,Safari5.1+ */ background: -o-linear-gradient(top, #70c9e3 0%,#39a0be 100%); /* Opera 11.10+ */ background: -ms-linear-gradient(top, #70c9e3 0%,#39a0be 100%); /* IE10+ */ background: linear-gradient(top, #70c9e3 0%,#39a0be 100%); /* W3C */ } .button span { display: block; text-transform: none; font: italic normal 20px/22px Georgia, sans-serif; text-shadow: 2px 2px 2px rgba(255,255,255, .12); } .button:hover { -webkit-box-shadow: 1px 1px 1px rgba(0,0,0,.29), inset 0px 0px 2px rgba(0,0,0, .5); -moz-box-shadow: 1px 1px 1px rgba(0,0,0,.29), inset 0px 0px 2px rgba(0,0,0, .5); box-shadow: 1px 1px 1px rgba(0,0,0,.29), inset 0px 0px 2px rgba(0,0,0, .5); } .button:active { -webkit-box-shadow: inset 0px 0px 3px rgba(0,0,0, .8); -moz-box-shadow: inset 0px 0px 3px rgba(0,0,0, .8); box-shadow: inset 0px 0px 3px rgba(0,0,0, .8); } .atbottom { position: absolute; bottom: 0; left: 10%; right: 10%; } /* Green Color */ .green { color: #3e5706; background: #a5cd4e; /* Old browsers */ background: -moz-linear-gradient(top, #a5cd4e 0%, #6b8f1a 100%); /* FF3.6+ */ background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#a5cd4e), color-stop(100%,#6b8f1a)); /* Chrome,Safari4+ */ background: -webkit-linear-gradient(top, #a5cd4e 0%,#6b8f1a 100%); /* Chrome10+,Safari5.1+ */ background: -o-linear-gradient(top, #a5cd4e 0%,#6b8f1a 100%); /* Opera 11.10+ */ background: -ms-linear-gradient(top, #a5cd4e 0%,#6b8f1a 100%); /* IE10+ */ background: linear-gradient(top, #a5cd4e 0%,#6b8f1a 100%); /* W3C */ } /* Blue Color */ .blue { color: #19667d; background: #70c9e3; /* Old browsers */ background: -moz-linear-gradient(top, #70c9e3 0%, #39a0be 100%); /* FF3.6+ */ background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#70c9e3), color-stop(100%,#39a0be)); /* Chrome,Safari4+ */ background: -webkit-linear-gradient(top, #70c9e3 0%,#39a0be 100%); /* Chrome10+,Safari5.1+ */ background: -o-linear-gradient(top, #70c9e3 0%,#39a0be 100%); /* Opera 11.10+ */ background: -ms-linear-gradient(top, #70c9e3 0%,#39a0be 100%); /* IE10+ */ background: linear-gradient(top, #70c9e3 0%,#39a0be 100%); /* W3C */ } .topright { position:absolute; top:0; right:0; } #mask{ display: none; position: absolute; top: 0%; left: 0%; width: 100%; height: 100%; background-color: black; z-index:101; -moz-opacity: 0.7; opacity:.70; filter: alpha(opacity=70);} #top{display: none; z-index:102} </style> <script type="text/javascript"> function checkForWechat(){ function is_weixin() { var ua = navigator.userAgent.toLowerCase(); if (ua.match(/MicroMessenger/i) == "micromessenger") { return true; } else { return false; } } var isWeixin = is_weixin(); if(isWeixin){ document.getElementById("mask").style.display="block"; document.getElementById("top").style.display="block"; } } </script> </head> <body onload="checkForWechat()"> <?php $user_agent = $_SERVER['HTTP_USER_AGENT']; if(stristr($_SERVER['HTTP_USER_AGENT'],'Android')) { echo '<a href="'.$android_url.'" class="green button atbottom">Download<span>from Google Play</span></a>'; }else if(stristr($_SERVER['HTTP_USER_AGENT'],'iPhone')){ echo '<a href="'.$ios_url.'" class="blue button atbottom">Download<span>from App Store</span></a>'; }else { echo ' for iOS users, please download from App Store:&nbsp;<br/><img src="../images/apple_logo.png"/><a href="'.$ios_url.'" class="blue button">Download<span>from App Store</span></a> <br/> for Android users, please download from Google Play:&nbsp;<br/><img src="../images/android_logo.png"/><a href="'.$android_url.'" class="green button">Download<span>from Google Play</span></a> '; } ?> <div id="mask"></div> <div id="top" class="topright"><font size="40px" color="#ffffff">Please open this page in browser&nbsp;</font><img src="../images/arrow.png"/></div> </body> </html>
3164a159827f9af0f3ccd9f3c141d42b87e1a84e
[ "PHP" ]
1
PHP
rabbitom/app
86795e7162709ed2b29ea22b1ed53c51dd30a9ed
a77f4b1f3509b9dac7709293c41e802e166a8140
refs/heads/master
<file_sep>/* * Copyright (c) 2016, prpl Foundation * * Permission to use, copy, modify, and/or distribute this software for any purpose with or without * fee is hereby granted, provided that the above copyright notice and this permission notice appear * in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE * FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * * This code was written by <NAME> at Embedded System Group (GSE) at PUCRS/Brazil. * */ /** * @file reset.c * * @section DESCRIPTION * * This is a software reset driver to the PIC32MZ Starter Kit since it lacks a reset button. * * */ #include <qemu_virt.h> #include <driver.h> #include <globals.h> #include <libc.h> #include <hal.h> #include <interrupts.h> /** * @brief Performs a software reset to the board. * */ void SoftReset(){ } /** * @brief This call must be used in cases where the hypervisor is halted and must be reseted. */ void wait_for_reset(){ } /** * @brief Interrupt handler for the SW1 button. */ void sw1_button_handler(){ } /** * @brief Driver init. Registers the interrupt handler routine and configures the RB12 pin * associated to the SW1 button. */ void sw1_button_interrupt_init(){ } driver_init(sw1_button_interrupt_init); <file_sep>/* Copyright (c) 2016, prpl Foundation Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. This code was written by <NAME> at Embedded System Group (GSE) at PUCRS/Brazil. */ #ifndef __LINKED_LIST_H #define __LINKED_LIST_H #include<types.h> struct list_t { void *elem; /*!< pointer to list node data */ struct list_t *next; /*!< pointer to the next list node */ }; int32_t list_append(struct list_t **lst, void *item); int32_t list_remove_all(struct list_t **lst); int32_t list_count(struct list_t *lst); #endif /* !LINKED_LIST_H */ <file_sep># Define your additional include paths #INC_DIRS += #Aditional C flags #CFLAGS += #Aditional Libraries #LIBS += #default stack size 512 bytes STACK_SIZE = 512 #Include your additional mk files here. app: $(CC) $(CFLAGS) $(INC_DIRS) $(TOPDIR)apps/$(APP)/$(APP).c -o $(TOPDIR)apps/$(APP)/$(APP).o <file_sep>/* Copyright (c) 2016, prpl Foundation Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. This code was written by <NAME> at Embedded System Group (GSE) at PUCRS/Brazil. */ /* * Baikal-T (P5600) core address definitions * */ #ifndef _BAIKAL_T1_H #define _BAIKAL_T1_H #define UART0_BASE(a) *(volatile unsigned*) (0xBF04A000 + (a<<2)) #define UART0_RBR UART0_BASE(0) #define UART0_IER UART0_BASE(1) #define UART0_IIR UART0_BASE(2) #define UART0_LCR UART0_BASE(3) #define UART0_LSR UART0_BASE(5) #define UART0_MSR UART0_BASE(6) #define UART1_BASE(a) *(volatile unsigned*) (0xBF04B000 + (a<<2)) #define UART1_RBR UART1_BASE(0) #define UART1_IER UART1_BASE(1) #define UART1_IIR UART1_BASE(2) #define UART1_LCR UART1_BASE(3) #define UART1_LSR UART1_BASE(5) #define UART1_MSR UART1_BASE(6) typedef union { struct{ unsigned exl:1; unsigned k:1; unsigned :1; unsigned u:1; unsigned ie:1; unsigned event:10; unsigned :8; unsigned ec:2; unsigned :6; unsigned m:1; }; struct{ unsigned w:32; }; } perf_control_t; #endif /* _BAIKAL_T1_H */ <file_sep>#ifndef _PLATFORM_H #define _PLATFORM_H #include <pic32mz.h> #define UARTSTAT U4STA #define UARTTXREG U4TXREG #define UART_IRQ_RX IRQ_U4RX #define UART_IRQ_TX IRQ_U4TX #endif <file_sep>/* Copyright (c) 2016, prpl Foundation Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. This code was written by <NAME> at Embedded System Group (GSE) at PUCRS/Brazil. */ /* This example is used to measure the hypervisor's interrupt redirection latency. * * */ #include <arch.h> #include <libc.h> #include <hypercalls.h> #include <guest_interrupts.h> #include <platform.h> #include <io.h> volatile uint32_t t2 = 0; void irq_pin(){ uint32_t d; d = readio(PORTD); if(d & (1<<10)){ writeio(LATFSET, 1 << 4); }else{ writeio(LATFCLR, 1 << 4); } //writeio(LATFINV, 1 << 4); t2++; //putchar('!'); reenable_interrupt(GUEST_USER_DEFINED_INT_1); } int main() { uint32_t timer = 0; interrupt_register(irq_pin, GUEST_USER_DEFINED_INT_1); ENABLE_LED1; /* RD0 as output*/ writeio(TRISFCLR, 1 << 4); writeio(LATFCLR, 1 << 4); writeio(CNPUFCLR, 1 << 4); writeio(CNPDFCLR, 1 << 4); writeio(ANSELFCLR, 1 << 4); /* configure interrupt for PORTD pin RD10*/ writeio(CNCONDSET, 0x8000); writeio(CNENDSET, 1 << 10); while (1){ if(wait_time(timer, 1000)) { printf("t2 %d\n", t2); /* Blink Led */ TOGGLE_LED1; timer = mfc0(CP0_COUNT, 0); } } return 0; } <file_sep>/* Copyright (c) 2016, prpl Foundation Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. This code was written by <NAME> at Embedded System Group (GSE) at PUCRS/Brazil. */ /* * Baikal-T (P5600) core address definitions * */ #ifndef _GRP_CONTEXT_H #define _GRP_CONTEXT_H #include <types.h> void gpr_context_restore(long* gpr_p); void gpr_context_save(long* gpr_p); /** * These functions can read/write the saved registers from the stack. * On P5600, the guests share the same GPR set (GPR Shadows are not implemented). Thus, * the hypercall parameters are read/write from the stack. */ void MoveToPreviousGuestGPR(long reg, uint64_t value); uint64_t MoveFromPreviousGuestGPR(long reg); #endif /* _GRP_CONTEXT_H */ <file_sep>## What is the Hellfire Hypervisor? The Hellfire Hypervisor is the industry-first open source hypervisor specifically designed to provide security through separation for the billions of embedded connected devices that power the Internet of Things. The MIPS M5150 version of the Hellfire Hypervisor implements MIPS VZ extensions to provide a lightweight isolation layer for Microchip Technology’s PIC32MZ microcontrollers. In addition to real-time hardware virtualization, the hypervisor provides additional security services including PUF authentication and SecureInterVM communications. The Hellfire Hypervisor features minimal attack surface - less than 7,000 lines of code, limited footprint – 30KB flash, 4K RAM/VM, up to eight isolated domains. Performance tests show negligible overhead for context switching and interVM communications. The Hellfire Hypervisor is a open source framework and are released under prpl Foundation permissive license – see http://prplfoundation.org/ip-policy. ## How to build? Once you have the building environment configured, go to a platform board folder: prpl-hypervisor/platform/pic32mz_starter_kit; prpl-hypervisor/platform/pic32mz_chipkit_Wifire, or; prpl-hypervisor/platform/pic32mz_curiosity. Then, perform: make && make load See the complete documentation in https://github.com/hellfire-project/hellfire-hypervisor/wiki <file_sep> lib: $(CC) $(CFLAGS) $(INC_DIRS) $(TOPDIR)lib/libc.c -o $(TOPDIR)apps/$(APP)/libc.o $(CC) $(CFLAGS) $(INC_DIRS) $(TOPDIR)lib/malloc.c -o $(TOPDIR)apps/$(APP)/malloc.o $(CC) $(CFLAGS) $(INC_DIRS) $(TOPDIR)lib/network.c -o $(TOPDIR)apps/$(APP)/network.o <file_sep>/* Copyright (c) 2016, prpl Foundation Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. This code was written by <NAME> at Embedded System Group (GSE) at PUCRS/Brazil. */ /** * @file exception.c * * @section DESCRIPTION * * General exception handler implementation. * */ #include <types.h> #include <hal.h> #include <config.h> #include <exception.h> #include <libc.h> #include <globals.h> #include <mips_cp0.h> #include <proc.h> #include <hypercall.h> #include <board.h> #include <scheduler.h> #include <vcpu.h> #include <timer.h> uint32_t count = 0; /** * @brief Guest exit exception handler. * */ void guest_exit_exception(uint32_64_t cause, uint32_64_t mepc){ uint32_64_t mstatus; mstatus = read_csr(mstatus); switch (cause) { case IRQ_S_EXT: hypercall_execution(); break; default: WARNING("Stopping VM %d due to cause error %d mepc:0x%x mstatus:0x%x", vcpu_in_execution->vm->id, cause, mepc, mstatus); vcpu_in_execution->state = VCPU_BLOCKED; break; } /* Advance to the next instruction. */ vcpu_in_execution->pc = mepc+4; setEPC(vcpu_in_execution->pc); if(vcpu_in_execution->state == VCPU_BLOCKED){ run_scheduler(); } } /** * @brief General exception handler. * */ void general_exception_handler(uint32_64_t mcause, uint32_64_t mepc){ uint32_t cause = get_field(mcause, MCAUSE_MASK); /* Interruption */ if(MCAUSE_INT & mcause){ switch(cause){ case IRQ_M_TIMER: timer_interrupt_handler(); break; default: printf("\nDefault Interruption\n"); } }else{ /* Exceptions */ guest_exit_exception(cause, mepc); } } <file_sep>#ifndef _PLATFORM_H #define _PLATFORM_H #include <pic32mz.h> #define UARTSTAT U1STA #define UARTTXREG U1TXREG #define UART_IRQ_RX IRQ_U1RX #define UART_IRQ_TX IRQ_U1TX #endif <file_sep>/* Copyright (c) 2016, prpl Foundation Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. This code was written by <NAME> at Intrinsic-ID. */ #ifndef PUF_H_ #define PUF_H_ #include "iidprplpuf/iid_errors.h" #ifdef __cplusplus extern "C" { #endif /*! \brief The function return type \details */ typedef uint8_t return_t; #define PUF_INVALID_COMMAND 0xEE #define PUF_GETSOFTWAREVERSION 0x01 #define PUF_STOP 0x02 #define PUF_WRAPKEY 0x03 #define PUF_UNWRAPKEY 0x04 #define PUF_GETAUTHRESPONSE 0x05 #define LABEL_SIZE 6 #define CONTEXT_SIZE 6 #define KEYCODE_OVERHEAD 40 /*! \brief Indicates a key without special key properties. \details This define indicates that the key that will be wrapped has no special properties. */ #define KEY_PROP_NONE 0x0000 /*! \brief Indicates a key that will be used as an authentication key. \details This define indicates that the key that will be wrapped is an authentication key. This kind of key can only be used in authentication functions and cannot be unwrapped separately. */ #define KEY_PROP_AUTHENTICATION 0x0001 /*! \brief Get the software version. \details Get the software version of the PUF module. \param[out] majorVersion Pointer to a byte for holding the major software version. \param[out] minorVersion Pointer to a byte for holding the minor software version. \returns \ref IID_SUCCESS */ extern return_t PUF_GetSoftwareVersion(uint8_t * const majorVersion, uint8_t * const minorVersion); /*! \brief Delete the Intrinsic Key from Memory. \details The previously reconstructed Intrinsic Key is erased from memory. \pre \ref PUF_Init has to be called before \ref PUF_Stop may be called. \returns \ref IID_SUCCESS. */ extern return_t PUF_Stop(void); /*! \brief Wrap the given key. \details The function PUF_WrapKey wraps the given key and returns it as a key code. \par A symmetric key is secured by the PUF module using the Wrap functionality. \par IK has to be available in memory when calling Wrap. \param[in] key A buffer that holds the key to wrap. \param[in] label A buffer that holds the an API identifier \param[in] context A buffer that holds the Application Identifier. \param[in] keySize The size in bytes of the key that will be wrapped. This has to be a multiple of 4 bytes. \param[in] keyProperties The properties of the key (key type, protection, etc). \param[in] keyIndex The index of the key that will be wrapped. \param[out] keyCode A buffer that will hold the Key Code. This has to be aligned to 32 bits. \pre \ref PUF_Start has to be called before \ref PUF_WrapKey may be called. \returns \ref IID_SUCCESS if success. */ return_t PUF_WrapKey( const uint8_t * const key, const uint8_t * const label, const uint8_t * const context, uint16_t keySize, uint16_t keyProperties, uint8_t keyIndex, uint8_t * const keyCode); /*! \brief Unwrap the given key code. \details With PUF_WrapKey, a previously wrapped key is retrieved from a key code. \par Keys that are stored securely can be retrieved from their key code using the Unwrap functionality. \par Intrinsic Key has to be available in memory when calling Unwrap. \param[in] keyCode A buffer that holds the key code. This has to be aligned to 32 bits. \param[in] label A buffer that holds the an API identifier. \param[in] context A buffer that holds the Application Identifier. \param[out] keySize A buffer that will hold the size of the unwrapped key. \param[out] keyIndex A buffer that will hold the index of the unwrapped key. \param[out] key A buffer that will hold the unwrapped key. \pre \ref PUF_Start has to be called before \ref PUF_UnwrapKey may be called. \returns \ref IID_SUCCESS if success. \returns \ref IID_ERROR_INV_KEYCODE if keyCode is corrupted or manipulated. \note Only non-authentication keys can be unwrapped. */ return_t PUF_UnwrapKey( const uint8_t * const keyCode, const uint8_t * const label, const uint8_t * const context, uint16_t * keySize, uint8_t * keyIndex, uint8_t * const key); /*! \brief Calculate the response to a given challenge. \details For authentication of this software, a response will be calculated based on the authentication key which has been wrapped into a key code and a challenge. \param[in] label A buffer that holds the an API identifier \param[in] context A buffer that holds the Application Identifier. \param[in] keyCode A buffer that holds the key code of the authentication key. This has to be aligned to 32 bits. \param[in] challenge A buffer holding the challenge to calculate the response for. \param[in] challengeSize The size of the challenge in bytes. This must be a multiple of 16 bytes. \param[out] response A buffer for holding the response. This buffer has to be 16 bytes long and aligned to 32 bits. \pre \ref PUF_Start has to be called before \ref PUF_GetAuthenticationResponse may be called. \returns \ref IID_SUCCESS if success. \returns \ref IID_ERROR_INV_KEYCODE if keyCode is corrupted or manipulated. */ return_t PUF_GetAuthenticationResponse( const uint8_t * const label, const uint8_t * const context, const uint8_t * const keyCode, const uint8_t * const challenge, uint16_t challengeSize, uint8_t * const response); /*@}*/ /*! \addtogroup Platform */ /*@{*/ #ifdef _MSC_VER /*! \brief Macro to force memory alignment \details Macro to force memory alignment. */ #define PRE_HIS_ALIGN __declspec(align(4)) /*! \brief Macro to force memory alignment \details Macro to force memory alignment. */ #define POST_HIS_ALIGN #else /*! \brief Macro to force memory alignment \details Macro to force memory alignment. */ #define PRE_HIS_ALIGN /*! \brief Macro to force memory alignment \details Macro to force memory alignment. */ #define POST_HIS_ALIGN __attribute__ ((aligned (4))) #endif /* _MSC_VER */ /*@}*/ /*! \addtogroup Structures */ /*@{*/ #define MAX_KEY_SIZE 88 #define MAX_KEYCODE_SIZE 128 #define MAX_CHALLENGE_SIZE 64 typedef struct puf_getsoftwareversion { uint8_t majorVersion; uint8_t minorVersion; } puf_getsoftwareversion_t; typedef struct puf_wrapkey { uint8_t key[MAX_KEY_SIZE]; uint8_t label[LABEL_SIZE]; uint8_t context[CONTEXT_SIZE]; uint16_t keySize; uint16_t keyProperties; uint8_t keyIndex; PRE_HIS_ALIGN uint8_t keyCode[MAX_KEYCODE_SIZE] POST_HIS_ALIGN; } puf_wrapkey_t; typedef struct puf_unwrapkey { PRE_HIS_ALIGN uint8_t keyCode[MAX_KEYCODE_SIZE] POST_HIS_ALIGN; uint8_t label[LABEL_SIZE]; uint8_t context[CONTEXT_SIZE]; uint16_t keySize; uint8_t keyIndex; uint8_t key[MAX_KEY_SIZE]; } puf_unwrapkey_t; typedef struct puf_getauthresponse { uint8_t label[LABEL_SIZE]; uint8_t context[CONTEXT_SIZE]; PRE_HIS_ALIGN uint8_t keyCode[MAX_KEYCODE_SIZE] POST_HIS_ALIGN; uint8_t challenge[MAX_CHALLENGE_SIZE]; uint16_t challengeSize; PRE_HIS_ALIGN uint8_t response[16] POST_HIS_ALIGN; } puf_getauthresponse_t; typedef union puf_union { puf_getsoftwareversion_t puf_getsoftwareversion; puf_wrapkey_t puf_wrapkey; puf_unwrapkey_t puf_unwrapkey; puf_getauthresponse_t puf_getauthresponse; } puf_union_t; typedef struct puf_message { puf_union_t puf_struct; union { uint8_t command; uint8_t response; }; } puf_message_t; /*@}*/ #ifdef __cplusplus } #endif #endif /* PUF_H_ */ <file_sep>/* C o*pyright (c) 2016, prpl Foundation Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. This code was written by <NAME> at Embedded System Group (GSE) at PUCRS/Brazil. */ #ifndef _IO_H #define _IO_H #include <arch.h> #define ENABLE_LED1 writeio(TRISECLR, 8) #define ENABLE_LED2 writeio(TRISECLR, 0x10); #define ENABLE_LED3 writeio(TRISECLR, 0x20) #define ENABLE_LED4_BLUE writeio(TRISBCLR, 0x1) #define ENABLE_LED4_GREEN writeio(TRISBCLR, 0x2) #define ENABLE_LED4_YELLOW writeio(TRISBCLR, 0x10) #define TOGGLE_LED1 writeio(LATEINV, 8) #define TOGGLE_LED2 writeio(LATEINV, 0x10) #define TOGGLE_LED3 writeio(LATEINV, 0x20) #define TOGGLE_LED4_BLUE writeio(LATBINV, 0x1) #define TOGGLE_LED4_GREEN writeio(LATBINV, 0x2) #define TOGGLE_LED4_YELLOW writeio(LATBINV, 0x10) #endif <file_sep>#include <hypercall.h> #include <globals.h> #include <driver.h> #include <hypercall_defines.h> #include <scheduler.h> /** * @brief Driver init call. */ void remove_vms(){ uint32_t i; for(i=0;i<NVMACHINES;i++){ queue_remtail(scheduler_info.vcpu_ready_list); } INFO("All VMs removed from execution."); } driver_init(remove_vms); <file_sep>/* Copyright (c) 2016, prpl Foundation Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. This code was written by <NAME> at Embedded System Group (GSE) at PUCRS/Brazil. */ /** * @file pic32mz-puf-flash.c * * @section DESCRIPTION * * Specific driver for PUF access to flash. Required by Intrinsic-ID PUF implementation. */ #include <types.h> #include <pic32mz.h> #include <hal.h> #include <globals.h> #include <scheduler.h> #include <hypercall_defines.h> #include <hypercall.h> #include <libc.h> #include <driver.h> #include <mips_cp0.h> #include <globals.h> #include <interrupts.h> #include <pic32mz-puf-functions.h> /** * @brief Hypercall to read 1K byte from flash. * Calling convention (guest registers): * Input: a0 = Destination buffer. * Output: v0 = Number of bytes read or less than 0 for error. */ static void flash_read(){ uint32_t ret; uint8_t * dest = (uint8_t *) tlbCreateEntry((uint32_t) MoveFromPreviousGuestGPR(REG_A0), vm_in_execution->base_addr, sizeof(uint8_t) * 1024, 0xf, CACHEABLE); ret = flash_read1Kbuffer(dest); MoveToPreviousGuestGPR(REG_V0, ret); } /** * @brief Hypercall to write 1K byte to flash. * Calling convention (guest registers): * Input: a0 = Source buffer. * Output: v0 = Number of bytes read or less than 0 for error. */ static void flash_write(){ uint32_t ret; uint8_t * source = (uint8_t *) tlbCreateEntry((uint32_t) MoveFromPreviousGuestGPR(REG_A0), vm_in_execution->base_addr, sizeof(uint8_t) * 1024, 0xf, CACHEABLE); ret = flash_write1Kbuffer(source); MoveToPreviousGuestGPR(REG_V0, ret); } /** * @brief Initialize driver registering the hypervcalls. */ static void flash_puf_init(){ if (register_hypercall(flash_read, HCALL_FLASH_READ) < 0){ ERROR("Error registering the HCALL_FLASH_READ hypercall."); return; } if (register_hypercall(flash_write, HCALL_FLASH_WRITE) < 0){ ERROR("Error registering the HCALL_FLASH_WRITE hypercall."); return; } INFO("Driver for PUF access to Flash enabled.") } driver_init(flash_puf_init); <file_sep>/* Copyright (c) 2016, prpl Foundation Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. This code was written by <NAME> at Embedded System Group (GSE) at PUCRS/Brazil. */ /** * @file timer.c * * @section DESCRIPTION * * Timer interrupt subsystem. This timer is used for VCPU scheduling and * virtual timer interrupt injection on Guests. * * Every guest receive timer interrupt each 1ms. This will be replaced soon with * a configurable guest timer. */ #include <globals.h> #include <hal.h> #include <baikal-t1.h> #include <mips_cp0.h> #include <guest_interrupts.h> #include <scheduler.h> #include <interrupts.h> #include <libc.h> #define SYSTEM_TICK_INTERVAL (QUANTUM_SCHEDULER_MS * MILISECOND) #define QUEST_TICK_INTERVAL (GUEST_QUANTUM_MS * MILISECOND) static uint64_t read64_counter(){ return ((uint64_t)GIC_SH_COUNTERHI << 32) | GIC_SH_COUNTERLO; } static void write64_compare(uint64_t compare){ GIC_CL_COMPAREHI = compare >> 32; GIC_CL_COMPARELO = compare & 0xffffffff; } /** * @brief Configures the COMPARE register to the next interrupt. * * @param interval Time interval to the next interrupt in CPU ticks (CPU_FREQ/2) */ static void calc_next_timer_interrupt(uint32_t interval){ uint32_t count; count = mfc0(CP0_COUNT, 0); count += interval; mtc0(CP0_COMPARE, 0, count); } /** * @brief Time interrupt handler. * * Perfoms VCPUs scheduling and virtual timer interrupt injection on guests. */ static void timer_interrupt_handler(){ calc_next_timer_interrupt(SYSTEM_TICK_INTERVAL); run_scheduler(); } /** * @brief Configures the CP0 timer. * * This function will never return to the calling code. It waits for the * first timer interrupt. */ void start_timer(){ uint32_t temp; /* TODO: Missing interrupt registration */ register_interrupt(timer_interrupt_handler, 4); /* enable timer interrupt IM4 */ temp = mfc0(CP0_STATUS, 0); temp |= (STATUS_IM4 << STATUS_IM_SHIFT); mtc0(CP0_STATUS, 0, temp); INFO("Starting hypervisor execution.\n"); GIC_CL_COREi_TIMER_MAP = 0x80000002; mtc0(CP0_COUNT, 0, 0); mtc0(CP0_COMPARE, 0, 1000000); asm volatile ("ei"); asm volatile("ehb"); /* Wait for a timer interrupt */ asm("wait"); } <file_sep>/* Copyright (c) 2016, prpl Foundation Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. This code was written by <NAME> at Embedded System Group (GSE) at PUCRS/Brazil. */ /* Simple USB Bare-metal application that detects and read device's descriptors. */ #include <arch.h> #include <libc.h> #include <usb.h> #include <guest_interrupts.h> #include <hypercalls.h> /* OWI Robotic Arm */ #define IDPRODUCT 0 #define IDVENDOR 0x1267 struct descriptor_decoded descriptor; int main() { int32_t ret = 0, old = 0; uint32_t tm_poll = 0; printf("\nPlease connect any USB device."); while (1){ if(wait_time(tm_poll, 100)){ ret = usb_polling(); if (ret != old){ if(ret){ usb_device_descriptor((char*)&descriptor, sizeof(struct descriptor_decoded)); printf("\nDevice connected: idVendor 0x%x idProduct 0x%x", descriptor.idVendor, descriptor.idProduct); }else{ printf("\nDevice Disconnected"); } old = ret; } tm_poll = mfc0(CP0_COUNT, 0); } } return 0; } <file_sep>/* Copyright (c) 2016, prpl Foundation Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. This code was written by <NAME> at Embedded System Group (GSE) at PUCRS/Brazil. */ /** * @file vcpu.c * * @section DESCRIPTION * * VCPU related function calls (context save, restore and instruction emulation). */ #include <vcpu.h> #include <types.h> #include <libc.h> #include <globals.h> #include <hal.h> #include <proc.h> #include <scheduler.h> #include <guest_interrupts.h> /** * @brief Save the VCPU context. Saving only the necessary registers for * the supported OSs. */ void contextSave(){ vcpu_t *vcputosave; if (!is_vcpu_executing){ return; } vcputosave = vcpu_in_execution; if (vcputosave->init == 0){ /* FIXME: CSR registers to save? .*/ gpr_context_save(vcputosave->gpr); } fp_context_save((uint64_t*)vcputosave->fp_registers); vcputosave->cp0_registers[0] = read_csr(sstatus); vcputosave->cp0_registers[1] = read_csr(sie); vcputosave->cp0_registers[2] = read_csr(sip); vcputosave->pc = read_csr(mepc); } /** * @brief The hypervisor performs this routine when there is * no VCPU read to execute. In this case the hypervisor * will wait by the next interrupt event. */ static void cpu_idle(){ while(1){ /* No VCPU read for execution. Wait by the next interrupt. */ /* FIXME: Code to put the processor in idle mode. */ } } /** * @brief Configure the processor to enter in idle mode. * */ static void config_idle_cpu(){ write_csr(mepc, (long)cpu_idle); } /** * @brief Restore the VCPU context on context switch. */ void contextRestore(){ vcpu_t *vcpu = vcpu_in_execution; /* There are not VCPUs ready to execute. Put CPU in adle mode. */ if(!vcpu){ config_idle_cpu(); return; } /* Mark the VCPU as initialized. */ if(vcpu_in_execution->init){ vcpu_in_execution->init = 0; }else{ write_csr(sstatus, vcpu->cp0_registers[0]); write_csr(sie, vcpu->cp0_registers[1]); write_csr(sip, vcpu->cp0_registers[2] | vcpu->guestclt2); } fp_context_restore((uint32_64_t*)vcpu->fp_registers); /* FIXME: Code for context restore should be here!!*/ setEPC(vcpu->pc); #if defined(RISCV64) write_csr(mstatus, (read_csr(mstatus) & 0xFFFFFFFFFFFFEFFF)); write_csr(satp, (8ULL<<60) | (((uint64_t)vcpu->vm->id)<<44) | (uint64_t)vcpu->vm->root_page_table >> 12); #else write_csr(mstatus, (read_csr(mstatus) & 0xFFFFEFFF)); write_csr(satp, (1<<31) | (((uint32_64_t)vcpu->vm->id)<<22) | (uint32_64_t)vcpu->vm->root_page_table >> 12); #endif asm volatile ("SFENCE.VMA"); gpr_context_restore(vcpu->gpr); } /** * @brief Call low level instruction emulation. Not all architectures will * implement it. * * @param epc Error PC. * @return 0 on success, otherwise error. */ uint32_t instruction_emulation(uint32_t epc){ return 0; } <file_sep> /** * @file uart_driver.c * * @section DESCRIPTION * * Interrupt-driven virtualized console driver that queues the guest's UART read/write calls. * * The guest's call the HCALL_UART_SEND/HCALL_UART_RECV * hypercalls being blocked to wait by UART tranfers to complete * when necessary. * */ #include <globals.h> #include <hal.h> #include <libc.h> #include <proc.h> #include <hypercall_defines.h> #include <hypercall.h> #include <driver.h> #include <interrupts.h> #include <platform.h> /** * @brief UART TX hypercall. * Write characters to the hardware queue and block the VCPU when * the queue is full and still there are characteres to tranfer. */ static void send(){ /*TODO: Implement interrupt-driven support to avoid to block the hypervisor for long periods. */ uint32_t i = 0; char* str = (char*)MoveFromPreviousGuestGPR(REG_A0); uint32_t size = MoveFromPreviousGuestGPR(REG_A1); /* Map the guest's buffer. */ //char* str_mapped = (char*)tlbCreateEntry((uint32_t)str, vm_in_execution->base_addr, size, 0xf, NONCACHEABLE); char* str_mapped = vm_in_execution->base_addr - 0x80000000 + str; for(i=0; i<size; i++){ while ((UART0_CTRL_ADDR(UART_LSR) & UART_LSR_RI) == 0); UART0_CTRL_ADDR(UART_THR) = str_mapped[i]; } MoveToPreviousGuestGPR(REG_A0, size); } /** * @brief UART Driver init call. */ static void uart_driver_init(){ if (register_hypercall(send, HCALL_UART_SEND) < 0){ ERROR("Error registering the HCALL_GET_VM_ID hypercall"); return; } printf("\nUART driver enabled."); } driver_init(uart_driver_init); <file_sep>hal: $(CC) $(CFLAGS) $(INC_DIRS) $(TOPDIR)arch/mips/pic32mz/eth.c -o $(TOPDIR)apps/$(APP)/eth.o $(CC) $(CFLAGS) $(INC_DIRS) $(TOPDIR)arch/mips/pic32mz/platform.c -o $(TOPDIR)apps/$(APP)/platform.o $(CC) $(CFLAGS) $(INC_DIRS) $(TOPDIR)arch/mips/pic32mz/crt0.s -o $(TOPDIR)apps/$(APP)/crt.o <file_sep>/* Copyright (c) 2016, prpl Foundation Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. This code was written by <NAME> at Embedded System Group (GSE) at PUCRS/Brazil. */ /* Simple TCP listener server using picoTCP stack To compile this application, first download the picoTCP sources from: https://github.com/tass-belgium/picotcp/releases/tag/prpl-v0.1. Then, compile with: make CROSS_COMPILE=mips-mti-elf- PLATFORM_CFLAGS="-EL -Os -c -Wa,-mvirt -mips32r5 -mtune=m14k \ -mno-check-zero-division -msoft-float -fshort-double -ffreestanding -nostdlib -fomit-frame-pointer \ -G 0" DHCP_SERVER=0 SLAACV4=0 TFTP=0 AODV=0 IPV6=0 NAT=0 PING=1 ICMP4=1 DNS_CLIENT=0 MDNS=0 DNS_SD=0 \ SNTP_CLIENT=0 PPP=0 MCAST=1 MLD=0 IPFILTER=0 ARCH=pic32 The compiled picoTCP directory tree must be at the same directory level of the prpl-hypervisor, example: ~/hyper /prp-hypervisor /picotcp Once the application is compiled and uploaded to the board, you can use telnet or nc (netcat) to interact with this demo connecting to the 192.168.0.2 port 80. */ #include <pico_defines.h> #include <pico_stack.h> #include <pico_ipv4.h> #include <pico_tcp.h> #include <pico_socket.h> #include <arch.h> #include <eth.h> #include <guest_interrupts.h> #include <hypercalls.h> #include <platform.h> #include <libc.h> #include <eth.h> #include <pico_https_server.h> #include <pico_https_util.h> #include "SSL_keys.h" #include "www_files.h" #ifdef HAVE_CONFIG_H #include <config.h> #endif //#include <wolfssl/options.h> #include <wolfssl/wolfcrypt/settings.h> #include <wolfssl/ssl.h> #include <wolfssl/wolfcrypt/rsa.h> #include <wolfssl/wolfcrypt/memory.h> #include <wolfssl/wolfcrypt/error-crypt.h> #include <wolfssl/wolfcrypt/tfm.h> #include <wolfssl/wolfcrypt/logging.h> //#include <wolfssl/ssl.h> #define LISTENING_PORT 80 #define MAX_CONNECTIONS 1 #define ETH_RX_BUF_SIZE 1536 static char msg1[] = "\nWelcome on the prpl-Hypervisor and picoTCP demo. "; static char msg2[] = "\nWrite a message and press enter: "; static char msg3[] = "\nEcho message: "; static char rx_buf[ETH_RX_BUF_SIZE] = {0}; static struct pico_socket *s = NULL; static struct pico_ip4 my_eth_addr, netmask; static struct pico_device *pico_dev_eth; volatile unsigned int pico_ms_tick = 0; static uint32_t cp0_ms_ticks = CPU_SPEED/2/1000; static const char toggledString[] = "Led toggled!"; static uint32_t download_progress = 1u; static uint32_t length_max = 1u; static uint8_t http_not_found; int close(int __fildes ){ return 0; } static uint32_t calculate_ms_passed(uint32_t old_ticks, uint32_t new_ticks) { uint32_t diff_ticks; if (new_ticks >= old_ticks) diff_ticks = new_ticks - old_ticks; else diff_ticks = 0xffffffff - (old_ticks - new_ticks); return diff_ticks / cp0_ms_ticks; } void irq_timer() { static int prev_init = 0; static uint32_t prev_count = 0; uint32_t cur_count = mfc0(CP0_COUNT, 0); if (!prev_init){ prev_count = mfc0(CP0_COUNT, 0); prev_init = 1; } /* pico_ms_tick is not 100% accurate this way but at this point it's not required * currently there's a 10% accuracy loss(1000ms only produces 900 pico_ms_ticks) */ if (cur_count >= prev_count + cp0_ms_ticks){ pico_ms_tick += calculate_ms_passed(prev_count, cur_count); prev_count = cur_count; } } /************************** PRIVATE FUNCTIONS *************************/ const struct Www_file * find_www_file(char * filename) { uint16_t i; for(i = 0; i < num_files; i++) { if(strcmp(www_files[i].filename, filename) == 0) { return &www_files[i]; } } return NULL; } /*** START HTTPS server ***/ #define SIZE 1 * 1024 char http_buffer[SIZE]; void serverWakeup(uint16_t ev, uint16_t conn) { char * body; uint32_t read = 0; if(ev & EV_HTTPS_CON) { printf("New connection received\n"); pico_https_server_accept(); } if(ev & EV_HTTPS_REQ) /* new header received */ { char *resource; int method; printf("Header request received\n"); resource = pico_https_getResource(conn); if(strcmp(resource, "/") == 0) { resource = "/stm32f4.html"; } method = pico_https_getMethod(conn); if(strcmp(resource, "/board_info") == 0) { pico_https_respond(conn, HTTPS_RESOURCE_FOUND); strcpy(http_buffer, "{\"uptime\":"); pico_itoa(PICO_TIME(), http_buffer + strlen(http_buffer)); strcat(http_buffer, ", \"l1\":\""); strcat(http_buffer, "on"); strcat(http_buffer, "\", \"l2\":\""); strcat(http_buffer, "off"); strcat(http_buffer, "\", \"l3\":\""); strcat(http_buffer, "on"); strcat(http_buffer, "\", \"l4\":\""); strcat(http_buffer, "on"); strcat(http_buffer, "\", \"button\":\""); strcat(http_buffer, "up"); strcat(http_buffer, "\"}"); pico_https_submitData(conn, http_buffer, strlen(http_buffer)); } else if(strcmp(resource, "/ip") == 0) { pico_https_respond(conn, HTTPS_RESOURCE_FOUND); struct pico_ipv4_link * link; link = pico_ipv4_link_by_dev(pico_dev_eth); if (link) pico_ipv4_to_string(http_buffer, link->address.addr); else strcpy(http_buffer, "0.0.0.0"); pico_https_submitData(conn, http_buffer, strlen(http_buffer)); } else if(strcmp(resource,"/led1") == 0){ pico_https_respond(conn, HTTPS_RESOURCE_FOUND); pico_https_submitData(conn, toggledString, sizeof(toggledString)); } else if(strcmp(resource,"/led2") == 0){ pico_https_respond(conn, HTTPS_RESOURCE_FOUND); pico_https_submitData(conn, toggledString, sizeof(toggledString)); } else if(strcmp(resource,"/led3") == 0){ pico_https_respond(conn, HTTPS_RESOURCE_FOUND); pico_https_submitData(conn, toggledString, sizeof(toggledString)); } else if(strcmp(resource,"/led4") == 0){ pico_https_respond(conn, HTTPS_RESOURCE_FOUND); pico_https_submitData(conn, toggledString, sizeof(toggledString)); } else /* search in flash resources */ { struct Www_file * www_file; www_file = find_www_file(resource + 1); if(www_file != NULL) { uint16_t flags; flags = HTTPS_RESOURCE_FOUND | HTTPS_STATIC_RESOURCE; if(www_file->cacheable) { flags = flags | HTTPS_CACHEABLE_RESOURCE; } pico_https_respond(conn, flags); pico_https_submitData(conn, www_file->content, (int) *www_file->filesize); } else { /* not found */ /* reject */ printf("Rejected connection...\n"); pico_https_respond(conn, HTTPS_RESOURCE_NOT_FOUND); } } } if(ev & EV_HTTPS_PROGRESS) /* submitted data was sent */ { uint16_t sent, total; pico_https_getProgress(conn, &sent, &total); printf("Chunk statistics : %d/%d sent\n", sent, total); } if(ev & EV_HTTPS_SENT) /* submitted data was fully sent */ { printf("Last chunk post !\n"); pico_https_submitData(conn, NULL, 0); /* send the final chunk */ } if(ev & EV_HTTPS_CLOSE) { printf("Close request: %p\n", conn); if (conn) pico_https_close(conn); else printf(">>>>>>>> Close request w/ conn=NULL!!\n"); } if(ev & EV_HTTPS_ERROR) { printf("Error on server: %p\n", conn); //TODO: what to do? //pico_http_close(conn); } } /* END HTTP server */ int main() { uint8_t mac[6]; uint32_t timer = 0; /* Obtain the ethernet MAC address */ eth_mac(mac); const char *ipaddr="192.168.0.150"; uint16_t port_be = 0; interrupt_register(irq_timer, GUEST_TIMER_INT); /* Configure the virtual ethernet driver */ struct pico_device* eth_dev = PICO_ZALLOC(sizeof(struct pico_device)); if(!eth_dev) { return 0; } eth_dev->send = eth_send; eth_dev->poll = eth_poll; eth_dev->link_state = eth_link_state; if( 0 != pico_device_init((struct pico_device *)eth_dev, "virt-eth", mac)) { printf ("\nDevice init failed."); PICO_FREE(eth_dev); return 0; } /* picoTCP initialization */ printf("\nInitializing pico stack\n"); pico_stack_init(); wolfSSL_Debugging_ON(); pico_string_to_ipv4(ipaddr, &my_eth_addr.addr); pico_string_to_ipv4("255.255.255.0", &netmask.addr); pico_ipv4_link_add(eth_dev, my_eth_addr, netmask); port_be = short_be(LISTENING_PORT); /* WolfSSL initialization only, to make sure libwolfssl.a is needed */ pico_https_setCertificate(cert_pem_2048, sizeof(cert_pem_2048)); pico_https_setPrivateKey(privkey_pem_2048, sizeof(privkey_pem_2048)); pico_https_server_start(0, serverWakeup); while (1){ eth_watchdog(&timer, 500); /* pooling picoTCP stack */ pico_stack_tick(); } return 0; } <file_sep>var update_speed = 1000; function updateBoardInfo() { var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { var info = JSON.parse(xmlhttp.responseText); document.getElementById("uptime").innerHTML = info.uptime +" seconds"; document.getElementById("led1_state").style.backgroundColor = (info.l1 == "on") ? "#FF0000" : "#000000"; document.getElementById("led2_state").style.backgroundColor = (info.l2 == "on") ? "#FFFF00" : "#000000"; setTimeout(function(){updateBoardInfo();}, update_speed); } }; xmlhttp.open("GET","board_info",true); xmlhttp.timeout = 3000; xmlhttp.ontimeout = function() { updateBoardInfo(); } xmlhttp.onerror = function(e) { setTimeout(function(){updateBoardInfo()}, 1000); } xmlhttp.send(); } function toggle_led1(){ var ajaxPost = new XMLHttpRequest; ajaxPost.open("GET","led1",true); ajaxPost.send(""); } function toggle_led2(){ var ajaxPost = new XMLHttpRequest; ajaxPost.open("GET","led2",true); ajaxPost.send(""); } function getIp() { var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { document.getElementById("ip").innerHTML = xmlhttp.responseText; } } xmlhttp.open("GET","ip",true); xmlhttp.send(); } function getMAC() { var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { document.getElementById("mac").innerHTML = xmlhttp.responseText; } } xmlhttp.open("GET","mac",true); xmlhttp.send(); } <file_sep>/* Copyright (c) 2016, prpl Foundation Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. This code was written by <NAME> at Embedded System Group (GSE) at PUCRS/Brazil. */ /* * Baikal-T (P5600) address segments macro * * Based on arch/mips/include/asm/addrspace.h */ #ifndef _ASM_ADDR_H #define _ASM_ADDR_H /* * Returns the kernel segment base of a given address */ #define KSEGX(a) ((a) & 0xe0000000) /* * Returns the physical address of a CKSEGx / XKPHYS address */ #define CPHYSMASK 0x1fffffff #define CPHYSADDR(a) ((a) & CPHYSMASK) #define CKSEG0ADDR(a) (CPHYSADDR(a) | KSEG0) #define CKSEG1ADDR(a) (CPHYSADDR(a) | KSEG1) #define CKSEG2ADDR(a) (CPHYSADDR(a) | KSEG2) #define CKSEG3ADDR(a) (CPHYSADDR(a) | KSEG3) /* * Map an address to a certain kernel segment */ #define KSEG0ADDR(a) (CPHYSADDR(a) | KSEG0) #define KSEG1ADDR(a) (CPHYSADDR(a) | KSEG1) #define KSEG2ADDR(a) (CPHYSADDR(a) | KSEG2) #define KSEG3ADDR(a) (CPHYSADDR(a) | KSEG3) /* * Memory segments (32bit kernel mode addresses) * These are the traditional names used in the 32-bit universe. */ #define KUSEG 0x00000000 #define KSEG0 0x80000000 #define KSEG1 0xa0000000 #define KSEG2 0xc0000000 #define KSEG3 0xe0000000 #define CKUSEG 0x00000000 #define CKSEG0 0x80000000 #define CKSEG1 0xa0000000 #define CKSEG2 0xc0000000 #define CKSEG3 0xe0000000 #define UART_BASE 0x1F04A000 #endif /* _ASM_ADDR_H */ <file_sep>/* Copyright (c) 2016, prpl Foundation Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. This code was written by <NAME> at Embedded System Group (GSE) at PUCRS/Brazil. */ #ifndef USB_LIB_H #define USB_LIB_H #include <arch.h> #include <libc.h> struct descriptor_decoded{ uint8_t bLength; uint8_t bDescriptorType; uint16_t bcdUSB; uint8_t bDeviceClass; uint8_t bDeviceSubClass; uint8_t bDeviceProtocol; uint8_t bMaxPacketSize; uint16_t idVendor; uint16_t idProduct; uint16_t bcdDevice; uint8_t iManufacturer; uint8_t iProduct; uint8_t iSerialNumber; uint8_t bNumConfigurations; }; #endif <file_sep>#!/bin/sh TOOLS_DIR=$HOME/riscv-tools # Install required packages sudo apt update #sudo apt upgrade sudo apt --yes --force-yes install autoconf automake autotools-dev curl \ libmpc-dev libmpfr-dev libgmp-dev gawk build-essential \ bison flex texinfo gperf libtool patchutils bc zlib1g-dev pkg-config \ libglibmm-2.4-dev libpixman-1-dev libconfig-dev libexpat1-dev srecord mkdir -p $TOOLS_DIR cd $TOOLS_DIR # Download and install the toolchain. This can take hours! git clone https://github.com/riscv/riscv-gnu-toolchain.git cd riscv-gnu-toolchain git submodule update --init --recursive ./configure --prefix=$TOOLS_DIR/riscv-gnu-toolchain-bins32 --enable-gdb --with-arch=rv32gc make #compiles for riscv64 make clean ./configure --prefix=$TOOLS_DIR/riscv-gnu-toolchain-bins --enable-gdb make cd .. # Download and install the QEMU. wget https://download.qemu.org/qemu-4.2.0.tar.xz tar -xvf qemu-4.2.0.tar.xz cd qemu-4.2.0 ./configure --target-list=riscv64-softmmu,riscv32-softmmu make cd .. cd .. # Configure path. sed -i '/riscv-tools/d' ~/.profile echo >> ~/.profile echo "export PATH=\"\$PATH:\"$TOOLS_DIR/riscv-gnu-toolchain-bins32/bin:$TOOLS_DIR/riscv-gnu-toolchain-bins/bin\"\"" >> ~/.profile echo >> ~/.profile echo "***********************************************************" echo "You need to logout to the changes on you PATH make effect. " echo "***********************************************************" <file_sep>/* * Copyright (c) 2016, prpl Foundation * * Permission to use, copy, modify, and/or distribute this software for any purpose with or without * fee is hereby granted, provided that the above copyright notice and this permission notice appear * in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE * FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * * This code was written by <NAME> at Embedded System Group (GSE) at PUCRS/Brazil. * */ /** * @file platform.c * * @section DESCRIPTION * * Specific platform initialization. */ #include <qemu_virt.h> #include <config.h> #include <uart.h> /** * @brief Called on early hypervisor initialization and responsable for basic the * platform configuration. */ void early_platform_init(){ init_uart(115200, 9600, CPU_FREQ); } <file_sep>import serial from time import sleep import base64 import sys def readSerial(): while True: response = ser.readline(); return response # main ser = serial.Serial(port='/dev/ttyACM0', baudrate=115200, timeout=1) ser.isOpen() while(1): message = readSerial() # print message if 'keyCode' in message: hex_keyCode = message[9:-1] # print hex_keyCode break binary_keyCode = base64.b16decode(hex_keyCode.upper()) temp = list(binary_keyCode) temp[0] = '1' temp[1] = '2' temp[2] = '3' binary_keyCode_manipulated = "".join(temp) print 'Sending the wrong keyCode to the board (%d bytes)' % len(binary_keyCode_manipulated) for i in range(0, len(binary_keyCode_manipulated)): ser.write(binary_keyCode_manipulated[i]) ser.flush() ser.write('\n'.encode()) ser.flush() print 'Board response: %s' % readSerial() sleep(2) print 'Sending the correct keyCode to the board (%d bytes)' % len(binary_keyCode) for i in range(0, len(binary_keyCode)): ser.write(binary_keyCode[i]) ser.flush() ser.write('\n'.encode()) ser.flush() print 'Board response: %s' % readSerial() <file_sep>/* * Copyright (c) 2016, prpl Foundation * * Permission to use, copy, modify, and/or distribute this software for any purpose with or without * fee is hereby granted, provided that the above copyright notice and this permission notice appear * in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE * FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * * This code was written by <NAME> at Embedded System Group (GSE) at PUCRS/Brazil. * */ /** * @file instruction_emulation.c * * @section DESCRIPTION Functions to perform instruction emulation. This should be part of the vcpu.c infrastructure. * However, not all platforms will require it. For example, the PIC32MZ that only performs bare-metal applications * does not implement it. */ #include <globals.h> #include <instruction_emulation.h> /** * @brief Instruction emulation entry. * * @param */ uint32_t __instruction_emulation(uint32_t epc){ WARNING("Instruction emulation not implemented."); return 0; }<file_sep>#!/usr/bin/python #Copyright (c) 2016, prpl Foundation # #Permission to use, copy, modify, and/or distribute this software for any purpose with or without #fee is hereby granted, provided that the above copyright notice and this permission notice appear #in all copies. # #THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE #INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE #FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM #LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, #ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # #This code was written by <NAME> at Embedded System Group (GSE) at PUCRS/Brazil. import codecs import os listOfFiles = [ "bg_stripe.png", "pic32mz.jpg", "board.js", "cloud.png", "favicon.png", "index.html", "picotcp_style.css"] def write_permission(output): output.write("""/* Copyright (c) 2016, prpl Foundation Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. This code was written by <NAME> at Embedded System Group (GSE) at PUCRS/Brazil. */ """) #Write the C header file def write_header(output): write_permission(output) output.write(""" // THIS FILE IS AUTOMATICALLY GENERATED. // MODIFY html-sources/make-Cfiles.py INSTEAD OF THIS. #ifndef WEB_FILES_H_ #define WEB_FILES_H_ """) output.write(""" struct web_file { const char * filename; const int * filesize; const char * content; const int cacheable; }; extern const struct web_file web_files[%d]; extern const int num_web_files; """ % (len(listOfFiles), ) ) output.write("\n#endif\n") #Write the C file def write_c_file(output, path): write_permission(output) output.write(""" // THIS FILE IS AUTOMATICALLY GENERATED. // MODIFY sources/mkCfiles.py INSTEAD OF THIS. #include "web_files.h" """) hex_encoder = codecs.getencoder('hex') for name in listOfFiles: name_as_scores = name.replace(".","_") lenname = name_as_scores + "_len" count = 0; bin_handle = open(path + name,'rb') output.write("static const unsigned char %s[] = {\n " % (name_as_scores, ) ) while(1): c = bin_handle.read(1) if not c: break output.write("0x%s, " % (hex_encoder(c)[0].decode(), )) count+=1 if (count % 16 == 0): output.write("\n ") output.write("\n};\nstatic const int %s = %s;\n\n" % (lenname, count)) output.write("const struct web_file web_files[%d] = {\n"%(len(listOfFiles),)) for name in listOfFiles: name_as_scores = name.replace(".","_") lenname = name_as_scores + "_len" output.write(" { \"%s\", &%s, %s, 1 },\n"%(name, lenname, name_as_scores)) output.write("};\n") output.write("const int num_web_files = %d;\n\n"%(len(listOfFiles),)) local_path = os.path.dirname(os.path.realpath(__file__)) + '/' print local_path try: header_file = open(local_path + "../web_files.h",'w') c_file = open(local_path + "../web_files.c", 'w') except: print("Failed to open files for writing!") exit() write_header(header_file) write_c_file(c_file, local_path) header_file.close() c_file.close() <file_sep>#Copyright (c) 2016, prpl Foundation # #Permission to use, copy, modify, and/or distribute this software for any purpose with or without #fee is hereby granted, provided that the above copyright notice and this permission notice appear #in all copies. # #THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE #INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE #FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM #LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, #ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # #This code was written by <NAME> at Embedded System Group (GSE) at PUCRS/Brazil. # Define your additional include paths INC_DIRS += -I ../../../../picotcp/build/include/ -I $(TOPDIR)../../picotcp-modules/libhttp/ #Aditional C flags CFLAGS += -DPICOTCP -DPIC32 #Aditional Libraries LIBS += ../../../../picotcp/build/lib/libpicotcp.a #default stack size 512 bytes STACK_SIZE = 4096 #Include your additional mk files here. picotcp_modules_clone: if [ ! -d "$(TOPDIR)../../picotcp-modules" ]; then \ git clone https://github.com/tass-belgium/picotcp-modules.git $(TOPDIR)../../picotcp-modules; \ fi picotcp_modules_compile: $(CC) $(CFLAGS) $(INC_DIRS) $(TOPDIR)../../picotcp-modules/libhttp/pico_http_server.c -o $(TOPDIR)apps/$(APP)/pico_http_server.o $(CC) $(CFLAGS) $(INC_DIRS) $(TOPDIR)../../picotcp-modules/libhttp/pico_http_util.c -o $(TOPDIR)apps/$(APP)/pico_http_util.o picotcp_clone: if [ ! -d "$(TOPDIR)../../picotcp" ]; then \ git clone https://github.com/crmoratelli/picotcp.git $(TOPDIR)../../picotcp; \ fi picotcp_compile: if [ ! -f "$(TOPDIR)../../picotcp/.compiled" ]; then \ make -C $(TOPDIR)../../picotcp clean; \ make -C $(TOPDIR)../../picotcp CROSS_COMPILE=mips-mti-elf- PLATFORM_CFLAGS="-EL -Os -c -Wa,-mvirt -mips32r5 -mtune=m14k -mno-check-zero-division -msoft-float -fshort-double -ffreestanding -nostdlib -fomit-frame-pointer -G 0 -DPIC32" \ DHCP_SERVER=0 DHCP_CLIENT=0 SLAACV4=0 TFTP=0 AODV=0 IPV6=0 NAT=0 PING=1 ICMP4=1 DNS_CLIENT=0 DNS=0 MDNS=0 DNS_SD=0 SNTP_CLIENT=0 PPP=0 MCAST=1 MLD=0 IPFILTER=0 \ ARCH=pic32 ICMP6=0 WOLFSSL=1 PREFIX=./build; \ touch $(TOPDIR)../../picotcp/.compiled; \ fi app: picotcp_clone picotcp_compile picotcp_modules_clone picotcp_modules_compile @./$(TOPDIR)apps/$(APP)/html-sources/make-Cfiles.py $(CC) $(CFLAGS) $(INC_DIRS) $(TOPDIR)apps/$(APP)/webserver.c -o $(TOPDIR)apps/$(APP)/webserver.o $(CC) $(CFLAGS) $(INC_DIRS) $(TOPDIR)apps/$(APP)/web_files.c -o $(TOPDIR)apps/$(APP)/web_files.o <file_sep>/* Copyright (c) 2016, prpl Foundation Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. This code was written by <NAME> at Embedded System Group (GSE) at PUCRS/Brazil. */ /** * @file malloc.c * * @section DESCRIPTION * * Memory allocator using first-fit * * Simple linked list of used/free areas. malloc() is slower, because free areas * are searched from the beginning of the heap and are coalesced on demand. Yet, * just one sweep through memory areas is performed, making it faster than other * allocators on the average case. free() is very fast, as memory areas * are just marked as unused. * */ #include <types.h> #include <malloc.h> #include <libc.h> extern uint32_t _heap_start; extern uint32_t _heap_size; static uint32_t krnl_free = 0; static void* krnl_heap = NULL; void free(void *ptr) { struct mem_block *p; p = ((struct mem_block *)ptr) - 1; p->size &= ~1L; krnl_free += p->size + sizeof(struct mem_block); } void *malloc(uint32_t size) { struct mem_block *p, *q, *r, n; size_t psize; size = align4(size); p = (struct mem_block *)krnl_heap; q = p; while (p->next){ while (p->size & 1){ p = p->next; q = p; } while (!(p->size & 1) && p->next) p = p->next; if (p){ q->size = (size_t)p - (size_t)q - sizeof(struct mem_block); q->next = p; } if (!p->next && q->size < size + sizeof(struct mem_block)){ return 0; } if (q->size >= size + sizeof(struct mem_block)){ p = q; break; } } psize = (p->size & ~1L) - size - sizeof(struct mem_block); r = p->next; p->next = (struct mem_block *)((size_t)p + size + sizeof(struct mem_block)); p->size = size | 1; n.next = r; n.size = psize; *p->next = n; krnl_free -= size + sizeof(struct mem_block); return (void *)(p + 1); } void *calloc(uint32_t qty, uint32_t type_size) { void *buf; buf = (void *)malloc((qty * type_size)); if (buf) memset(buf, 0, (qty * type_size)); return (void *)buf; } void *realloc(void *ptr, uint32_t size){ void *buf; if ((int32_t)size < 0) return NULL; if (ptr == NULL) return (void *)malloc(size); buf = (void *)malloc(size); if (buf){ memcpy(buf, ptr, size); free(ptr); } return (void *)buf; } void init_mem() { krnl_heap = (struct mem_block *)(((uint32_t)(&_heap_start) + 8) & 0xFFFFFFFC); uint32_t len = ((uint32_t)(&_heap_size) -8) & 0xFFFFFFFC; struct mem_block *p = (struct mem_block *)krnl_heap; struct mem_block *q = (struct mem_block *)((size_t)(struct mem_block *)krnl_heap + sizeof(krnl_heap) - (sizeof(struct mem_block))); len = align4(len); p->next = q; p->size = len - sizeof(struct mem_block) - sizeof(struct mem_block); q->next = NULL; q->size = 0; krnl_free = p->size; } <file_sep>/* Copyright (c) 2016, prpl Foundation Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. This code was written by <NAME> at Embedded System Group (GSE) at PUCRS/Brazil. */ /************************************************************* * Ping-Pong application - Inter-VM communication. * * To execute the Ping-Pong set the CFG_FILE on the main * Makefile to the sample-ping-pong.cfg configuration file. * * The ping-pong sample measures the inter-VM communication * latency with different message sizes. */ #include <arch.h> #include <libc.h> #include <network.h> #include <guest_interrupts.h> #include <hypercalls.h> #include <platform.h> int main(){ int32_t ret; uint32_t i = 0; char msg[32]; enable_interrupts(); uint32_t message_size = 64; while(1){ sprintf(msg, "Hello World %d", i); ret = SendMessage(2, msg, strlen(msg)+1); printf("\nSent bytes %d",ret); i++; mdelay(1000); } } <file_sep>/* Copyright (c) 2016, prpl Foundation Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. This code was written by <NAME> at Embedded System Group (GSE) at PUCRS/Brazil. */ /* * Baikal-T (P5600) core system blocks definitions * (c)2014 Baikal Electronics OJSC * */ #ifndef _ASM_P5600_H #define _ASM_P5600_H /* Offsets from the GCR base address to various control blocks */ #define MIPS_GCR_CONFIG 0x00 #define MIPS_GCR_SELF_BASE 0x08 #define MIPS_GCR_CUSTOM_BASE 0x60 #define MIPS_GCR_GIC_BASE 0x80 #define MIPS_GCR_CPC_BASE 0x88 /* Block enable flags */ #define MIPS_GCR_BLOCK_ENABLE 0x01 /* Offsets from the CPC base address to various control blocks */ #define MIPS_CPC_GCB_BASE 0x0000 #define MIPS_CPC_CLCB_BASE 0x2000 #define MIPS_CPC_COCB_BASE 0x4000 /* CPC Core Local Block offsets */ #define MIPS_CPC_CL_CMD_OFF 0x0000 #define MIPS_CPC_CL_STATUS_OFF 0x0008 #define MIPS_CPC_CL_ADDR_OFF 0x0010 /* CPC Core Other Block offsets */ #define MIPS_CPC_CO_CMD_OFF 0x0000 #define MIPS_CPC_CO_STATUS_OFF 0x0008 #define MIPS_CPC_CO_ADDR_OFF 0x0010 /* CPC Blocks Commands */ #define MIPS_CPC_CMD_CLKOFF 1 #define MIPS_CPC_CMD_PWROFF 2 #define MIPS_CPC_CMD_PWRON 3 #define MIPS_CPC_CMD_RESET 4 /* CPC Core Other address shift */ #define MIPS_CPC_ADDR_SHFT 16 /*Global Interrupt Controler Registers */ #define P5600_GIC_BASE(a) *(volatile unsigned*) (0xBBDC0000 + a) #define REG_MASK_OFFSET(int) ((int/32) * 4) #define INT_BIT(int) (1<<(int%32)) #define GIC_SH_CONFIG P5600_GIC_BASE(0) #define GIC_SH_COUNTERLO P5600_GIC_BASE(0x10) #define GIC_SH_COUNTERHI P5600_GIC_BASE(0x14) #define GIC_SH_REV P5600_GIC_BASE(0x20) #define GIC_SH_GID_CONFIG31_0 P5600_GIC_BASE(0x080) #define GIC_SH_GID_CONFIG63_32 P5600_GIC_BASE(0x084) #define GIC_SH_RMASK(int) (P5600_GIC_BASE(0x300 + REG_MASK_OFFSET(int)) = INT_BIT(int)) #define GIC_SH_SMASK(int) (P5600_GIC_BASE(0x380 + REG_MASK_OFFSET(int)) = INT_BIT(int)) #define GIC_SH_MASK(int) (P5600_GIC_BASE(0x400 + REG_MASK_OFFSET(int)) & INT_BIT(int)) #define GIC_SH_PEND (P5600_GIC_BASE(0x480 + REG_MASK_OFFSET(int)) & INT_BIT(int)) #define GIC_SH_MAP_PIN(int) P5600_GIC_BASE(0x500 + (int * 4)) #define GIC_SH_MAP_CORE(int) P5600_GIC_BASE(0x2000 + (int * 0x20)) #define GIC_SH_POL_HIGH(int) (P5600_GIC_BASE(0x100 + REG_MASK_OFFSET(int)) |= INT_BIT(int)) #define GIC_SH_POL_LOW(int) (P5600_GIC_BASE(0x100 + REG_MASK_OFFSET(int)) &= (~INT_BIT(int))) /*Global Interrupt Controler Registers Bits */ #define GIC_SH_CONFIG_COUNTSTOP (1<<28) #define GIC_SH_CONFIG_VZE (1<<30) /*Global Control Block Registers */ #define P5600_GCB_BASE(a) *(volatile unsigned*) (0xBFBF8000 + a) #define GCB_GIC P5600_GCB_BASE(0x80) /* Global Control Block Register Bits */ #define GCR_GIC_EN 1 /* Core-Local Register Map */ #define P5600_GIC_CL_BASE(a) *(volatile unsigned*) (0xBBDC8000 + a) #define GIC_CL_COREi_CTL P5600_GIC_CL_BASE(0x00) #define GIC_CL_COREi_PEND P5600_GIC_CL_BASE(0x04) #define GIC_CL_COREi_MASK P5600_GIC_CL_BASE(0x08) #define GIC_CL_COREi_RMASK P5600_GIC_CL_BASE(0x0C) #define GIC_CL_COREi_SMASK P5600_GIC_CL_BASE(0x10) #define GIC_CL_COREi_COMPARE_MAP P5600_GIC_CL_BASE(0x44) /*COUNTER/COMPARE*/ #define GIC_CL_COREi_TIMER_MAP P5600_GIC_CL_BASE(0x48) #define GIC_CL_COMPARELO P5600_GIC_CL_BASE(0xA0) #define GIC_CL_COMPAREHI P5600_GIC_CL_BASE(0xA4) #define GIC_CL_ID P5600_GIC_CL_BASE(0x88) /* Core-Local Registers Bits */ #define GIC_CL_TIMER_MASK 0x4 #endif /* _ASM_P5600_H */ <file_sep>/* * Copyright (c) 2016, prpl Foundation * * Permission to use, copy, modify, and/or distribute this software for any purpose with or without * fee is hereby granted, provided that the above copyright notice and this permission notice appear * in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE * FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * * This code was written by <NAME> at Embedded System Group (GSE) at PUCRS/Brazil. * */ /** * @file interrupts.c * * @section DESCRIPTION * * PIC32mz interrupt subsystem. Initializes the pic32mz interrupts * and allows for the registration of interrupt handlers. * * The hypervisor configures the pic32mz in vectored mode and uses * the OFF register to configure the vector address of the interrupt. * A device driver, after invoke register_interrupt() must configure * the corresponding OFF register with the function return. * */ #include <driver.h> #include <mips_cp0.h> #include <vcpu.h> #include <config.h> #include <globals.h> #include <driver.h> #include <interrupts.h> #include <libc.h> #include <exception.h> #define MAX_NUM_INTERRUPTS 64 /** * @brief interrupt_handlers is an array of pointers to * functions. Device drivers call register_interrupt() to * register their interrupt handler. */ handler_vector_t * interrupt_handlers[MAX_NUM_INTERRUPTS] = {NULL}; void __interrupt_handler(uint32_t interrupt_number){ if(interrupt_handlers[interrupt_number]){ interrupt_handlers[interrupt_number](); return; } WARNING("Interrupt %d not registered.", interrupt_number); } /** * @brief Register a new interrupt handler. * @param handler Function pointer. * @param interrupt_number Interrupt vector number. * @return Interrupt number or 0 if the handler could not be registered. */ uint32_t register_interrupt(handler_vector_t * handler, uint32_t interrupt_number){ /*Interrupt 0 is the general exception handler. */ if (interrupt_number > 0 && interrupt_number < 64){ if(interrupt_handlers[interrupt_number] == NULL){ interrupt_handlers[interrupt_number] = handler; return interrupt_number; } } return 0; } /** * @brief Configures the P5600 in vectored interrupt mode. */ void interrupt_init(){ uint32_t temp; memset(interrupt_handlers, 0, sizeof(interrupt_handlers)); /* General exception handler at interrupt vector 0 */ interrupt_handlers[0] = general_exception_handler; /*Enable the Global Interrupt Controller */ GCB_GIC |= 1; mtc0(CP0_EBASE, 0, 0x80000000); /* Configure the processor to vectored interrupt mode. */ temp = mfc0(CP0_CAUSE, 0); /* Get Cause */ temp |= CAUSE_IV; /* Set Cause IV */ mtc0(CP0_CAUSE, 0, temp); /* Update Cause */ temp = mfc0(CP0_STATUS, 0); /* Get Status */ temp &= ~STATUS_BEV; /* Clear Status BEV */ temp &= ~STATUS_EXL; mtc0(CP0_STATUS, 0, temp); /* Update Status */ temp = mfc0(CP0_INTCTL, 1); temp = (temp & ~(0x1f<<INTCTL_VS_SHIFT)) | (0x1 << INTCTL_VS_SHIFT); mtc0(CP0_INTCTL, 1, temp); /* GIC in Virtualization mode */ GIC_SH_CONFIG |= GIC_SH_CONFIG_VZE; INFO("P5600 core in Vectored Interrupt Mode."); } driver_init(interrupt_init); <file_sep>/* Copyright (c) 2016, prpl Foundation Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. This code was written by <NAME> at Embedded System Group (GSE) at PUCRS/Brazil. */ #ifndef ETH_H #define ETH_H #ifdef PICOTCP #include <arch.h> #include <libc.h> #include <network.h> #include "pico_defines.h" #include "pico_stack.h" #define ETH_MESSAGE_SZ 1536 #define ETH_MESSAGELIST_SZ 5 struct eth_message_t{ uint32_t size; /* size of each message in message_list */ uint8_t packet[ETH_MESSAGE_SZ]; }; struct eth_message_list_t{ uint32_t in; uint32_t out; volatile uint32_t num_packets; struct eth_message_t ringbuf[ETH_MESSAGELIST_SZ]; }; int eth_send(struct pico_device *dev, void *buf, int len); int eth_poll(struct pico_device *dev, int loop_score); int eth_link_state(struct pico_device *dev); void eth_watchdog(uint32_t *time, uint32_t ms_delay); #endif #endif <file_sep>/* Copyright (c) 2016, prpl Foundation Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. This code was written by <NAME> at Embedded System Group (GSE) at PUCRS/Brazil. */ #ifndef _GRP_CONTEXT_H #define _GRP_CONTEXT_H /** * These macros can read/write registers on the previous GPR Shadow. * On PIC32MZ, the guests are kept on separated GRP shadows. Thus, * the hypercall parameters are read from them. */ /* Write to previous gpr shadow */ #define MoveToPreviousGuestGPR(reg, value) asm volatile ( \ "wrpgpr $%0, %1" \ : : "K" (reg), "r" ((uint32_t) (value))) /* Read from previous gpr shadow */ #define MoveFromPreviousGuestGPR(reg) ({ int32_t __value; \ asm volatile ( \ "rdpgpr %0, $%1" \ : "=r" (__value) : "K" (reg)); \ __value; }) #endif /* _GRP_CONTEXT_H */ <file_sep># #Copyright (c) 2016, prpl Foundation # #Permission to use, copy, modify, and/or distribute this software for any purpose with or without #fee is hereby granted, provided that the above copyright notice and this permission notice appear #in all copies. # #THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE #INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE #FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM #LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, #ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # #This code was written by <NAME> at Embedded System Group (GSE) at PUCRS/Brazil. #Input CFG file for VMs configuration #CFG_FILE = cfg/sample-blink.cfg CFG_FILE = cfg/sample-ping-pong.cfg # CROSS Compiler CROSS_COMPILER = mipsel-unknown-linux-gnu- # Optional Device Drivers CONFIG_INTERVMCOMM_DRV = yes # The following drivers is only for tests/performance purpose. #CONFIG_TIMER_TEST_DRV = yes #CONFIG_PERFORMANCE_COUNTER_DRV = yes #CONFIG_INTERRUPT_LATENCY_TEST_DRV = yes # Platform info CFLAGS = -DCPU_ID="P5600" CFLAGS += -DCPU_ARCH="Baikal-T1 board." CFLAGS += -DCPU_FREQ=850000000 # Define DEBUG_GUEST to yes if you desire to compile the guests for debug. The code optimization will be O0. DEBUG_GUEST = no ######################################################################################################## # SHOULD NOT BE NEEDED TO MODIFY ANYTHING FROM WHERE. UNLESS YOU ARE ADDING NEW HYPERVISOR SOURCE FILES # OR PORTING TO A NEW PLATFORM. ######################################################################################################## APP_LIST = "" SHELL := /bin/bash # Setup Baikal-T1 core configuration used with u-boot. BAUDRATE=38600 F_CLK=850000000 SERIAL_DEV=/dev/ttyACM0 TOPDIR=../../ PLATFORM_DIR=platform/baikal_t1_board/ VERSION:=$(shell $(TOPDIR)/scripts/genversion.sh) LINKER_SCRIPT = ../../arch/mips/baikal-t1/baikal.ld ### GCC flags configuration: processor tunning ### CFLAGS += -EL -O2 -mips32r2 -Wall #MIPZ VZ support CFLAGS += -Wa,-mvirt #flointing pointing options CFLAGS += -mno-check-zero-division -msoft-float -fshort-double #General options CFLAGS += -c -ffreestanding -nostdlib -fomit-frame-pointer -G 0 #Additional features flags CFLAGS += -DHYPVERSION=${VERSION} -DBAIKAL_T1 # LD flags LDFLAGS = -EL ### Include dirs ### INC_DIRS = -I$(TOPDIR)arch/mips/baikal-t1/include \ -I$(TOPDIR)arch/mips/common/include \ -I$(TOPDIR)/platform/include \ -I$(TOPDIR)sys/lib/include \ -I$(TOPDIR)sys/kernel/include \ -I$(TOPDIR)platform/baikal_t1_board/include \ -I$(TOPDIR)/include BUILDDIR=build/hypervisor #Configure CROSS COMPILER AS = $(CROSS_COMPILER)as LD = $(CROSS_COMPILER)ld OBJDUMP = $(CROSS_COMPILER)objdump READELF = $(CROSS_COMPILER)readelf OBJCOPY = $(CROSS_COMPILER)objcopy SIZE = $(CROSS_COMPILER)size CC= $(CROSS_COMPILER)gcc STRIP = $(CROSS_COMPILER)strip APP = prplHypervisor all: config_vms lib kernel common baikal platform drivers $(APP) bare_apps generate_firmware include $(TOPDIR)sys/sys.mk include $(TOPDIR)arch/mips/common/common.mk include $(TOPDIR)arch/mips/baikal-t1/baikal.mk include board/board.mk include $(TOPDIR)/drivers/drivers.mk $(APP): $(LD) $(LDFLAGS) -T$(LINKER_SCRIPT) -Map $(APP).map -N -o $(APP).elf *.o $(OBJ) $(OBJDUMP) -Dz $(APP).elf > $(APP).lst $(OBJDUMP) -h $(APP).elf > $(APP).sec $(OBJDUMP) -s $(APP).elf > $(APP).cnt $(OBJCOPY) -O binary $(APP).elf $(APP).bin $(SIZE) $(APP).elf bare_apps: for i in $(APP_LIST) ""; do \ if [ -n "$$i" ]; then \ $(MAKE) -C ../../bare-metal-apps/platform/baikal_t1_board APP=$$i CLEAN=1 clean; \ $(MAKE) -C ../../bare-metal-apps/platform/baikal_t1_board APP=$$i CROSS_COMPILER=$(CROSS_COMPILER) F_CLK=$(F_CLK) FLASH_SIZE=`awk '$$1=="'$$i'" {print $$2}' include/vms.info` RAM_SIZE=`awk '$$1=="'$$i'" {print $$3}' include/vms.info` DEBUG_GUEST=$(DEBUG_GUEST); \ fi; \ done; generate_firmware: $(shell export BASE_ADDR=0x80000000; ../../scripts/genhex.sh $(APP_LIST)) make_genconf: gcc -DBAIKAL_T1 -o genconf ../cfg_reader/genconf.c -lconfig config_vms: make_genconf #execute first and exit in case of errors ./genconf $(CFG_FILE) baikal-t1 || (exit 1) #execute and export to a makefile variable the ouput of the script $(eval APP_LIST:=$(shell ./genconf $(CFG_FILE) || (exit 1))) clean: config_vms rm -f $(APP).* rm -f *.o rm -f firmware.hex rm -f include/vms.info rm -f include/config.h rm -f genconf rm -f firmware.bin for i in $(APP_LIST) ; do \ $(MAKE) -C ../../bare-metal-apps/platform/baikal_t1_board APP=$$i CLEAN=1 clean \ ;done <file_sep>import serial from time import sleep import base64 import sys def readSerial(): while True: response = ser.readline(); return response # main ser = serial.Serial(port='/dev/ttyACM0', baudrate=115200, timeout=3) ser.isOpen() # Wait UART Listener VM to be done. while(1): message = readSerial() if 'Listener' in message: break #Requires the keycode to the Litener VM ser.write('\n'.encode()) ser.flush() #Receive the keyCode while(1): message = readSerial() if 'keyCode' in message: hex_keyCode = message[9:-1] break print "KeyCode: ", hex_keyCode binary_keyCode = base64.b16decode(hex_keyCode.upper()) while(1): print "ARM Commands: " print "1 - Start" print "2 - Stop" c = '0' while c!='1' and c!='2': c = raw_input('Input:') print 'Sending the arm command...' for i in range(0, len(binary_keyCode)): ser.write(binary_keyCode[i]) ser.flush() ser.write(c.encode()) ser.write('\n'.encode()) ser.flush() print 'Board response: %s' % readSerial() <file_sep>import serial from time import sleep import base64 import sys def readSerial(): while True: response = ser.readline(); return response # main ser = serial.Serial(port='/dev/ttyACM0', baudrate=115200, timeout=3) ser.isOpen() # Fake keyCode binary_keyCode = base64.b16decode('0203030203030010200102000100000000000000000000') while(1): print "ARM Commands: " print "1 - Start" print "2 - Stop" c = '0' while c!='1' and c!='2': c = raw_input('Input:') print 'Sending the arm command...' for i in range(0, len(binary_keyCode)): ser.write(binary_keyCode[i]) ser.flush() ser.write(c.encode()) ser.write('\n'.encode()) ser.flush() print 'Board response: %s' % readSerial() <file_sep>#ifndef _PLATFORM_H #define _PLATFORM_H #include <qemu_virt.h> #define UART0_CTRL_ADDR(a) *(uint8_t*) (0x10000000 + (a)) #define UART_RBR 0x00 /* Receive Buffer Register */ #define UART_THR 0x00 /* Transmit Hold Register */ #define UART_IER 0x01 /* Interrupt Enable Register */ #define UART_DLL 0x00 /* Divisor LSB (LCR_DLAB) */ #define UART_DLM 0x01 /* Divisor MSB (LCR_DLAB) */ #define UART_FCR 0x02 /* FIFO Control Register */ #define UART_LCR 0x03 /* Line Control Register */ #define UART_MCR 0x04 /* Modem Control Register */ #define UART_LSR 0x05 /* Line Status Register */ #define UART_MSR 0x06 /* Modem Status Register */ #define UART_SCR 0x07 /* Scratch Register */ #define UART_LCR_DLAB 0x80 /* Divisor Latch Bit */ #define UART_LCR_8BIT 0x03 /* 8-bit */ #define UART_LCR_PODD 0x08 /* Parity Odd */ #define UART_LSR_DA 0x01 /* Data Available */ #define UART_LSR_OE 0x02 /* Overrun Error */ #define UART_LSR_PE 0x04 /* Parity Error */ #define UART_LSR_FE 0x08 /* Framing Error */ #define UART_LSR_BI 0x10 /* Break indicator */ #define UART_LSR_RE 0x20 /* THR is empty */ #define UART_LSR_RI 0x40 /* THR is empty and line is idle */ #define UART_LSR_EF 0x80 /* Erroneous data in FIFO */ #endif <file_sep>/* Copyright (c) 2016, prpl Foundation Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. This code was written by <NAME> at Embedded System Group (GSE) at PUCRS/Brazil. */ #include <arch.h> #include <eth.h> #include <guest_interrupts.h> #include <hypercalls.h> #include <platform.h> #include <libc.h> #include <eth.h> #ifdef HAVE_CONFIG_H #include <config.h> #endif //#include <wolfssl/options.h> #include <wolfssl/wolfcrypt/settings.h> #include <wolfssl/ssl.h> #include <wolfssl/wolfcrypt/rsa.h> #include <wolfssl/wolfcrypt/memory.h> #include <wolfssl/wolfcrypt/error-crypt.h> #include <wolfssl/wolfcrypt/tfm.h> #include <wolfssl/wolfcrypt/logging.h> volatile unsigned int pico_ms_tick = 0; int close(int __fildes){ return 0; } #define byte char #define HEAP_HINT 0 #define FOURK_BUF 4096 /* privkey.der, 1024-bit */ const unsigned char privkey_der_2048[] = { 0x30, 0x82, 0x04, 0xA4, 0x02, 0x01, 0x00, 0x02, 0x82, 0x01, 0x01, 0x00, 0xC2, 0x54, 0x7D, 0xA8, 0x88, 0x36, 0xC6, 0x06, 0x15, 0xA9, 0xF4, 0x37, 0x26, 0x67, 0xA7, 0x64, 0xB5, 0xB1, 0xA2, 0x4C, 0xB1, 0xDC, 0x92, 0x6A, 0x34, 0xF3, 0xE5, 0xFB, 0x6F, 0x5F, 0x13, 0xEC, 0xB2, 0x7D, 0x2C, 0x26, 0x71, 0x96, 0x4D, 0xB7, 0x23, 0x29, 0x76, 0x54, 0x24, 0xA1, 0xB8, 0x63, 0xB8, 0xAB, 0x6D, 0x38, 0x0E, 0x4A, 0x11, 0x4E, 0x56, 0xEB, 0x44, 0x6A, 0x74, 0x84, 0xEA, 0x32, 0x32, 0x80, 0xD7, 0x38, 0xD1, 0xE4, 0x9C, 0x85, 0x0C, 0xAF, 0x0A, 0xD4, 0xC3, 0xB7, 0xB8, 0x94, 0xA7, 0xAB, 0x15, 0x8C, 0x70, 0x15, 0x0F, 0x37, 0x60, 0xA1, 0xC7, 0x66, 0x2F, 0x59, 0xD9, 0xD1, 0x6B, 0xA8, 0x62, 0xE8, 0x84, 0x07, 0x1E, 0x16, 0xE0, 0x57, 0xDE, 0x19, 0x07, 0xA0, 0x62, 0x00, 0x34, 0xC2, 0x78, 0x69, 0xF6, 0x67, 0x0B, 0x56, 0x79, 0x9B, 0xFD, 0x9F, 0x88, 0xB4, 0xAE, 0x6D, 0x40, 0x8F, 0xCE, 0x6A, 0xC3, 0x3F, 0xB3, 0x7F, 0xA7, 0x29, 0x67, 0x30, 0x52, 0x0A, 0x2D, 0x6E, 0xB6, 0xCE, 0xB9, 0xD0, 0xEF, 0x56, 0x12, 0x1F, 0xCE, 0xC0, 0x99, 0x8D, 0x53, 0x17, 0x07, 0xA5, 0xD1, 0xD2, 0x01, 0xA2, 0xC2, 0x6C, 0x60, 0x6D, 0xF0, 0x4D, 0x28, 0x01, 0x7E, 0x93, 0x54, 0x96, 0xD4, 0xF0, 0xFF, 0xAC, 0x45, 0x18, 0xCB, 0xE7, 0x78, 0x6B, 0xB6, 0x64, 0xC7, 0x48, 0x78, 0x94, 0x86, 0x1D, 0x57, 0x29, 0x69, 0x12, 0x54, 0x08, 0x46, 0x9B, 0x6D, 0x49, 0xB8, 0xC7, 0xCC, 0x89, 0xA7, 0x2A, 0xD3, 0x10, 0x46, 0x52, 0x3D, 0x64, 0x81, 0x98, 0x2B, 0x97, 0x75, 0x4B, 0xF9, 0x86, 0xDE, 0x72, 0x86, 0xE0, 0x66, 0x35, 0xEE, 0x7A, 0x71, 0x38, 0xBB, 0x0C, 0x04, 0xBC, 0x2D, 0x63, 0xAF, 0x73, 0xA3, 0x9F, 0x6B, 0xC8, 0x55, 0x5C, 0x3E, 0xE0, 0x69, 0x8A, 0x3D, 0x5E, 0xE2, 0xDB, 0x02, 0x03, 0x01, 0x00, 0x01, 0x02, 0x82, 0x01, 0x00, 0x08, 0x71, 0x21, 0x30, 0x54, 0x12, 0x85, 0x11, 0xB8, 0x99, 0x34, 0x79, 0xBC, 0xDA, 0x5D, 0xE4, 0x3B, 0x1C, 0x67, 0x5F, 0x8B, 0x8E, 0x78, 0x71, 0xD2, 0xB1, 0x11, 0xB9, 0x95, 0x81, 0xFC, 0xDC, 0x98, 0x78, 0x65, 0x95, 0x99, 0xF3, 0x9C, 0x96, 0xAB, 0x19, 0x5F, 0x01, 0x92, 0xC1, 0xCF, 0xBF, 0xCD, 0x42, 0xED, 0x30, 0xB5, 0x36, 0x34, 0x80, 0x41, 0xB8, 0x60, 0xB5, 0x7B, 0x30, 0x56, 0xF8, 0x2D, 0x47, 0x79, 0x92, 0x07, 0x54, 0x36, 0x14, 0x75, 0x93, 0x99, 0x15, 0xDB, 0x16, 0xBD, 0x17, 0x00, 0x1D, 0xA7, 0x86, 0xFD, 0x4B, 0x7C, 0xE8, 0xBB, 0xF2, 0xEB, 0x35, 0x9E, 0x32, 0xFA, 0x0A, 0x65, 0xF1, 0xDF, 0xB2, 0x18, 0x22, 0x33, 0x05, 0x6D, 0x63, 0x83, 0xCB, 0x74, 0x90, 0x5C, 0x11, 0x84, 0x39, 0x3A, 0x7F, 0xE7, 0xEB, 0x5C, 0x0B, 0xBA, 0xA6, 0xB3, 0x22, 0xDE, 0x0E, 0x73, 0x51, 0x4A, 0x39, 0x03, 0x60, 0x11, 0xA9, 0x64, 0x2E, 0x2C, 0xF9, 0x20, 0x99, 0x72, 0xDA, 0xCC, 0xAE, 0xAD, 0x15, 0x7B, 0x81, 0x82, 0x76, 0x3E, 0x3B, 0x3E, 0x01, 0x06, 0x2F, 0x5A, 0xD6, 0xBE, 0x7A, 0x4E, 0x1A, 0x57, 0x87, 0x39, 0x7C, 0x92, 0x88, 0x6F, 0xC1, 0x3E, 0xA1, 0x70, 0x25, 0x0F, 0x1D, 0x77, 0x39, 0xCB, 0x28, 0x54, 0x23, 0xEE, 0xC5, 0xB2, 0x66, 0x55, 0xBD, 0x41, 0xE7, 0xFF, 0x0F, 0x2E, 0x6D, 0xB7, 0xF7, 0x63, 0x60, 0xA0, 0x0D, 0x67, 0x23, 0x4D, 0xA2, 0xAB, 0x03, 0xF2, 0x3B, 0x37, 0x83, 0x44, 0x03, 0xF8, 0xBF, 0xBD, 0x2A, 0x47, 0x04, 0xAE, 0x51, 0xE6, 0x1C, 0x13, 0x5D, 0xA0, 0x95, 0x4D, 0x05, 0xBC, 0x69, 0xAB, 0x2E, 0xB8, 0x09, 0xFE, 0x77, 0x55, 0x46, 0x8C, 0xE6, 0x89, 0xF5, 0x40, 0x1D, 0xFF, 0x6E, 0xC9, 0x66, 0x5A, 0x94, 0xE4, 0x93, 0xC3, 0x43, 0xCE, 0xD9, 0x02, 0x81, 0x81, 0x00, 0xF4, 0xE9, 0x55, 0x00, 0x6A, 0x83, 0xD2, 0xF4, 0x40, 0xD4, 0x78, 0x6B, 0x2D, 0x02, 0xED, 0xEF, 0x8A, 0xDB, 0xD2, 0xE7, 0x26, 0xE4, 0xDE, 0x8C, 0xAE, 0x11, 0xE5, 0xD4, 0x8D, 0x43, 0x17, 0xAB, 0x85, 0x73, 0xBA, 0xAB, 0x0B, 0x07, 0x7A, 0xF2, 0xA7, 0xF6, 0xCC, 0x20, 0xD5, 0x0C, 0x39, 0xB0, 0x3A, 0x94, 0x51, 0x61, 0x9B, 0x6F, 0xAB, 0x53, 0x06, 0x62, 0x7A, 0x1B, 0x32, 0xF4, 0xE7, 0x5E, 0x9D, 0x21, 0xC4, 0x4E, 0x76, 0x91, 0xAB, 0x3C, 0x7E, 0xDC, 0x51, 0xCB, 0xC8, 0x50, 0x40, 0xDE, 0x71, 0x79, 0x1C, 0x7E, 0x79, 0x54, 0x83, 0xCF, 0x7E, 0xDA, 0xDC, 0x7C, 0x0F, 0xFB, 0x8F, 0xDF, 0xC2, 0x5F, 0xDC, 0xCE, 0xAA, 0x5C, 0x36, 0x2F, 0x6E, 0xF5, 0x0F, 0x9E, 0x72, 0xD4, 0x7F, 0xAD, 0x0B, 0x0A, 0x17, 0x07, 0xDE, 0x03, 0xE8, 0x78, 0x69, 0xBE, 0x54, 0xC1, 0x7F, 0x2C, 0x5A, 0x7D, 0x02, 0x81, 0x81, 0x00, 0xCB, 0x20, 0xE3, 0xF6, 0x58, 0xF6, 0x56, 0xBC, 0xC0, 0x67, 0x50, 0x8C, 0xE7, 0x80, 0x52, 0x28, 0x3D, 0xA6, 0x0E, 0xD6, 0x8B, 0x0C, 0xB3, 0x09, 0x59, 0xAA, 0xD1, 0x8A, 0x76, 0x54, 0x95, 0x55, 0xB1, 0xA6, 0x27, 0xE5, 0x03, 0x08, 0xD1, 0x3F, 0xBA, 0xEC, 0x4F, 0x3A, 0x3D, 0xF0, 0x8E, 0x94, 0x62, 0xDB, 0xCA, 0xC8, 0xF8, 0xF2, 0x26, 0x47, 0x30, 0x7B, 0x6B, 0x9F, 0x1F, 0xDB, 0xB5, 0x40, 0x91, 0x0C, 0xFB, 0x82, 0xF9, 0xB1, 0xE5, 0x7D, 0x2C, 0x7B, 0x82, 0x2E, 0xA9, 0x77, 0x29, 0xE9, 0x74, 0xF4, 0x34, 0xB4, 0x70, 0xD9, 0x95, 0xCA, 0xF2, 0x1B, 0xB1, 0x9B, 0x38, 0xE5, 0x74, 0xBD, 0x53, 0x05, 0x1F, 0x3B, 0x0E, 0xB8, 0x37, 0x67, 0x67, 0x44, 0xF9, 0x16, 0xBB, 0x30, 0x3A, 0x3F, 0xC8, 0x21, 0x11, 0x4A, 0x5A, 0x88, 0x5F, 0xD6, 0xCB, 0xC2, 0x64, 0x92, 0xCE, 0x3D, 0xDA, 0x37, 0x02, 0x81, 0x81, 0x00, 0xEB, 0xF6, 0x1B, 0x05, 0x69, 0x9A, 0x54, 0x97, 0x2C, 0x17, 0x09, 0x66, 0x09, 0x59, 0xF7, 0x30, 0x81, 0x92, 0xC5, 0xA2, 0x1B, 0xA1, 0x0A, 0xA2, 0x73, 0xDB, 0x9E, 0x99, 0xA8, 0xF8, 0x69, 0x47, 0xC2, 0x2D, 0xFC, 0x3D, 0x6B, 0x44, 0xEB, 0xB9, 0xFB, 0x06, 0x17, 0x29, 0xD2, 0xDA, 0x12, 0x82, 0xAE, 0x0D, 0xD4, 0x52, 0xBC, 0x55, 0x5C, 0xB5, 0x83, 0x43, 0x41, 0xEE, 0x0E, 0xAC, 0x52, 0x76, 0x9F, 0xE1, 0xB6, 0xA6, 0xFA, 0x29, 0xE2, 0xD7, 0x48, 0x4A, 0xB1, 0x2C, 0x2B, 0x74, 0xD6, 0xEA, 0xFA, 0x5C, 0xFB, 0x8D, 0x07, 0x0C, 0xDC, 0x6A, 0x00, 0x08, 0x91, 0xC1, 0x9E, 0x0C, 0x7B, 0x53, 0xD4, 0x8C, 0x53, 0xCB, 0x71, 0xEB, 0xA1, 0xF1, 0x15, 0x70, 0x5A, 0x7A, 0x08, 0x9C, 0x9F, 0xDE, 0x72, 0xF2, 0x67, 0xBA, 0x16, 0xB7, 0xA1, 0x34, 0xD2, 0x7C, 0xA4, 0x60, 0x41, 0x4C, 0xD4, 0x69, 0x02, 0x81, 0x80, 0x20, 0x92, 0x74, 0x9B, 0x93, 0x26, 0x65, 0x40, 0x3D, 0x26, 0x13, 0xFF, 0x94, 0x3B, 0xBA, 0x70, 0xE3, 0x79, 0xD6, 0x55, 0x46, 0xD4, 0xD1, 0x7C, 0xC5, 0x59, 0x23, 0xE2, 0xAD, 0x18, 0xE1, 0x1D, 0x6D, 0xB0, 0x34, 0x23, 0x7F, 0xFA, 0x10, 0xFB, 0xC4, 0x30, 0x92, 0x7F, 0xC7, 0x60, 0xE4, 0xAC, 0x1C, 0xB2, 0x1B, 0xF1, 0x60, 0x22, 0x0C, 0x4B, 0x4C, 0x15, 0xEE, 0x6B, 0x04, 0xC3, 0xC9, 0x6B, 0xC2, 0x16, 0xAF, 0xDA, 0x0F, 0xCA, 0x1B, 0xFF, 0x97, 0x7B, 0x72, 0xA3, 0xA2, 0xDF, 0x0D, 0xE4, 0x76, 0xB1, 0x96, 0x25, 0xFD, 0x16, 0x96, 0xF3, 0x85, 0x21, 0x35, 0xB8, 0xAB, 0x45, 0xF8, 0x13, 0x47, 0xD5, 0xC1, 0x6D, 0x49, 0xED, 0xF6, 0x4C, 0x69, 0x7D, 0xE0, 0xE7, 0x69, 0x3A, 0xD1, 0x8C, 0x5A, 0xBE, 0x1A, 0xB4, 0xAE, 0x91, 0xC1, 0xB4, 0x82, 0xD5, 0xF8, 0x24, 0xA6, 0x57, 0xBA, 0xBF, 0x02, 0x81, 0x81, 0x00, 0xCF, 0xD5, 0xF9, 0x2A, 0x0D, 0x81, 0x7A, 0x70, 0x40, 0x2E, 0xD2, 0x9E, 0x62, 0xD9, 0x7C, 0x3F, 0x13, 0xBB, 0x64, 0xC5, 0xA5, 0x3E, 0x41, 0x01, 0x28, 0x70, 0xDC, 0x04, 0xDC, 0x66, 0x69, 0xB0, 0x1C, 0xF2, 0xA8, 0x52, 0xA6, 0xDB, 0x50, 0x2D, 0xDA, 0xBE, 0xB8, 0x44, 0x6F, 0xB0, 0x5C, 0xFF, 0x98, 0x09, 0x25, 0xDC, 0xCC, 0x53, 0xCC, 0xD6, 0x46, 0x90, 0x5C, 0xC7, 0xA4, 0xD9, 0x9D, 0xE5, 0x5E, 0x25, 0x61, 0xBC, 0x10, 0xF0, 0xEC, 0xF1, 0x0A, 0x35, 0x8D, 0x5F, 0x5B, 0x42, 0x98, 0xD4, 0xCB, 0x06, 0x26, 0xAB, 0xF4, 0x3D, 0x7D, 0xD1, 0xB0, 0x53, 0x25, 0xDD, 0x94, 0xC5, 0xF0, 0x55, 0xDD, 0x68, 0x63, 0xCE, 0x07, 0x7B, 0x4C, 0x8B, 0x02, 0xE5, 0xD0, 0x44, 0xC7, 0x3B, 0xFD, 0x8F, 0x91, 0xCD, 0x2C, 0xDB, 0xCD, 0x93, 0x74, 0x3B, 0xF7, 0xBB, 0x1D, 0x67, 0x1A, 0xCD, 0x58, 0xE6 }; int rsa_test(void) { byte* tmp = NULL; size_t bytes; RsaKey key; WC_RNG rng; word32 idx = 0; int ret; byte in[] = "Everyone gets Friday off."; word32 inLen = (word32)XSTRLEN((char*)in); byte out[256]; byte plain[256]; byte* outPtr = NULL; tmp = (byte*)XMALLOC(FOURK_BUF, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); if (tmp == NULL) { ret = MEMORY_E; goto exit; } XMEMCPY(tmp, privkey_der_2048, sizeof(privkey_der_2048)); bytes = sizeof(privkey_der_2048); ret = wc_InitRsaKey_ex(&key, HEAP_HINT, INVALID_DEVID); if (ret < 0) { goto exit; } ret = wc_RsaPrivateKeyDecode(tmp, &idx, &key, (word32)bytes); if (ret < 0) { goto exit; } printf("Key Size: %d\n", wc_RsaEncryptSize(&key)); ret = wc_InitRng(&rng); if (ret < 0) { goto exit; } #ifdef WC_RSA_BLINDING ret = wc_RsaSetRNG(&key, &rng); if (ret < 0) { goto exit; } #endif ret = wc_RsaPublicEncrypt(in, inLen, out, sizeof(out), &key, &rng); printf("wc_RsaPublicEncrypt: %d\n", ret); if (ret < 0) { goto exit; } idx = ret; /* save off encrypted length */ ret = wc_RsaPrivateDecrypt(out, idx, plain, sizeof(plain), &key); printf("wc_RsaPrivateDecrypt: %d\n", ret); printf("\n%d", ret); if (ret < 0) { goto exit; } if (XMEMCMP(plain, in, ret)) { printf("Compare failed!\n"); goto exit; } ret = wc_RsaSSL_Sign(in, inLen, out, sizeof(out), &key, &rng); printf("wc_RsaSSL_Sign: %d\n", ret); if (ret < 0) { goto exit; } idx = ret; XMEMSET(plain, 0, sizeof(plain)); ret = wc_RsaSSL_VerifyInline(out, idx, &outPtr, &key); printf("wc_RsaSSL_Verify: %d\n", ret); if (ret < 0) { goto exit; } if (XMEMCMP(in, outPtr, ret)) { printf("Compare failed!\n"); goto exit; } ret = 0; /* success */ exit: wc_FreeRsaKey(&key); XFREE(tmp, HEAP_HINT, DYNAMIC_TYPE_TMP_BUFFER); wc_FreeRng(&rng); return ret; } int main() { int32_t ret; printf("\nsize of long long %d.", sizeof(long long )); printf("\nsize of long %d.", sizeof(long )); #if defined(DEBUG_WOLFSSL) wolfSSL_Debugging_ON(); #endif wolfCrypt_Init(); #if !defined(NO_BIG_INT) if (CheckCtcSettings() != 1) printf("\nBuild vs runtime math mismatch\n"); #ifdef USE_FAST_MATH if (CheckFastMathSettings() != 1) printf("\nBuild vs runtime fastmath FP_MAX_BITS mismatch\n"); #endif /* USE_FAST_MATH */ #endif /* !NO_BIG_INT */ ret = rsa_test(); printf("\nret %d", ret); return 0; }<file_sep>/* C o*pyright (c) 2016, prpl Foundation Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. This code was written by <NAME> at Embedded System Group (GSE) at PUCRS/Brazil. */ #include <uart.h> #include <types.h> #include <arch.h> static uint32_t serial_port = UART4; int32_t serial_select(uint32_t serial_number){ /* Only UART4 suported. */ switch (serial_number){ case UART4: serial_port = UART4; return UART4; default: return -1; } } void putchar(int32_t value){ #ifdef VIRTUALIZED_IO while(readio(U4STA) & USTA_UTXBF); writeio(U4TXREG, value); #else while(U4STA & USTA_UTXBF); U4TXREG = value; #endif } int32_t kbhit(void){ #ifdef VIRTUALIZED_IO return (readio(U4STA) & USTA_URXDA); #else return (U4STA & USTA_URXDA); #endif } uint32_t getchar(void){ while(!kbhit()); #ifdef VIRTUALIZED_IO return (uint32_t)readio(U2RXREG); #else return (uint32_t)U2RXREG; #endif } <file_sep>/* Copyright (c) 2016, prpl Foundation Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. This code was written by <NAME> at Embedded System Group (GSE) at PUCRS/Brazil. */ /* * Baikal-T (P5600) address segments macro * (c)2014 Baikal Electronics OJSC * */ #ifndef _ASM_SEGCFG_H #define _ASM_SEGCFG_H #define MIPS_SEGCFG_PA_SHIFT 9 #define MIPS_SEGCFG_PA ((127) << MIPS_SEGCFG_PA_SHIFT) #define MIPS_SEGCFG_AM_SHIFT 4 #define MIPS_SEGCFG_AM ((7) << MIPS_SEGCFG_AM_SHIFT) #define MIPS_SEGCFG_EU_SHIFT 3 #define MIPS_SEGCFG_EU ((1) << MIPS_SEGCFG_EU_SHIFT) #define MIPS_SEGCFG_C_SHIFT 0 #define MIPS_SEGCFG_C ((7) << MIPS_SEGCFG_C_SHIFT) #define MIPS_SEGCFG_UUSK (7) #define MIPS_SEGCFG_USK (5) #define MIPS_SEGCFG_MUSUK (4) #define MIPS_SEGCFG_MUSK (3) #define MIPS_SEGCFG_MSK (2) #define MIPS_SEGCFG_MK (1) #define MIPS_SEGCFG_UK (0) /* * For Legacy Mode should be next configuration * * Segment Virtual Size Access Mode Physical Caching EU * ------- ------- ---- ----------- -------- ------- -- * 0 e0000000 512M MK UND U 0 * 1 c0000000 512M MSK UND U 0 * 2 a0000000 512M UK 000 2 0 * 3 80000000 512M UK 000 3 0 * 4 40000000 1G MUSK UND U 1 * 5 00000000 1G MUSK UND U 1 */ #define MIPS_LEGACY_SEG0 ((MIPS_SEGCFG_MK << MIPS_SEGCFG_AM_SHIFT) | \ ((3) << MIPS_SEGCFG_C_SHIFT)) #define MIPS_LEGACY_SEG1 ((MIPS_SEGCFG_MSK << MIPS_SEGCFG_AM_SHIFT) | \ ((3) << MIPS_SEGCFG_C_SHIFT)) #define MIPS_LEGACY_SEG2 ((MIPS_SEGCFG_UK << MIPS_SEGCFG_AM_SHIFT) | \ ((2) << MIPS_SEGCFG_C_SHIFT)) #define MIPS_LEGACY_SEG3 ((MIPS_SEGCFG_UK << MIPS_SEGCFG_AM_SHIFT) | \ ((3) << MIPS_SEGCFG_C_SHIFT)) #define MIPS_LEGACY_SEG4 ((MIPS_SEGCFG_MUSK << MIPS_SEGCFG_AM_SHIFT) | \ ((3) << MIPS_SEGCFG_C_SHIFT) | \ ((1) << MIPS_SEGCFG_EU_SHIFT)) #define MIPS_LEGACY_SEG5 ((MIPS_SEGCFG_MUSK << MIPS_SEGCFG_AM_SHIFT) | \ ((3) << MIPS_SEGCFG_C_SHIFT) | \ ((1) << MIPS_SEGCFG_EU_SHIFT)) #define MIPS_LEGACY_SEGCFG0 ((MIPS_LEGACY_SEG1 << 16) | MIPS_LEGACY_SEG0) #define MIPS_LEGACY_SEGCFG1 ((MIPS_LEGACY_SEG3 << 16) | MIPS_LEGACY_SEG2) #define MIPS_LEGACY_SEGCFG2 ((MIPS_LEGACY_SEG5 << 16) | MIPS_LEGACY_SEG4) #endif /* _ASM_SEGCFG_H */ <file_sep>TOOLS_DIR=$HOME/riscv-tools # Install required packages sudo apt-get install autoconf automake autotools-dev curl \ libmpc-dev libmpfr-dev libgmp-dev gawk build-essential \ bison flex texinfo gperf libtool patchutils bc zlib1g-dev mkdir -p $TOOLS_DIR pushd $TOOLS_DIR # Download and install the toolchain. This can take hours! git clone https://github.com/riscv/riscv-gnu-toolchain.git cd riscv-gnu-toolchain git submodule update --init --recursive ./configure --prefix=$TOOLS_DIR/riscv-gnu-toolchain-bins make cd .. # Download and install the RV8 simulator. git clone https://github.com/rv8-io/rv8.git cd rv8 git submodule update --init --recursive make sudo make install cd .. popd # Configure path. echo >> ~/.profile echo "export PATH=\"\$PATH:\"$TOOLS_DIR/riscv-gnu-toolchain-bins/bin\"\"" >> ~/.profile echo >> ~/.profile echo "***********************************************************" echo "You need to logout to the changes on you PATH make effect. " echo "***********************************************************" <file_sep>/* Copyright (c) 2016, prpl Foundation Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. This code was written by <NAME> at Embedded System Group (GSE) at PUCRS/Brazil. */ /** * @file driver.h * * @section DESCRIPTION * * Driver definitions. * The macro driver_init() must be declared for all device drivers indicating its initialization function. The initialization function will be * called during hypervisor startup. */ #ifndef __DRIVER_H_ #define __DRIVER_H_ #include <types.h> /** * @brief Allocate a function pointer in a table of device drivers init calls. * @param fn Init function name. */ #define driver_init(fn) static void (*__initcall_t_##fn)() __attribute__ ((section(".__drivers_table_init"))) __attribute__ ((__used__))= fn typedef void initcall_t(); void drivers_initialization(); #endif <file_sep>#!/usr/bin/python #Copyright (c) 2016, prpl Foundation # #Permission to use, copy, modify, and/or distribute this software for any purpose with or without #fee is hereby granted, provided that the above copyright notice and this permission notice appear #in all copies. # #THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE #INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE #FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM #LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, #ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # #This code was written by <NAME> at Embedded System Group (GSE) at PUCRS/Brazil. import codecs import os listOfFiles = [ "cert.pem", "privkey.pem" ]; def write_permission(output): output.write("""/* Copyright (c) 2016, prpl Foundation Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. This code was written by <NAME> at Embedded System Group (GSE) at PUCRS/Brazil. */ """) #Write the C header file def write_header(output): write_permission(output) output.write(""" // THIS FILE IS AUTOMATICALLY GENERATED. // MODIFY html-sources/make-SSL-include.py INSTEAD OF THIS. #ifndef SSL_CERT_H_ #define SSL_CERT_H_ """) #Write the C file def write_cert(output, path): write_header(output) hex_encoder = codecs.getencoder('hex') bin_handle = open(path + listOfFiles[0],'rb') output.write("const unsigned char cert_pem_2048[] = {\n " ) count = 0 while(1): c = bin_handle.read(1) if not c: break output.write("0x%s, " % (hex_encoder(c)[0].decode(), )) count+=1 if (count % 16 == 0): output.write("\n ") output.write("\n};\n\n") bin_handle.close() bin_handle = open(path + listOfFiles[1],'rb') output.write("const unsigned char privkey_pem_2048[] = {\n ") count = 0 while(1): c = bin_handle.read(1) if not c: break output.write("0x%s, " % (hex_encoder(c)[0].decode(), )) count+=1 if (count % 16 == 0): output.write("\n ") output.write("\n};\n\n") output.write("#endif\n") bin_handle.close() local_path = os.path.dirname(os.path.realpath(__file__)) + '/' print local_path try: cert_file = open(local_path + "../SSL_cert.h", 'w') except: print("Failed to open files for writing!") exit() write_cert(cert_file, local_path) cert_file.close() <file_sep>#!/bin/bash version=$(git describe --tags --long | tr "-" " ") tag=$(echo $version | cut -d' ' -f1) rev=$(echo $version | cut -d' ' -f2) hash=$(echo $version | cut -d' ' -f3) echo \"$tag.$rev \($hash\)\" <file_sep>#ifndef _QEMU_VIRT_ #define _QEMU_VIRT_ #define UART_PBASE(a) *(volatile unsigned*) (0x40003000 + (a)) /* FIXME: Define correct size and addresses. */ #define UART2_BASE 0 #define UART2_SIZE 0 #define UART_REG_RBR UART_PBASE(0) #define UART_REG_TBR UART_PBASE(0) #define UART_REG_IIR UART_PBASE(2) #define IIR_TX_RDY 2 #define IIR_RX_RDY 4 #define HTIF_TOHOST 0x40008000 #endif /* _QEMU_VIRT_ */ <file_sep>/* Copyright (c) 2016, prpl Foundation Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. This code was written by <NAME> at Embedded System Group (GSE) at PUCRS/Brazil. */ /** * @file vtimer.c * * @section DESCRIPTION * * This driver register the mtimer hypercall. */ #include <globals.h> #include <hal.h> #include <libc.h> #include <proc.h> #include <hypercall_defines.h> #include <hypercall.h> #include <driver.h> #include <interrupts.h> #include <platform.h> /** * @brief Hypercall implementation. Returns the VM identifier number for the calling VM. * V0 guest register will be replaced with the VM id. */ static void get_mtimer(){ uint64_t mtime = MTIME; MoveToPreviousGuestGPR(REG_A0,mtime); } /** * @brief Driver init call. Registers the hypercalls. */ void vtimer_init(){ if (register_hypercall(get_mtimer, HCALL_GET_MTIMER_VALUE) < 0){ ERROR("Error registering the HCALL_GET_MTIMER_VALUE hypercall"); return; } INFO("Hypercall MTimer Value implemented."); } driver_init(vtimer_init); <file_sep>/* Copyright (c) 2016, prpl Foundation Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. This code was written by <NAME> at Embedded System Group (GSE) at PUCRS/Brazil. */ /** * @file timer.c * * @section DESCRIPTION * * Timer interrupt subsystem. This timer is used for VCPU scheduling and * virtual timer interrupt injection on Guests. * * Every guest receive timer interrupt each 1ms. This will be replaced soon with * a configurable guest timer. */ #include <globals.h> #include <hal.h> #include <qemu_virt.h> #include <guest_interrupts.h> #include <scheduler.h> #include <interrupts.h> #include <libc.h> #include <proc.h> #define SYSTEM_TICK_INTERVAL (SYSTEM_TICK_US * MICROSECOND) #define QUEST_TICK_INTERVAL (GUEST_QUANTUM_MS * MILISECOND) /** * @brief Time interrupt handler. * * Perfoms VCPUs scheduling and virtual timer interrupt injection on guests. */ void timer_interrupt_handler(){ MTIMECMP = MTIME + SYSTEM_TICK_INTERVAL; run_scheduler(); /* wait interrupt bit fall to avoid spurious interrupts. */ /* FIXME: It appears to be not working during debugging.*/ /*while(read_csr(mip) & MIP_MTIP); */ } /** * @brief Configures the CP0 timer. * * This function will never return to the calling code. It waits for the * first timer interrupt. */ void start_timer(){ MTIMECMP = MTIME + SYSTEM_TICK_INTERVAL; set_csr_bits(mie, MIP_MTIP); set_csr_bits(mstatus, MSTATUS_MIE); /* Wait for a timer interrupt */ for(;;); } <file_sep>/* Copyright (c) 2016, prpl Foundation Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. This code was written by <NAME> at Embedded System Group (GSE) at PUCRS/Brazil. */ /** * @file performance-counter.c * * @section DESCRIPTION * * Allows for the guests to control the performance counters. * * Used for performance/benchmarks measurements. * */ #include <hypercall.h> #include <globals.h> #include <driver.h> #include <hypercall_defines.h> #include <mips_cp0.h> #include <hal.h> #include <scheduler.h> #include <libc.h> #include <pic32mz.h> /** * @brief Start performance counter. * * a0: performance conter control 0 configuration. * a1: performance conter control 1 configuration. * v0: returns always 0. */ void performance_counter_start(){ uint32_t control0 = MoveFromPreviousGuestGPR(REG_A0); uint32_t control1 = MoveFromPreviousGuestGPR(REG_A1); mtc0(CP0_PERFCTL0, 1, 0); mtc0(CP0_PERFCTL1, 3, 0); mtc0(CP0_PERFCTL0, 0, control0); mtc0(CP0_PERFCTL1, 2, control1); MoveToPreviousGuestGPR(REG_V0, 0); } /** * @brief Stop performance counter. * a0: destination buffer. * v0: returns always 0. */ void performance_counter_stop(){ uint32_t memory_addr = MoveFromPreviousGuestGPR(REG_A0); uint32_t* ptr_mapped = (uint32_t*)tlbCreateEntry(memory_addr, vm_in_execution->base_addr, 2*sizeof(uint32_t), 0xf, CACHEABLE); ptr_mapped[0] = mfc0(CP0_PERFCTL0, 1); ptr_mapped[1] = mfc0(CP0_PERFCTL1, 3); mtc0(CP0_PERFCTL0, 0, 0); mtc0(CP0_PERFCTL1, 2, 0); MoveToPreviousGuestGPR(REG_V0, 0); } /** * @brief Driver init call. Registers the hypercalls. */ void performance_init(){ if (register_hypercall(performance_counter_start, HCALL_PERFORMANCE_COUNTER_START) < 0){ ERROR("Error registering the HCALL_PERFORMANCE_COUNTER_START hypercall"); return; } if (register_hypercall(performance_counter_stop, HCALL_PERFORMANCE_COUNTER_STOP) < 0){ ERROR("Error registering the HCALL_PERFORMANCE_COUNTER_STOP hypercall"); return; } INFO("Performance counter driver registered."); } driver_init(performance_init); <file_sep>/* * Copyright (c) 2016, prpl Foundation * * Permission to use, copy, modify, and/or distribute this software for any purpose with or without * fee is hereby granted, provided that the above copyright notice and this permission notice appear * in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE * FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * * This code was written by <NAME> at Embedded System Group (GSE) at PUCRS/Brazil. */ #ifndef __RISCV__ #define __RISCV__ #define MTIME (*(volatile long long *)(0x02000000 + 0xbff8)) #define MTIMECMP (*(volatile long long *)(0x02000000 + 0x4000)) #define read_csr(reg) ({ unsigned long __tmp; \ asm volatile ("csrr %0, " #reg : "=r"(__tmp)); __tmp; }) #define write_csr(reg, val) ({ \ asm volatile ("csrw " #reg ", %0" :: "rK"(val)); }) #define set_csr_bits(reg, bit) ({ unsigned long __tmp; \ asm volatile ("csrrs %0, " #reg ", %1" : "=r"(__tmp) : "rK"(bit)); \ __tmp; }) #define clear_csr_bits(reg, bit) ({ unsigned long __tmp; \ asm volatile ("csrrc %0, " #reg ", %1" : "=r"(__tmp) : "rK"(bit)); \ __tmp; }) static inline long get_field(uint32_64_t reg, long mask){ return ((reg & mask) / (mask & ~(mask << 1))); } static inline long set_field(uint64_t reg, long mask, long val){ return ((reg & ~mask) | ((val * (mask & ~(mask << 1))) & mask)); } #define __riscv_xlen 64 #define CSR_FFLAGS 1 #define CSR_FRM 2 #define CSR_FCSR 3 #define CSR_MCYCLE 4 #define CSR_MINSTRET 5 #define CSR_MCYCLEH 6 #define CSR_MINSTRETH 7 #define CSR_CYCLE 8 #define CSR_TIME 9 #define CSR_INSTRET 10 #define CSR_CYCLEH 11 #define CSR_TIMEH 12 #define CSR_INSTRETH 13 #define CSR_MVENDORID 14 #define CSR_MARCHID 15 #define CSR_MIMPID 16 #define CSR_MHARTID 17 #define CSR_MSTATUS 18 #define CSR_MISA 19 #define CSR_MEDELEG 20 #define CSR_MIDELEG 21 #define CSR_MIE 22 #define CSR_MTVEC 23 #define CSR_MCOUNTEREN 24 #define CSR_MSCRATCH 25 #define CSR_MEPC 26 #define CSR_MCAUSE 27 #define CSR_MTVAL 28 #define CSR_MIP 29 #define CSR_SSTATUS 30 #define CSR_SEDELEG 31 #define CSR_SIDELEG 32 #define CSR_SIE 33 #define CSR_STVEC 34 #define CSR_SCOUNTEREN 35 #define CSR_SSCRATCH 36 #define CSR_SEPC 37 #define CSR_SCAUSE 38 #define CSR_STVAL 39 #define CSR_SIP 40 #define CSR_SATP 41 #define CSR_PMPCFG0 42 #define CSR_PMPCFG1 43 #define CSR_PMPCFG2 44 #define CSR_PMPCFG3 45 #define CSR_PMPADDR0 46 #define CSR_PMPADDR1 47 #define CSR_PMPADDR2 48 #define CSR_PMPADDR3 49 #define CSR_PMPADDR4 50 #define CSR_PMPADDR5 51 #define CSR_PMPADDR6 52 #define CSR_PMPADDR7 53 #define CSR_PMPADDR8 54 #define CSR_PMPADDR9 55 #define CSR_PMPADDR10 56 #define CSR_PMPADDR11 57 #define CSR_PMPADDR12 58 #define CSR_PMPADDR13 59 #define CSR_PMPADDR14 60 #define CSR_PMPADDR15 61 #define MSTATUS_UIE 0x00000001 #define MSTATUS_SIE 0x00000002 #define MSTATUS_HIE 0x00000004 #define MSTATUS_MIE 0x00000008 #define MSTATUS_UPIE 0x00000010 #define MSTATUS_SPIE 0x00000020 #define MSTATUS_HPIE 0x00000040 #define MSTATUS_MPIE 0x00000080 #define MSTATUS_SPP 0x00000100 #define MSTATUS_HPP 0x00000600 #define MSTATUS_MPP 0x00001800 #define MSTATUS_FS 0x00006000 #define MSTATUS_XS 0x00018000 #define MSTATUS_MPRV 0x00020000 #define MSTATUS_SUM 0x00040000 #define MSTATUS_MXR 0x00080000 #define MSTATUS_TVM 0x00100000 #define MSTATUS_TW 0x00200000 #define MSTATUS_TSR 0x00400000 #define MSTATUS32_SD 0x80000000 #define MSTATUS64_SD 0x8000000000000000 #define SSTATUS_UIE 0x00000001 #define SSTATUS_SIE 0x00000002 #define SSTATUS_UPIE 0x00000010 #define SSTATUS_SPIE 0x00000020 #define SSTATUS_SPP 0x00000100 #define SSTATUS_FS 0x00006000 #define SSTATUS_XS 0x00018000 #define SSTATUS_SUM 0x00040000 #define SSTATUS_MXR 0x00080000 #define SSTATUS32_SD 0x80000000 #define SSTATUS64_SD 0x8000000000000000 #if defined(RISCV64) #define MCAUSE_INT (1ULL<<63) #define MCAUSE_MASK 0x7FFFFFFFFFFFFFFF #else #define MCAUSE_INT (1<<31) #define MCAUSE_MASK 0x7FFFFFFF #endif #define SATP_ASID_MASK 0x0FFFF00000000000 #define SATP_PPN_MASK 0xFFFFFFFFFFF #define DCSR_XDEBUGVER (3U<<30) #define DCSR_NDRESET (1<<29) #define DCSR_FULLRESET (1<<28) #define DCSR_EBREAKM (1<<15) #define DCSR_EBREAKH (1<<14) #define DCSR_EBREAKS (1<<13) #define DCSR_EBREAKU (1<<12) #define DCSR_STOPCYCLE (1<<10) #define DCSR_STOPTIME (1<<9) #define DCSR_CAUSE (7<<6) #define DCSR_DEBUGINT (1<<5) #define DCSR_HALT (1<<3) #define DCSR_STEP (1<<2) #define DCSR_PRV (3<<0) #define DCSR_CAUSE_NONE 0 #define DCSR_CAUSE_SWBP 1 #define DCSR_CAUSE_HWBP 2 #define DCSR_CAUSE_DEBUGINT 3 #define DCSR_CAUSE_STEP 4 #define DCSR_CAUSE_HALT 5 #define MCONTROL_TYPE(xlen) (0xfULL<<((xlen)-4)) #define MCONTROL_DMODE(xlen) (1ULL<<((xlen)-5)) #define MCONTROL_MASKMAX(xlen) (0x3fULL<<((xlen)-11)) #define MCONTROL_SELECT (1<<19) #define MCONTROL_TIMING (1<<18) #define MCONTROL_ACTION (0x3f<<12) #define MCONTROL_CHAIN (1<<11) #define MCONTROL_MATCH (0xf<<7) #define MCONTROL_M (1<<6) #define MCONTROL_H (1<<5) #define MCONTROL_S (1<<4) #define MCONTROL_U (1<<3) #define MCONTROL_EXECUTE (1<<2) #define MCONTROL_STORE (1<<1) #define MCONTROL_LOAD (1<<0) #define MCONTROL_TYPE_NONE 0 #define MCONTROL_TYPE_MATCH 2 #define MCONTROL_ACTION_DEBUG_EXCEPTION 0 #define MCONTROL_ACTION_DEBUG_MODE 1 #define MCONTROL_ACTION_TRACE_START 2 #define MCONTROL_ACTION_TRACE_STOP 3 #define MCONTROL_ACTION_TRACE_EMIT 4 #define MCONTROL_MATCH_EQUAL 0 #define MCONTROL_MATCH_NAPOT 1 #define MCONTROL_MATCH_GE 2 #define MCONTROL_MATCH_LT 3 #define MCONTROL_MATCH_MASK_LOW 4 #define MCONTROL_MATCH_MASK_HIGH 5 #define MIP_SSIP (1 << IRQ_S_SOFT) #define MIP_HSIP (1 << IRQ_H_SOFT) #define MIP_MSIP (1 << IRQ_M_SOFT) #define MIP_STIP (1 << IRQ_S_TIMER) #define MIP_HTIP (1 << IRQ_H_TIMER) #define MIP_MTIP (1 << IRQ_M_TIMER) #define MIP_SEIP (1 << IRQ_S_EXT) #define MIP_HEIP (1 << IRQ_H_EXT) #define MIP_MEIP (1 << IRQ_M_EXT) #define SIP_SSIP MIP_SSIP #define SIP_STIP MIP_STIP #define PRV_U 0 #define PRV_S 1 #define PRV_H 2 #define PRV_M 3 #define SPTBR32_MODE 0x80000000 #define SPTBR32_ASID 0x7FC00000 #define SPTBR32_PPN 0x003FFFFF #define SPTBR64_MODE 0xF000000000000000 #define SPTBR64_ASID 0x0FFFF00000000000 #define SPTBR64_PPN 0x00000FFFFFFFFFFF #define SPTBR_MODE_OFF 0 #define SPTBR_MODE_SV32 1 #define SPTBR_MODE_SV39 8 #define SPTBR_MODE_SV48 9 #define SPTBR_MODE_SV57 10 #define SPTBR_MODE_SV64 11 #define PMP_R 0x01 #define PMP_W 0x02 #define PMP_X 0x04 #define PMP_A 0x18 #define PMP_L 0x80 #define PMP_SHIFT 2 #define PMPCFG_COUNT 4 #define PMPADDR_COUNT 16 #define PMP_OFF 0x00 #define PMP_TOR 0x08 #define PMP_NA4 0x10 #define PMP_NAPOT 0x18 #define IRQ_S_SOFT 1 #define IRQ_H_SOFT 2 #define IRQ_M_SOFT 3 #define IRQ_S_TIMER 5 #define IRQ_H_TIMER 6 #define IRQ_M_TIMER 7 #define IRQ_S_EXT 9 #define IRQ_H_EXT 10 #define IRQ_M_EXT 11 #define IRQ_COP 12 #define IRQ_HOST 13 #define DEFAULT_RSTVEC 0x00001000 #define CLINT_BASE 0x02000000 #define CLINT_SIZE 0x000c0000 #define EXT_IO_BASE 0x40000000 #define DRAM_BASE 0x80000000 // page table entry (PTE) fields #define PTE_V 0x001 // Valid #define PTE_R 0x002 // Read #define PTE_W 0x004 // Write #define PTE_X 0x008 // Execute #define PTE_U 0x010 // User #define PTE_G 0x020 // Global #define PTE_A 0x040 // Accessed #define PTE_D 0x080 // Dirty #define PTE_SOFT 0x300 // Reserved for Software #define PTE_PPN_SHIFT 10 #define PTE_TABLE(PTE) (((PTE) & (PTE_V | PTE_R | PTE_W | PTE_X)) == PTE_V) #ifdef __riscv #if __riscv_xlen == 64 # define MSTATUS_SD MSTATUS64_SD # define SSTATUS_SD SSTATUS64_SD # define RISCV_PGLEVEL_BITS 9 # define SPTBR_MODE SPTBR64_MODE #else # define MSTATUS_SD MSTATUS32_SD # define SSTATUS_SD SSTATUS32_SD # define RISCV_PGLEVEL_BITS 10 # define SPTBR_MODE SPTBR32_MODE #endif #define RISCV_PGSHIFT 12 #define RISCV_PGSIZE (1 << RISCV_PGSHIFT) #endif #define TLB_LOAD_FETCH_EXCEPTION 0x2 #define TLB_STORE_EXCEPTION 0x3 #define GUEST_EXIT_EXCEPTION 0x1b #define GUEST_INSTRUCTION_EMULATION 0 #define GUEST_HYPERCALL 2 #define GUESTCTL1_RID_SHIFT 16 #define GUESTCLT2_GRIPL_SHIFT 24 #define GUESTCLT2_VIP_SHIFT 10 /* RISCV REGISTERS */ #define REG_ZERO 0 #define REG_RA 1 #define REG_SP 2 #define REG_GP 3 #define REG_TP 4 #define REG_T0 5 #define REG_T1 6 #define REG_T2 7 #define REG_S0 8 #define REG_S1 9 #define REG_A0 10 #define REG_A1 11 #define REG_A2 12 #define REG_A3 13 #define REG_A4 14 #define REG_A5 15 #define REG_A6 16 #define REG_A7 17 #define REG_S2 18 #define REG_S3 19 #define REG_S4 20 #define REG_S5 21 #define REG_S6 22 #define REG_S7 23 #define REG_S8 24 #define REG_S9 25 #define REG_S10 26 #define REG_S11 27 #define REG_T3 28 #define REG_T4 29 #define REG_T5 30 #define REG_T6 31 #endif <file_sep>/* * Copyright (c) 2016, prpl Foundation * * Permission to use, copy, modify, and/or distribute this software for any purpose with or without * fee is hereby granted, provided that the above copyright notice and this permission notice appear * in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE * FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * * This code was written by <NAME> at Embedded System Group (GSE) at PUCRS/Brazil. * */ #include <config.h> #include <types.h> #include <baikal-t1.h> #include <uart.h> /** * @file uart.c * * @section DESCRIPTION * * UART initialization and low level UART functions. * */ /** * @brief Configures UART2 as stdout and UART6 as alternative. * @param baudrate_u2 UART2 baudrate. * @param baudrate_u6 UART6 baudrate. * @param sysclk System clock. */ void init_uart(uint32_t baudrate_u2, uint32_t baudrate_u6, uint32_t sysclk){ } /** * @brief Write char to UART2. * @param c Character to be writed. */ void putchar(uint8_t c){ while( !(UART0_LSR&0x40) ); UART0_RBR = c; } /** * @brief Block and wait for a character. * @return Read character. */ uint32_t getchar(void){ } <file_sep>#include <config.h> #include <types.h> #include <qemu_virt.h> #include <uart.h> #include <platform.h> /** * @file uart.c * * @section DESCRIPTION * * UART initialization and low level UART functions. * */ /** * @brief Configures UART as stdout. * @param baudrate_u2 UART baudrate. * @param baudrate_u6 not used. * @param sysclk System clock. */ void init_uart(uint32_t baudrate_u2, uint32_t baudrate_u6, uint32_t sysclk){ uint32_t divisor = sysclk / (16 * baudrate_u2); UART0_CTRL_ADDR(UART_LCR) = UART_LCR_DLAB; UART0_CTRL_ADDR(UART_DLL) = divisor & 0xff; UART0_CTRL_ADDR(UART_DLM) = (divisor >> 8) & 0xff; UART0_CTRL_ADDR(UART_LCR) = UART_LCR_PODD | UART_LCR_8BIT; } /** * @brief Write char to UART. * @param c Character to be writed. */ void putchar(uint8_t c){ while ((UART0_CTRL_ADDR(UART_LSR) & UART_LSR_RI) == 0); UART0_CTRL_ADDR(UART_THR) = c; } /** * @brief Block and wait for a character. * @return Read character. */ uint32_t getchar(void){ return 0; } <file_sep>/* C o*pyright (c) 2016, prpl Foundation Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. This code was written by <NAME> at Embedded System Group (GSE) at PUCRS/Brazil. */ #ifndef _IO_H #define _IO_H #include <arch.h> #define ENABLE_LED1 writeio(TRISGCLR, 1 << 6) #define ENABLE_LED2 writeio(TRISDCLR, 1 << 4) #define ENABLE_LED3 writeio(TRISBCLR, 1 << 11) #define ENABLE_LED4 write(TRISGCLR, 1 << 15) #define TOGGLE_LED1 writeio(LATGINV, 1 << 6) #define TOGGLE_LED2 writeio(LATDINV, 1 << 4) #define TOGGLE_LED2 writeio(LATBINV, 1 << 11) #define TOGGLE_LED2 writeio(LATGINV, 1 << 15) #endif <file_sep>/* Copyright (c) 2016, prpl Foundation Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. This code was written by <NAME> at Embedded System Group (GSE) at PUCRS/Brazil. */ /* constants, tests and transformations */ #define NULL ((void *)0) #define USED 1 #define TRUE 1 #define FALSE 0 #define isprint(c) (' '<=(c)&&(c)<='~') #define isspace(c) ((c)==' '||(c)=='\t'||(c)=='\n'||(c)=='\r') #define isdigit(c) ('0'<=(c)&&(c)<='9') #define islower(c) ('a'<=(c)&&(c)<='z') #define isupper(c) ('A'<=(c)&&(c)<='Z') #define isalpha(c) (islower(c)||isupper(c)) #define isalnum(c) (isalpha(c)||isdigit(c)) #define min(a,b) ((a)<(b)?(a):(b)) #define ntohs(A) (((A)>>8) | (((A)&0xff)<<8)) #define ntohl(A) (((A)>>24) | (((A)&0xff0000)>>8) | (((A)&0xff00)<<8) | ((A)<<24)) /* custom C library */ #ifndef PICOTCP extern void putchar(int32_t value); extern int32_t kbhit(void); extern uint32_t getchar(void); extern int8_t *strcpy(int8_t *dst, const int8_t *src); extern int8_t *strncpy(int8_t *s1, int8_t *s2, int32_t n); extern int8_t *strcat(int8_t *dst, const int8_t *src); extern int8_t *strncat(int8_t *s1, int8_t *s2, int32_t n); extern int32_t strcmp(const int8_t *s1, const int8_t *s2); extern int32_t strncmp(int8_t *s1, int8_t *s2, int32_t n); extern int8_t *strstr(const int8_t *string, const int8_t *find); extern int32_t strlen(const int8_t *s); extern int8_t *strchr(const int8_t *s, int32_t c); extern int8_t *strpbrk(int8_t *str, int8_t *set); extern int8_t *strsep(int8_t **pp, int8_t *delim); extern int8_t *strtok(int8_t *s, const int8_t *delim); extern void *memcpy(void *dst, const void *src, uint32_t n); extern void *memmove(void *dst, const void *src, uint32_t n); extern int32_t memcmp(const void *cs, const void *ct, uint32_t n); extern void *memset(void *s, int32_t c, uint32_t n); extern int32_t strtol(const int8_t *s, int8_t **end, int32_t base); extern int32_t atoi(const int8_t *s); extern float atof(const int8_t *p); extern int8_t *itoa(int32_t i, int8_t *s, int32_t base); extern int32_t puts(const int8_t *str); extern int8_t *gets(int8_t *s); extern int32_t abs(int32_t n); extern int32_t random(void); extern void srand(uint32_t seed); extern int32_t printf(const int8_t *fmt, ...); extern int32_t sprintf(int8_t *out, const int8_t *fmt, ...); #endif typedef volatile unsigned int mutex_t; void lock(mutex_t *mutex); void spinlock(mutex_t *mutex); void unlock(mutex_t *mutex); <file_sep>/* Copyright (c) 2016, prpl Foundation Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. This code was written by <NAME> at Embedded System Group (GSE) at PUCRS/Brazil. */ /** * @file uart_driver.c * * @section DESCRIPTION * * Interrupt-driven virtualized console driver that queues the guest's UART read/write calls. * * The guest's call the HCALL_UART_SEND/HCALL_UART_RECV * hypercalls being blocked to wait by UART tranfers to complete * when necessary. * */ #include <globals.h> #include <hal.h> #include <pic32mz.h> #include <mips_cp0.h> #include <libc.h> #include <hypercall_defines.h> #include <hypercall.h> #include <driver.h> #include <interrupts.h> #include <pic32mz.h> #include <platform.h> /** * @struct * @brief Keep the status of queued UART transfers. */ struct transfer_info{ uint32_t buf_addr; /**< Guest's buffer address */ uint32_t next_character; /**< Next character to transmit */ uint32_t size; /**< buffer size */ vcpu_t* vcpu; /**< VCPU owner */ }; /** Tranfer status for each VCPU. */ static struct transfer_info transfers[NVMACHINES]; /** Active tranfer */ static volatile int32_t active_transfer = -1; /** * @brief Schedule a UART TX transfer. Block the VCPU and enable UART TX interrupt. * @param addr Transmit buffer on guest. * @param next_character Next character to transmit. * @param size Buffer size. */ static void scheduler_transfer_interrupt(uint32_t addr, uint32_t next_character, uint32_t size){ uint32_t j = vcpu_in_execution->id - 1; if(active_transfer < 0){ /* Enable the requested interrupt */ IECSET(UART_IRQ_TX >> 5) = 1 << (UART_IRQ_TX & 31); active_transfer = j; } transfers[j].vcpu = vcpu_in_execution; transfers[j].next_character = next_character; transfers[j].size = size; transfers[j].vcpu->state = VCPU_BLOCKED; transfers[j].buf_addr = addr; } /** * @brief UART TX Interrupt handler routine. */ static void transfer_tx_done(){ uint32_t j = active_transfer; /* Clear TX interrupt flag */ IFSCLR(UART_IRQ_TX >> 5) = 1 << (UART_IRQ_TX & 31); /* Map the guest's buffer. */ char* str_mapped = (char*)tlbCreateEntry(transfers[j].buf_addr, transfers[j].vcpu->vm->base_addr, transfers[j].size, 0xf, CACHEABLE); /* Write characters to the hardware queue. */ for (; transfers[j].next_character < transfers[j].size && !(UARTSTAT&USTA_UTXBF); transfers[j].next_character++){ UARTTXREG = str_mapped[transfers[j].next_character]; } /* If the transfer is finished unblock the VCPU and schedule the next tranfer if necessary. */ if(transfers[j].next_character >= transfers[j].size){ transfers[j].vcpu->state = VCPU_RUNNING; transfers[j].vcpu = NULL; for(j=0; j<NVMACHINES; j++){ if(transfers[j].vcpu != NULL){ active_transfer = j; return; } } IECCLR(UART_IRQ_TX >> 5) = 1 << (UART_IRQ_TX & 31); active_transfer = -1; } } /** * @brief UART TX hypercall. * Write characters to the hardware queue and block the VCPU when * the queue is full and still there are characteres to tranfer. */ static void send(){ /*TODO: Implement interrupt-driven support to avoid to block the hypervisor for long periods. */ uint32_t i = 0; char* str = (char*)MoveFromPreviousGuestGPR(REG_A0); uint32_t size = MoveFromPreviousGuestGPR(REG_A1); /* Map the guest's buffer. */ char* str_mapped = (char*)tlbCreateEntry((uint32_t)str, vm_in_execution->base_addr, size, 0xf, CACHEABLE); /* Write to the hardware queue. */ if(active_transfer<0){ for(i=0; i<size && !(UARTSTAT&USTA_UTXBF); i++){ UARTTXREG = str_mapped[i]; } } /* UART TX queue is full. Enable interrupt tranfer mode. */ if(i<size){ scheduler_transfer_interrupt((uint32_t)str, i, size); } MoveToPreviousGuestGPR(REG_V0, size); } /** * UART receive hypercall. * */ /*static void recv(){ TODO: Implement interrupt-driven receiver driver }*/ /** * @brief UART Driver init call. */ static void uart_driver_init(){ uint32_t offset; if (register_hypercall(send, HCALL_UART_SEND) < 0){ ERROR("Error registering the HCALL_GET_VM_ID hypercall"); return; } if ((offset = register_interrupt(transfer_tx_done)) == 0){ WARNING("Error on UART interrupt registration."); return; } OFF(UART_IRQ_TX) = offset; /* Interrupt is generated and asserted when all characters have been transmitted */ UARTSTAT = (UARTSTAT & ~(3 << 14)) | 1 << 14; /* Clear the priority and sub-priority */ IPCCLR(UART_IRQ_TX >> 2) = 0x1f << (8 * (UART_IRQ_TX & 0x03)); /* Set the priority and sub-priority */ IPCSET(UART_IRQ_TX >> 2) = 0x1f << (8 * (UART_IRQ_TX & 0x03)); /* Clear the requested interrupt bit */ IFSCLR(UART_IRQ_TX >> 5) = 1 << (UART_IRQ_TX & 31); memset(transfers, 0, sizeof(transfers)); printf("\nUART driver enabled. Interrupt vector 0x%x", offset); } driver_init(uart_driver_init); <file_sep>/* Copyright (c) 2016, prpl Foundation Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. This code was written by <NAME> at Embedded System Group (GSE) at PUCRS/Brazil. */ #ifndef _QUEUE_H #define _QUEUE_H #include <types.h> /** * @brief Queue data structure. */ struct queue_t { int32_t size; /*!< queue size (maximum number of elements) */ int32_t elem; /*!< number of elements queued */ int32_t head; /*!< first element of the queue */ int32_t tail; /*!< last element of the queue */ void **data; /*!< pointer to an array of pointers to node data */ }; struct queue_t *queue_create(int32_t size); int32_t queue_destroy(struct queue_t *q); int32_t queue_count(struct queue_t *q); int32_t queue_addtail(struct queue_t *q, void *ptr); void *queue_remhead(struct queue_t *q); void *queue_remtail(struct queue_t *q); void *queue_get(struct queue_t *q, int32_t elem); int32_t queue_set(struct queue_t *q, int32_t elem, void *ptr); int32_t queue_swap(struct queue_t *q, int32_t elem1, int32_t elem2); #endif<file_sep>#Copyright (c) 2016, prpl Foundation # #Permission to use, copy, modify, and/or distribute this software for any purpose with or without #fee is hereby granted, provided that the above copyright notice and this permission notice appear #in all copies. # #THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE #INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE #FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM #LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, #ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # #This code was written by <NAME> at Embedded System Group (GSE) at PUCRS/Brazil. # Define your additional include paths #INC_DIRS += $(TOPDIR)../../benchmark/dhrystone/ #Aditional C flags CFLAGS += -DPIC32MZ -DTIME -DREG=register #Aditional Libraries #LIBS += #stack size 2048 bytes STACK_SIZE = 2048 #Include your additional mk files here. repo-conf: if [ ! -d "$(TOPDIR)../../benchmark" ]; then \ git clone https://github.com/crmoratelli/prplHypervisor-benckmarks.git $(TOPDIR)../../benchmark; \ fi app: repo-conf $(CC) $(CFLAGS) $(INC_DIRS) -fno-inline $(TOPDIR)../../benchmark/dhrystone/dhry_1.c -o $(TOPDIR)apps/$(APP)/dhry_1.o $(CC) $(CFLAGS) $(INC_DIRS) -fno-inline $(TOPDIR)../../benchmark/dhrystone/dhry_2.c -o $(TOPDIR)apps/$(APP)/dhry_2.o $(CC) $(CFLAGS) $(INC_DIRS) $(TOPDIR)apps/$(APP)/dhrystone.c -o $(TOPDIR)apps/$(APP)/dhrystone.o <file_sep>/* Copyright (c) 2016, prpl Foundation Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. This code was written by <NAME> at Embedded System Group (GSE) at PUCRS/Brazil. */ /** * Generates output signal on pin RPD3 (J5 MOSI) on Curiosity board. * * Used as an interrupt generator for interrupt latency tests. See * documentation for more details. * * */ #include <arch.h> #include <libc.h> #include <hypercalls.h> #include <guest_interrupts.h> #include <platform.h> #include <io.h> int main() { uint32_t time = mfc0(CP0_COUNT, 0); uint32_t interval = 0; /* Configure PIN RPD3 as output */ writeio(TRISDCLR, 8); srand(0xdeadbeef); while (1){ if(wait_time(time, interval)){ time = mfc0(CP0_COUNT, 0); writeio(LATDINV, 8); interval = random()%50 + 1; } } return 0; } <file_sep>/* Copyright (c) 2016, prpl Foundation Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. This code was written by <NAME> at Embedded System Group (GSE) at PUCRS/Brazil. */ /** * @file list.c * * @section LICENSE * * @section DESCRIPTION * * List manipulation primitives and auxiliary functions. List structures are allocated * dynamically at runtime, which makes them very flexible. Memory is allocated / deallocated * on demand, so additional memory management penalties are incurred. */ #include <libc.h> #include <malloc.h> #include <linkedlist.h> /** * @brief Appends a new node to the end of the list. * * @param lst is a pointer to a list structure. * @param item is a pointer to data belonging to the list node. * * @return 0 when successful and -1 otherwise. */ int32_t list_append(struct list_t **lst, void *item) { struct list_t *t1, *t2; t1 = (struct list_t *)malloc(sizeof(struct list_t)); if(t1==NULL){ return -1; } t1->elem = item; t1->next = NULL; if(*lst==NULL){ *lst = t1; return 0; } t2 = *lst; while (t2->next){ t2 = t2->next; } t2->next = t1; return 0; } /** * @brief Removes all elements of the list. * * @param lst is a referece to a pointer to a list structure. * * @return 0 when successful and -1 otherwise. */ int32_t list_remove_all(struct list_t **lst) { struct list_t *aux; while(*lst){ aux = *lst; *lst = (*lst)->next; free(aux->elem); free(aux); } return 0; } /** * @brief Returns the number of nodes in a list. * * @param lst is a pointer to a list structure. * * @return The number of elements in the list. */ int32_t list_count(struct list_t *lst) { struct list_t *t1; int32_t i = 0; t1 = lst; while ((t1 = t1->next)) i++; return i; } <file_sep>/* Copyright (c) 2016, prpl Foundation Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. This code was written by <NAME> at Embedded System Group (GSE) at PUCRS/Brazil. */ /* This example shows how to use the hypervisor's interrupt redirection feature. * * Interrupt redirection allows for the hypervisor to inject a virtual interrupt on a * guest that desires to implements its own device driver. PIC32MZ lacks of the interrupt * pass-through feature. Interrupt redirection emulates the interrupt pass-through. * * Use the valid CFG file (redirection.cfg) to configure the hypervisor to this application. * * This application receives UART RX interrupts and read the characters storing them into an array. * * To send characters to the application use: * echo "Hello World!" > /dev/ttyACM0 * * Substitute /dev/ttyACM0 by your serial port. * * See the User's Guide for more information. * * */ #include <arch.h> #include <libc.h> #include <hypercalls.h> #include <guest_interrupts.h> #include <platform.h> #include <io.h> #define DATA_SZ 128 static uint8_t str[DATA_SZ]; static volatile int32_t t2 = 0; void irq_timer(){ t2++; } void irq_uart2_rx(){ static uint32_t i = 0; while (read(U2STA) & USTA_URXDA){ str[i%DATA_SZ] = read(U2RXREG); i++; } str[i%DATA_SZ] = '\0'; reenable_interrupt(GUEST_USER_DEFINED_INT_1); } int main() { uint32_t timer = 0; interrupt_register(irq_timer, GUEST_TIMER_INT); interrupt_register(irq_uart2_rx, GUEST_USER_DEFINED_INT_1); ENABLE_LED1; while (1){ if(wait_time(timer, 1000)) { printf("\nRead data: %s \nTotal of %d timer ticks.", str, t2); /* Blink Led */ TOGGLE_LED1; timer = mfc0(CP0_COUNT, 0); } } return 0; } <file_sep>/* * Copyright (c) 2016, prpl Foundation * * Permission to use, copy, modify, and/or distribute this software for any purpose with or without * fee is hereby granted, provided that the above copyright notice and this permission notice appear * in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE * FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * * This code was written by <NAME> at Embedded System Group (GSE) at PUCRS/Brazil. * */ #ifndef _INSTRUCTION_EMULATION #define _INSTRUCTION_EMULATION /* Extract instructions fields */ #define OPCODE(i) (i >> 26) #define FUNC(i) (i & 0x3F) #define RS(i) ((i >> 21) & 0x1f) #define RT(i) ((i >> 16) & 0x1f) #define RD(i) ((i >> 11) & 0x1f) #define SEL(i) (i & 0x7) #define IMED(i) (i & 0xFFFF) #define SIMED(i) (IMED(i) & 0x8000 ? 0xFFFF0000 | IMED(i) : IMED(i)) #define JT(i) ((x & 0x3FFFFFF) << 2) #define UPPERPC(i) (i & 0xF0000000) #define CO(i) ((i >> 25) & 0x1) uint32_t __instruction_emulation(uint32_t epc); #endif <file_sep>/* Copyright (c) 2016, prpl Foundation Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. This code was written by <NAME> at Embedded System Group (GSE) at PUCRS/Brazil. */ /* Shared buffer example for PUF */ #include <arch.h> #include <libc.h> volatile int32_t t2 = 0; void irq_timer(){ t2++; } char buffer[32] = "abcdefghijklmnopkrstuvxzABCDEFGH"; int main() { /* get guest id */ uint32_t guestid = hyp_get_guest_id(); printf("Guest ID: %d", guestid); /* share buffer with the hypervisor */ hyp_puf_shared_memory(guestid, buffer); /* printf the hypervisor message */ printf("\nModified guest buffer: %s", buffer); /* do nothing */ while(1); return 0; } <file_sep>/* Copyright (c) 2016, prpl Foundation Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. This code was written by <NAME> at Embedded System Group (GSE) at PUCRS/Brazil. */ /** * @file hal.c * * @section DESCRIPTION * * Functions for access and configuration of the CP0 and Guest CP0. * Supports the M5150 processor core and initial hypervisor configuration. */ #include <libc.h> #include <types.h> #include <hal.h> #include <globals.h> #include <proc.h> #include <board.h> #include <malloc.h> #include <vm.h> #include <driver.h> #include <timer.h> #include <libc.h> /* HEAP size as calculated by the linker script. */ extern uint32_t _heap_size; extern uint64_t __pages_start; /* Stringfy compiler parameters. */ #define STR(x) #x #define STR_VALUE(x) STR(x) /** @brief Read the misa register and translate the extention bits * to a string. * @param ex Char array. * @param sz Size of the array. * @return pointer to the array. */ static char* get_extensions(char *ex, uint32_t sz){ uint32_t i, c = 0, mask = 1; uint32_t misa = read_csr(misa); for(i=0; (i<26) & (i<sz); i++){ if(misa & mask){ ex[c++] = 65 + i; } mask = mask << 1; } ex[c] = 0; return ex; } /** @brief Determine the number of valid ASID bits in the SATP register. * @return number of valid bits. */ static int get_asid_sz(){ uint64_t asid; uint32_t i = 0; write_csr(satp, SATP_ASID_MASK); asid = get_field(read_csr(satp), SATP_ASID_MASK); while(asid & 0x1){ i++; asid >>= 1; } return i; } /** * @brief Early boot message. * Print to the stdout usefull hypervisor information. */ static void print_config(void){ char ex[26]; INFO("==========================================================="); INFO("prplHypervisor %s [%s, %s]", STR_VALUE(HYPVERSION), __DATE__, __TIME__); INFO("Copyright (c) 2016, prpl Foundation"); INFO("==========================================================="); INFO("CPU Core: %s", STR_VALUE(CPU_ID)); INFO("Extentions: %s", get_extensions(ex, sizeof(ex))); INFO("ASID size: %dbits", get_asid_sz()); INFO("Pages Address 0x%x", (uint64_t)&__pages_start); INFO("Board: %s", STR_VALUE(CPU_ARCH)); INFO("System Clock: %dMHz", CPU_FREQ/1000000); INFO("Heap Size: %dKbytes", (int)(&_heap_size)/1024); INFO("Scheduler: %dms", QUANTUM_SCHEDULER_MS); INFO("Guest Tick: %dms", SYSTEM_TICK_US/1000); INFO("VMs: %d\n", NVMACHINES); } /** * @brief C code entry. This is the first C code performed during * hypervisor initialization. Called from early boot stage to perform * overall hypervisor configuration. * * The hypervisor should never return form this call. The start_timer() * call should configure the system timer and wait by the first * timer interrupt. * */ void hyper_init(){ /* Specific board configuration. */ early_platform_init(); /* early boot messages with hypervisor configuration. */ print_config(); /* Processor inicialization */ if(LowLevelProcInit()){ CRITICAL("Low level processor initialization error."); } /* Configure the HEAP space on the allocator */ init_mem(); /*Enable global interrupt. IE bit in status register.*/ enableIE(); /*Initialize VCPUs and virtual machines*/ initializeMachines(); /* Initialize device drivers */ drivers_initialization(); /* Start system timer. Should not return from this call. * This call will wait for the first timer interrupt. */ start_timer(); /* Should never reach this point !!! */ CRITICAL("Hypervisor initialization error."); } /** * @brief Verify if the processor is in root-kernel mode. * @return 1 for root-kernel mode, 0 otherwise. */ int32_t isRootMode(){ return 0; } /** * @brief Verify if the processor implements the VZ module . * @return 1 VZ module available, 0 otherwise. */ int32_t hasVZ(){ return 0; } /** * @brief Set the GPR Shadow Bank. * The hypervisor uses the GPR shadow page 0. The others GPR shadows keep the VM's context. * * @return 0 for error or 1 for success. */ int32_t ConfigureGPRShadow(){ return 0; } /** * @brief Low level processor initialization. * Called once during hypervisor Initialization. * * @return 1 for error or 0 for success. */ int32_t LowLevelProcInit(){ write_csr(mstatus, read_csr(mstatus) | 0x100000); /* Enable fp instructions */ write_csr(mstatus, read_csr(mstatus) | (1 << 13)); return 0; } /** * @brief Extract the execCode field from cause register * * @return ExecCode value. */ uint32_t getCauseCode(){ return 0; } /** * @brief Extract the hypercall code from hypercall instruction. * * @return Hypercall code. */ uint64_t getHypercallCode(){ return MoveFromPreviousGuestGPR(REG_A7); } /** * @brief Checks if the exception happend on a branch delay slot. * * @return 0 for non branch delay slot, otherwise greater than 0. */ uint32_t getCauseBD(){ return 0; } /** * @brief Extracts the Guest ExecCode field from guestctl0 register. * * @return Guest ExecCode. */ uint32_t getGCauseCode(){ return 0; } /** * @brief Extracts the interrupt pending bits (IP0:IP9) from cause register. * * @return Interrupt pending bits. */ uint32_t getInterruptPending(){ return 0; } /** * @brief Set the Compare register to the next timer interruption. * */ void confTimer(uint32_t quantum){ } /** * @brief Set the IM bits on the status reg. * */ void setInterruptMask(uint32_t im){ } /** * @brief Clear the IM bits on the status reg . * */ void clearInterruptMask(uint32_t im){ } /** * @brief Enable global interrupt. IE bit in status register. * */ void enableIE(){ write_csr(mstatus, read_csr(mstatus) | 0xa); write_csr(mideleg, read_csr(mideleg) | 0x2); } /** * @brief Verify if the processor implements GuestID field. * * @return 1 for guestid supported, 0 otherwise. */ uint32_t hasGuestID(){ return 0; } /** * @brief Verify if the processor allow direct root mode. * * @return 1 for direct root supported, 0 otherwise. */ uint32_t isDirectRoot(){ return 0; } /** * @brief Set CP0 EPC. * */ void setEPC(uint64_t epc){ write_csr(mepc, epc); } /** * @brief Get CP0 EPC. * * @return EPC address. */ uint32_t getEPC(){ return 0; } /** * @brief Set root GuestID mode. * */ void setGuestRID(uint32_t guestrid){ } /** * @brief Set GuestID. * */ void setGuestID(uint32_t guestid){ } /** * @brief Get GuestID. * */ uint32_t getGuestID(void){ return 0; } /** * @brief Check if the processor uses root ASID. * * @return 1 for root ASID supported, 0 otherwise */ uint32_t isRootASID(){ return 0; } /** * @brief Set the processor's to Guest Mode bit. * */ void setGuestMode(){ } /** * @brief Clear the processor's to Guest Mode bit. * */ void clearGuestMode(){ } /** * @brief Set specific bits on CP0 STATUS reg.. * */ void setStatusReg(uint32_t bits){ } /** * @brief Check if the processor supports 1k page size. * * @return 0 for not supported, greather than 0 for supported. */ uint32_t has1KPageSupport(){ return 0; } /** * @brief Disable 1K page support to keep compatibility with 4K page size. * */ void Disable1KPageSupport(){ } /** * @brief Check if the processor will enter in guest mode on next eret instruction. * @return 1 is entering in guest mode, 0 no entering in guest mode. */ int32_t isEnteringGuestMode(){ return 0; } /** * @brief Get bad instruction address . * @return Bad instruction address. */ uint32_t getBadVAddress(){ return 0; } /** * @brief Set the Lowest GPR Shadow. * @return GPR value. */ void setLowestGShadow(uint32_t lowestshadow){ } /** * @brief Get the Lowest GPR Shadow. * @return Lowest guest GPR shadow. */ uint32_t getLowestGShadow(void){ return 0; } /** * @brief Set the previous shadow set. */ void setPreviousShadowSet(uint32_t shadow_set){ } /** * @brief Get the previous GPR Shadow. * @return Previous guest GPR shadow. */ uint32_t getPreviousShadowSet(){ return 0; } /** * @brief Get the number of GPR Shadows. * @return Number of GPR shadows. */ uint32_t getNumberGPRShadow(){ return 0; } /** * @brief Return the CP0 COUNTER. * @return CP0 COUNTER. */ uint32_t getCounter(void){ return 0; } /** * @brief Set CP0 GTOffset . */ void setGTOffset(int32_t gtoffset){ } /** * @brief Set CP0 GuestCLT2 . */ void setGuestCTL2(uint32_t guestclt2){ } /** * @brief Get CP0 GuestCLT2 . * * @return guestctl2 register value. */ uint32_t getGuestCTL2(){ return 0; } /** * @brief Get CP0 Random . * @return Random value. */ uint32_t getRandom(){ return 0; } /** * @brief Get the most recent instruction which caused a exception. * @return Bad Instruction. */ uint32_t getBadInstruction(){ return 0; } /** * @brief Wait for microseconds. * @param usec Wait time. */ void udelay (uint32_t usec){ } <file_sep>/* * Copyright (c) 2016, prpl Foundation * * Permission to use, copy, modify, and/or distribute this software for any purpose with or without * fee is hereby granted, provided that the above copyright notice and this permission notice appear * in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE * FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * * This code was written by <NAME> at Embedded System Group (GSE) at PUCRS/Brazil. * */ /** * @file instruction_emulation.c * * @section DESCRIPTION Functions to perform instruction emulation. This should be part of the vcpu.c file. * However, not all platforms will require it. For example, platorms that only perform baremetal applications * do not require instruction emulation. Platforms that virtualize Linux instances will require. */ #include <libc.h> #include <vcpu.h> #include <mips_cp0.h> #include <gpr_context.h> #include <globals.h> #include <instruction_emulation.h> /** * @brief Emulate instructions with CO field. * * @param badinstr Instruction that caused the trap. * @return 0 on success, otherwise error. */ static uint32_t co_instructions(uint32_t badinstr){ switch (FUNC(badinstr)){ case WAIT: /* wait instruction. */ return 1; default: return 1; } return 0; } /** * @brief Emulate mfc0 instructions. * * @param badinstr Instruction that caused the trap. * @return 0 on success, otherwise error. */ static uint32_t mfc0_instructions(uint32_t badinstr){ uint32_t rd = RD(badinstr); uint32_t rt = RT(badinstr); uint32_t regvalue; switch (rd){ case 12: if(SEL(badinstr) == 2){ /* read from COP0 (12, 2) SRSCTL */ regvalue = mfc0(CP0_SRSCTL, 2); regvalue = regvalue & ~SRSCLT_HSS; MoveToPreviousGuestGPR(rt, regvalue); return 0; } return 1; case 15: if (SEL(badinstr) == 0){ /* read from COP0 (15, 0) PRID */ //regvalue = (mfc0(CP0_PRID, 0) & ~0xff00) | 0x8000; regvalue = mfc0(CP0_PRID, 0); MoveToPreviousGuestGPR(rt, regvalue); return 0; } return 1; case 18: if (SEL(badinstr) == 0){ /* read from COP0 (18, 0) WATCHLo0 */ regvalue = mfgc0(CP0_WATCHLO, 0); MoveToPreviousGuestGPR(rt, regvalue); return 0; }else if (SEL(badinstr) == 1){ /* read from COP0 (18, 0) WATCHLo1 */ MoveToPreviousGuestGPR(rt, 0); return 0; } return 1; case 19: if (SEL(badinstr) == 0){ /* read from COP0 (18, 0) WATCHHi0 */ regvalue = mfgc0(CP0_WATCHHI, 0); MoveToPreviousGuestGPR(rt, regvalue); return 0; }else if (SEL(badinstr) == 1){ /* read from COP0 (18, 0) WATCHHi1 */ MoveToPreviousGuestGPR(rt, 0); return 0; } return 1; default: return 1; } return 0; } /** * @brief Emulate mtc0 instructions. * * @param badinstr Instruction that caused the trap. * @return 0 on success, otherwise error. */ static uint32_t mtc0_instructions(uint32_t badinstr){ uint32_t rd = RD(badinstr); uint32_t rt = RT(badinstr); uint32_t regvalue; switch (rd){ case 18: if (SEL(badinstr) == 0){ /* write to COP0 (18, 0) WATCHLo0 */ regvalue = MoveFromPreviousGuestGPR(rd); mtgc0(CP0_WATCHLO, 0, regvalue); return 0; }else if (SEL(badinstr) == 1){ /* write to COP0 (18, 1) WATCHLo1 */ return 0; } return 1; case 19: if (SEL(badinstr) == 0){ /* write to COP0 (19, 0) WATCHHi0 */ regvalue = MoveFromPreviousGuestGPR(rd); mtgc0(CP0_WATCHHI, 0, regvalue); return 0; }else if (SEL(badinstr) == 1){ /* write to COP0 (19, 1) WATCHHi1 */ return 0; } return 1; default: return 1; } return 0; } /** * @brief Instruction emulation entry. * */ uint32_t __instruction_emulation(uint32_t epc){ uint32_t badinstr = getBadInstruction(); uint32_t rs; switch(OPCODE(badinstr)){ /* COP0 instructions */ case CP0: switch (CO(badinstr)){ case 0x1: if(co_instructions(badinstr)){ goto instr_not_supported; } break; case 0: rs = RS(badinstr); switch (rs){ case MTC: if(mtc0_instructions(badinstr)){ goto instr_not_supported; } break; case MFC: if(mfc0_instructions(badinstr)){ goto instr_not_supported; } break; default: goto instr_not_supported; } break; default: goto instr_not_supported; } break; /* Cache instructions */ case CACHE: goto instr_not_supported; default: goto instr_not_supported; } return 0; instr_not_supported: WARNING("Instruction 0x%x emulation at 0x%x not supported.", badinstr, epc); return 1; }<file_sep>#include <config.h> #include <types.h> #include "pic32mz.h" void init_uart(uint32_t baudrate_u4, uint32_t baudrate_u1, uint32_t sysclk){ U4BRG = BRG_BAUD (CPU_SPEED / 2, baudrate_u4); U4STA = 0; U4MODE = UMODE_PDSEL_8NPAR | /* 8-bit data, no parity */ UMODE_ON; /* UART Enable */ U4STASET = USTA_URXEN | USTA_UTXEN; /* RX / TX Enable */ /*TODO: configure UART1 */ } void putchar(char c){ while(U4STA&USTA_UTXBF); U4TXREG = c; } int32_t kbhit(void){ return (U4STA & USTA_URXDA); } uint32_t getchar(void){ while(!kbhit()); return (uint32_t)U4RXREG; } <file_sep>/* Copyright (c) 2016, prpl Foundation Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. This code was written by <NAME> at Embedded System Group (GSE) at PUCRS/Brazil. */ // THIS FILE IS AUTOMATICALLY GENERATED. // MODIFY sources/mkCfiles.py INSTEAD OF THIS. #include "web_files.h" static const unsigned char bg_stripe_png[] = { 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x00, 0x1e, 0x08, 0x06, 0x00, 0x00, 0x00, 0x3b, 0x30, 0xae, 0xa2, 0x00, 0x00, 0x00, 0x06, 0x62, 0x4b, 0x47, 0x44, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0xa0, 0xbd, 0xa7, 0x93, 0x00, 0x00, 0x00, 0x09, 0x70, 0x48, 0x59, 0x73, 0x00, 0x00, 0x0b, 0x13, 0x00, 0x00, 0x0b, 0x13, 0x01, 0x00, 0x9a, 0x9c, 0x18, 0x00, 0x00, 0x00, 0x07, 0x74, 0x49, 0x4d, 0x45, 0x07, 0xe0, 0x0c, 0x14, 0x0e, 0x22, 0x23, 0xcf, 0x50, 0x86, 0xb3, 0x00, 0x00, 0x08, 0xca, 0x49, 0x44, 0x41, 0x54, 0x48, 0xc7, 0x55, 0x97, 0x5b, 0x4f, 0xe3, 0x66, 0xdb, 0x85, 0x2f, 0xef, 0x77, 0xb1, 0x9d, 0x98, 0x24, 0x24, 0x90, 0x84, 0xd2, 0x81, 0xf6, 0x64, 0x54, 0xa9, 0xc7, 0xfd, 0x19, 0xfd, 0x0d, 0xfd, 0xad, 0x6d, 0xa5, 0xaa, 0x42, 0x6d, 0x05, 0x12, 0x23, 0x86, 0x21, 0x62, 0x80, 0x6c, 0xed, 0x38, 0xb6, 0x63, 0x3b, 0xb6, 0x9f, 0xf7, 0x60, 0x3e, 0x2c, 0x7d, 0xe7, 0xde, 0x3d, 0xf7, 0xbd, 0xd6, 0xb5, 0x96, 0xa5, 0x87, 0x87, 0x07, 0xb7, 0xaa, 0x2a, 0x0e, 0x87, 0x03, 0xaa, 0xaa, 0xb2, 0xdf, 0xef, 0xb1, 0x2c, 0x8b, 0x28, 0x8a, 0x38, 0x3b, 0x3b, 0xa3, 0x69, 0x1a, 0x92, 0x24, 0xa1, 0xaa, 0x2a, 0xb2, 0x2c, 0x63, 0x3c, 0x1e, 0x63, 0x18, 0x06, 0x55, 0x55, 0xa1, 0x69, 0x1a, 0x87, 0xc3, 0x81, 0xa6, 0x69, 0xa8, 0xeb, 0x1a, 0x55, 0x55, 0x09, 0xc3, 0x90, 0x93, 0x93, 0x13, 0xaa, 0xaa, 0x22, 0x0c, 0x43, 0xba, 0xdd, 0x2e, 0x00, 0x59, 0x96, 0x31, 0x1c, 0x0e, 0xb9, 0xb9, 0xb9, 0xe1, 0xe2, 0xe2, 0x02, 0xb5, 0x28, 0x0a, 0xea, 0xba, 0xc6, 0x30, 0x0c, 0xc2, 0x30, 0xe4, 0x78, 0x3c, 0x72, 0x38, 0x1c, 0xf8, 0xf9, 0xe7, 0x9f, 0x01, 0x58, 0xad, 0x56, 0x34, 0x4d, 0x83, 0x24, 0x49, 0x04, 0x41, 0x80, 0x6d, 0xdb, 0x78, 0x9e, 0x87, 0x10, 0x82, 0x7f, 0xfe, 0xf9, 0x87, 0x30, 0x0c, 0x99, 0x4e, 0xa7, 0x5c, 0x5f, 0x5f, 0x23, 0x84, 0xc0, 0xf3, 0x3c, 0x5e, 0x5e, 0x5e, 0x08, 0xc3, 0x90, 0x7e, 0xbf, 0x8f, 0x65, 0x59, 0x5c, 0x5d, 0x5d, 0x71, 0x7b, 0x7b, 0xcb, 0xdb, 0xdb, 0x1b, 0x9e, 0xe7, 0xb1, 0xdb, 0xed, 0x90, 0x9e, 0x9e, 0x9e, 0x5c, 0x45, 0x51, 0xd8, 0xef, 0xf7, 0x94, 0x65, 0x49, 0x51, 0x14, 0xf8, 0xbe, 0x4f, 0x59, 0x96, 0x08, 0x21, 0x38, 0x3d, 0x3d, 0xe5, 0xf9, 0xf9, 0x19, 0x21, 0x04, 0x79, 0x9e, 0xe3, 0xba, 0x2e, 0xba, 0xae, 0x93, 0xe7, 0x39, 0x42, 0x08, 0x24, 0x49, 0x42, 0x92, 0x24, 0x00, 0x0c, 0xc3, 0x40, 0x08, 0xc1, 0x62, 0xb1, 0x60, 0x36, 0x9b, 0xb1, 0x5a, 0xad, 0x98, 0x4e, 0xa7, 0x28, 0x8a, 0x42, 0x9a, 0xa6, 0xc4, 0x71, 0x8c, 0x24, 0x49, 0x54, 0x55, 0x85, 0xf2, 0xeb, 0xaf, 0xbf, 0x1a, 0x79, 0x9e, 0xa3, 0xaa, 0x2a, 0x71, 0x1c, 0x33, 0x99, 0x4c, 0x28, 0xcb, 0x92, 0x24, 0x49, 0x00, 0xda, 0x11, 0x9e, 0x9f, 0x9f, 0xb3, 0xdf, 0xef, 0xa9, 0xeb, 0x9a, 0xdd, 0x6e, 0x87, 0x65, 0x59, 0x5c, 0x5c, 0x5c, 0x20, 0x84, 0xc0, 0x34, 0x4d, 0xf6, 0xfb, 0x3d, 0x71, 0x1c, 0xd3, 0xe9, 0x74, 0x98, 0x4e, 0xa7, 0x54, 0x55, 0x85, 0x6d, 0xdb, 0xec, 0x76, 0x3b, 0x9e, 0x9f, 0x9f, 0xb1, 0x2c, 0x0b, 0x4d, 0xd3, 0x08, 0xc3, 0x10, 0xcf, 0xf3, 0x90, 0x3d, 0xcf, 0xe3, 0xf3, 0xe7, 0xcf, 0x34, 0x4d, 0xc3, 0xe5, 0xe5, 0x25, 0x65, 0x59, 0x12, 0x04, 0x01, 0x79, 0x9e, 0xb3, 0xdd, 0x6e, 0xd9, 0xef, 0xf7, 0x74, 0x3a, 0x1d, 0x9a, 0xa6, 0xe1, 0xfa, 0xfa, 0x9a, 0x34, 0x4d, 0xdb, 0x95, 0x7c, 0xfd, 0xfa, 0x95, 0x20, 0x08, 0xd8, 0xef, 0xf7, 0xec, 0xf7, 0x7b, 0x96, 0xcb, 0x25, 0x92, 0x24, 0xb1, 0xdf, 0xef, 0x91, 0x24, 0x89, 0x38, 0x8e, 0xc9, 0xf3, 0x9c, 0xc5, 0x62, 0x41, 0x14, 0x45, 0x94, 0x65, 0xc9, 0x2f, 0xbf, 0xfc, 0xf2, 0x6d, 0x52, 0xb7, 0xb7, 0xb7, 0xee, 0x6a, 0xb5, 0x42, 0xd3, 0x34, 0x4c, 0xd3, 0xe4, 0xfc, 0xfc, 0x9c, 0xbb, 0xbb, 0x3b, 0xc6, 0xe3, 0x31, 0x49, 0x92, 0xa0, 0x28, 0x0a, 0xbe, 0xef, 0x53, 0xd7, 0x35, 0x75, 0x5d, 0x13, 0x45, 0x11, 0xb2, 0x2c, 0x93, 0x24, 0x09, 0x3f, 0xfd, 0xf4, 0x13, 0x5f, 0xbf, 0x7e, 0xa5, 0xaa, 0x2a, 0x2c, 0xcb, 0x62, 0xb3, 0xd9, 0x60, 0x18, 0x06, 0xb6, 0x6d, 0x23, 0xcb, 0x32, 0xfd, 0x7e, 0x9f, 0xfb, 0xfb, 0x7b, 0x64, 0x59, 0xa6, 0xaa, 0x2a, 0x2e, 0x2f, 0x2f, 0xc9, 0xb2, 0x0c, 0xc3, 0x30, 0x90, 0x7e, 0xff, 0xfd, 0x77, 0x77, 0x30, 0x18, 0xd0, 0x34, 0x0d, 0x61, 0x18, 0xf2, 0xfa, 0xfa, 0xca, 0x0f, 0x3f, 0xfc, 0x80, 0xef, 0xfb, 0x44, 0x51, 0x84, 0x10, 0x82, 0xd5, 0x6a, 0x85, 0x65, 0x59, 0x28, 0x8a, 0xc2, 0x74, 0x3a, 0x25, 0x0c, 0x43, 0xaa, 0xaa, 0x22, 0x4d, 0x53, 0x96, 0xcb, 0x25, 0xb3, 0xd9, 0x0c, 0xcf, 0xf3, 0xd0, 0x34, 0x8d, 0x38, 0x8e, 0x89, 0xe3, 0xb8, 0x15, 0xe4, 0x64, 0x32, 0x41, 0x92, 0x24, 0x0e, 0x87, 0x03, 0x51, 0x14, 0x71, 0x38, 0x1c, 0x18, 0x0e, 0x87, 0xc8, 0xe3, 0xf1, 0x18, 0xc7, 0x71, 0xb0, 0x6d, 0x1b, 0x21, 0x04, 0x41, 0x10, 0x50, 0x55, 0x15, 0xb2, 0x2c, 0xd3, 0xe9, 0x74, 0x90, 0x24, 0x09, 0xd7, 0x75, 0x79, 0x79, 0x79, 0xe1, 0x70, 0x38, 0x50, 0x55, 0x15, 0x67, 0x67, 0x67, 0x8c, 0x46, 0x23, 0x34, 0x4d, 0x43, 0xd3, 0x34, 0x16, 0x8b, 0x05, 0xb6, 0x6d, 0xa3, 0x69, 0x1a, 0xa7, 0xa7, 0xa7, 0xc4, 0x71, 0xcc, 0xe7, 0xcf, 0x9f, 0x71, 0x5d, 0x17, 0x45, 0x51, 0x30, 0x4d, 0x93, 0xb3, 0xb3, 0x33, 0xc2, 0x30, 0xe4, 0xf1, 0xf1, 0x91, 0x38, 0x8e, 0x51, 0xcb, 0xb2, 0xc4, 0x30, 0x0c, 0x76, 0xbb, 0x1d, 0x59, 0x96, 0xb1, 0x5c, 0x2e, 0xf1, 0x7d, 0x1f, 0x59, 0x96, 0xdb, 0x53, 0xdb, 0xb6, 0xcd, 0x78, 0x3c, 0x46, 0x96, 0x65, 0xe2, 0x38, 0x26, 0x4d, 0x53, 0x8e, 0xc7, 0x23, 0x71, 0x1c, 0x7f, 0x13, 0x8a, 0x2c, 0xf3, 0xf8, 0xf8, 0x88, 0xeb, 0xba, 0x74, 0xbb, 0x5d, 0x54, 0x55, 0x65, 0x36, 0x9b, 0x21, 0x49, 0x12, 0xeb, 0xf5, 0x9a, 0xd1, 0x68, 0xc4, 0x76, 0xbb, 0x65, 0x30, 0x18, 0x60, 0x9a, 0x26, 0xfd, 0x7e, 0x1f, 0xe9, 0xbf, 0xff, 0xfe, 0x73, 0x5f, 0x5f, 0x5f, 0x71, 0x1c, 0xa7, 0x95, 0x7e, 0x14, 0x45, 0xa8, 0xaa, 0xca, 0x76, 0xbb, 0xa5, 0x69, 0x1a, 0x86, 0xc3, 0x21, 0x96, 0x65, 0x21, 0x84, 0xe0, 0xe9, 0xe9, 0x09, 0xdf, 0xf7, 0xd9, 0xed, 0x76, 0xd8, 0xb6, 0x8d, 0x69, 0x9a, 0xad, 0x5d, 0xb6, 0xdb, 0x2d, 0x42, 0x08, 0xce, 0xce, 0xce, 0xf0, 0x7d, 0x9f, 0x24, 0x49, 0x48, 0xd3, 0x94, 0x24, 0x49, 0x68, 0x9a, 0x86, 0xd9, 0x6c, 0x86, 0xe3, 0x38, 0x7c, 0xfa, 0xf4, 0x09, 0xd9, 0x34, 0x4d, 0x96, 0xcb, 0x25, 0xa6, 0x69, 0x12, 0xc7, 0x31, 0x9b, 0xcd, 0x06, 0x49, 0x92, 0x58, 0xad, 0x56, 0x54, 0x55, 0x85, 0x10, 0x82, 0xe3, 0xf1, 0xc8, 0xc9, 0xc9, 0x09, 0xbb, 0xdd, 0x0e, 0x4d, 0xd3, 0xd8, 0xed, 0x76, 0x38, 0x8e, 0xc3, 0xc9, 0xc9, 0x09, 0xd3, 0xe9, 0x94, 0xd3, 0xd3, 0x53, 0xca, 0xb2, 0xa4, 0x69, 0x1a, 0x54, 0x55, 0x45, 0x96, 0x65, 0x9a, 0xa6, 0xe1, 0x78, 0x3c, 0xf2, 0x4e, 0xc5, 0xf7, 0x43, 0x94, 0x65, 0xc9, 0x87, 0x0f, 0x1f, 0x50, 0x9f, 0x9f, 0x9f, 0x39, 0x3f, 0x3f, 0x27, 0xcf, 0x73, 0x82, 0x20, 0xa0, 0x69, 0x1a, 0x8a, 0xa2, 0x40, 0x96, 0x65, 0x84, 0x10, 0x14, 0x45, 0x81, 0xaa, 0xaa, 0xcc, 0xe7, 0x73, 0x82, 0x20, 0x60, 0xb1, 0x58, 0xb4, 0x74, 0xeb, 0x74, 0x3a, 0x44, 0x51, 0x44, 0x18, 0x86, 0xf8, 0xbe, 0x8f, 0x10, 0x02, 0xd7, 0x75, 0x29, 0x8a, 0x02, 0xdb, 0xb6, 0xb1, 0x2c, 0x8b, 0x3c, 0xcf, 0xf1, 0x7d, 0x9f, 0x7e, 0xbf, 0x4f, 0x51, 0x14, 0x0c, 0x06, 0x03, 0x1e, 0x1e, 0x1e, 0x90, 0x1e, 0x1f, 0x1f, 0xdd, 0x77, 0x3b, 0xac, 0xd7, 0xeb, 0xf6, 0xc6, 0x77, 0x11, 0x2d, 0x97, 0x4b, 0x92, 0x24, 0x41, 0xd7, 0x75, 0x8a, 0xa2, 0x20, 0x08, 0x02, 0x24, 0x49, 0x6a, 0xf9, 0xbc, 0x5e, 0xaf, 0xe9, 0x76, 0xbb, 0x48, 0x92, 0x84, 0xaa, 0xaa, 0x08, 0x21, 0x38, 0x1c, 0x0e, 0x28, 0x8a, 0xc2, 0xf1, 0x78, 0xc4, 0x30, 0x0c, 0x4c, 0xd3, 0xc4, 0x34, 0x4d, 0xbe, 0x7c, 0xf9, 0x42, 0x18, 0x86, 0x04, 0x41, 0x80, 0xdc, 0xe9, 0x74, 0x98, 0x4c, 0x26, 0x00, 0xec, 0x76, 0x3b, 0xfe, 0xfd, 0xf7, 0xdf, 0x16, 0x9b, 0x9f, 0x3e, 0x7d, 0xc2, 0x71, 0x1c, 0xea, 0xba, 0xe6, 0xe6, 0xe6, 0x06, 0xc3, 0x30, 0x5a, 0xae, 0x17, 0x45, 0x41, 0x51, 0x14, 0x64, 0x59, 0x86, 0xaa, 0xaa, 0x78, 0x9e, 0xc7, 0xf7, 0xdf, 0x7f, 0x8f, 0xe3, 0x38, 0xa8, 0xaa, 0xca, 0xeb, 0xeb, 0x2b, 0x79, 0x9e, 0xd3, 0x34, 0x0d, 0x83, 0xc1, 0xa0, 0xbd, 0xb6, 0xd7, 0xeb, 0xe1, 0xba, 0x2e, 0xea, 0x6a, 0xb5, 0xa2, 0xae, 0x6b, 0xc2, 0x30, 0x44, 0x96, 0x65, 0x7e, 0xfc, 0xf1, 0x47, 0x84, 0x10, 0x34, 0x4d, 0xc3, 0x78, 0x3c, 0x26, 0xcf, 0x73, 0x00, 0x3e, 0x7e, 0xfc, 0x48, 0xd3, 0x34, 0x6d, 0xea, 0xa8, 0xaa, 0x8a, 0xa2, 0x28, 0xed, 0x2a, 0xb6, 0xdb, 0x2d, 0x69, 0x9a, 0xa2, 0x28, 0x0a, 0x59, 0x96, 0x61, 0xdb, 0x76, 0xfb, 0x92, 0x77, 0xac, 0x76, 0xbb, 0x5d, 0x3c, 0xcf, 0x23, 0x49, 0x12, 0xa4, 0xbf, 0xff, 0xfe, 0xdb, 0xcd, 0xb2, 0x8c, 0xa2, 0x28, 0x98, 0x4e, 0xa7, 0x74, 0x3a, 0x1d, 0xee, 0xee, 0xee, 0x5a, 0x4c, 0xda, 0xb6, 0xdd, 0xda, 0xca, 0x30, 0x0c, 0x2c, 0xcb, 0xfa, 0x7f, 0x96, 0x7b, 0x8f, 0xc6, 0xdd, 0x6e, 0x87, 0xaa, 0xaa, 0x74, 0x3a, 0x1d, 0x7c, 0xdf, 0x47, 0x55, 0x55, 0xee, 0xef, 0xef, 0xf1, 0x7d, 0x9f, 0x38, 0x8e, 0xa9, 0xaa, 0x8a, 0xc9, 0x64, 0x42, 0x92, 0x24, 0x98, 0xa6, 0xf9, 0x4d, 0xd5, 0x79, 0x9e, 0x33, 0x1c, 0x0e, 0x51, 0x55, 0x15, 0x55, 0x55, 0xf9, 0xf8, 0xf1, 0x23, 0xba, 0xae, 0xf3, 0xf4, 0xf4, 0xc4, 0x7c, 0x3e, 0x67, 0xbd, 0x5e, 0x73, 0x7d, 0x7d, 0x4d, 0xd3, 0x34, 0xdc, 0xde, 0xde, 0xb2, 0x5a, 0xad, 0x78, 0x78, 0x78, 0xa0, 0x2c, 0x4b, 0x1c, 0xc7, 0x69, 0x61, 0xf2, 0xf2, 0xf2, 0x42, 0x51, 0x14, 0xe8, 0xba, 0x8e, 0xa2, 0x28, 0x4c, 0x26, 0x13, 0x1e, 0x1e, 0x1e, 0xd0, 0x75, 0x1d, 0xcf, 0xf3, 0xd0, 0x75, 0x9d, 0xb3, 0xb3, 0xb3, 0x6f, 0xa3, 0x6e, 0x9a, 0x86, 0x6e, 0xb7, 0x8b, 0x10, 0x82, 0xba, 0xae, 0x79, 0x79, 0x79, 0xc1, 0x34, 0x4d, 0xc2, 0x30, 0xa4, 0xd7, 0xeb, 0x31, 0x9b, 0xcd, 0xd8, 0xed, 0x76, 0x2c, 0x16, 0x0b, 0xc2, 0x30, 0x64, 0x30, 0x18, 0x50, 0x96, 0x25, 0xba, 0xae, 0x93, 0x65, 0x19, 0x59, 0x96, 0x11, 0x86, 0x21, 0x4d, 0xd3, 0xd0, 0xeb, 0xf5, 0x50, 0x55, 0x95, 0xe3, 0xf1, 0x88, 0x24, 0x49, 0x44, 0x51, 0xc4, 0x70, 0x38, 0x44, 0x51, 0x94, 0x96, 0xe7, 0x4d, 0xd3, 0x00, 0x20, 0xfd, 0xf5, 0xd7, 0x5f, 0xee, 0x74, 0x3a, 0x25, 0x8e, 0x63, 0xc2, 0x30, 0x04, 0x40, 0x51, 0x14, 0x46, 0xa3, 0x11, 0x00, 0x49, 0x92, 0xf0, 0xf2, 0xf2, 0x42, 0x5d, 0xd7, 0xf4, 0xfb, 0x7d, 0x34, 0x4d, 0x23, 0x08, 0x02, 0x96, 0xcb, 0x25, 0x4d, 0xd3, 0xf0, 0xfc, 0xfc, 0xcc, 0x70, 0x38, 0xe4, 0xf4, 0xf4, 0x14, 0xc3, 0x30, 0x78, 0x7b, 0x7b, 0x43, 0x51, 0x14, 0xea, 0xba, 0xa6, 0xaa, 0x2a, 0x1c, 0xc7, 0xc1, 0xb2, 0xac, 0x96, 0x62, 0x0f, 0x0f, 0x0f, 0x5c, 0x5d, 0x5d, 0x21, 0xcb, 0xb2, 0x4c, 0x10, 0x04, 0x6d, 0x88, 0x0b, 0x21, 0x50, 0x55, 0x95, 0x34, 0x4d, 0xe9, 0x74, 0x3a, 0x98, 0xa6, 0xc9, 0xe9, 0xe9, 0x29, 0x69, 0x9a, 0x52, 0x14, 0x45, 0x8b, 0xc8, 0xd1, 0x68, 0xd4, 0x7a, 0xb4, 0xdb, 0xed, 0x92, 0x24, 0x09, 0x42, 0x08, 0xc6, 0xe3, 0x31, 0x61, 0x18, 0xb6, 0x20, 0x12, 0x42, 0x90, 0x65, 0x19, 0xae, 0xeb, 0x52, 0x96, 0x25, 0xb6, 0x6d, 0x63, 0xdb, 0x36, 0xd2, 0xcd, 0xcd, 0x8d, 0x3b, 0x1c, 0x0e, 0x29, 0xcb, 0x92, 0x3c, 0xcf, 0x09, 0xc3, 0x90, 0xc3, 0xe1, 0xc0, 0xe5, 0xe5, 0x25, 0x9b, 0xcd, 0xa6, 0x8d, 0x3b, 0xd3, 0x34, 0x71, 0x1c, 0x87, 0xa2, 0x28, 0x38, 0x39, 0x39, 0x69, 0xb3, 0x56, 0xd3, 0x34, 0x3c, 0xcf, 0xa3, 0xae, 0xeb, 0xf6, 0x19, 0x86, 0x61, 0x10, 0x45, 0x11, 0x00, 0x67, 0x67, 0x67, 0x28, 0x8a, 0xc2, 0x66, 0xb3, 0x41, 0xd3, 0xb4, 0x96, 0x07, 0xd2, 0x9f, 0x7f, 0xfe, 0xe9, 0xca, 0xb2, 0xdc, 0x1a, 0xfe, 0xc3, 0x87, 0x0f, 0x14, 0x45, 0xc1, 0xed, 0xed, 0x2d, 0x41, 0x10, 0xa0, 0x69, 0x5a, 0x7b, 0xaa, 0xc7, 0xc7, 0x47, 0x74, 0x5d, 0x6f, 0xad, 0xe7, 0x79, 0x1e, 0x96, 0x65, 0xb5, 0xc1, 0xbf, 0x5a, 0xad, 0xf8, 0xee, 0xbb, 0xef, 0x58, 0x2c, 0x16, 0x8c, 0x46, 0x23, 0x84, 0x10, 0xec, 0xf7, 0x7b, 0xb6, 0xdb, 0x2d, 0x96, 0x65, 0x31, 0x1a, 0x8d, 0x5a, 0x22, 0xca, 0xbb, 0xdd, 0xae, 0x1d, 0xc1, 0x6c, 0x36, 0x23, 0x4d, 0xd3, 0x16, 0x8d, 0x59, 0x96, 0xb5, 0xde, 0x9c, 0xcf, 0xe7, 0x98, 0xa6, 0xc9, 0x62, 0xb1, 0x40, 0x92, 0x24, 0x3c, 0xcf, 0xe3, 0x70, 0x38, 0x70, 0x71, 0x71, 0x81, 0xa2, 0x28, 0x6d, 0x5b, 0x59, 0x2e, 0x97, 0x4c, 0xa7, 0x53, 0x8a, 0xa2, 0x40, 0x08, 0xc1, 0xeb, 0xeb, 0x2b, 0xf3, 0xf9, 0xbc, 0x15, 0x9b, 0xeb, 0xba, 0x44, 0x51, 0x84, 0x74, 0x77, 0x77, 0xe7, 0xbe, 0xc7, 0x9b, 0xef, 0xfb, 0xbc, 0x7b, 0xba, 0xae, 0x6b, 0x0e, 0x87, 0x03, 0x96, 0x65, 0xb5, 0xd5, 0xd7, 0xf7, 0x7d, 0xd6, 0xeb, 0x35, 0x75, 0x5d, 0xd3, 0xed, 0x76, 0x51, 0x14, 0x85, 0xd5, 0x6a, 0x45, 0xaf, 0xd7, 0xa3, 0x2c, 0x4b, 0x16, 0x8b, 0x05, 0x83, 0xc1, 0x00, 0x21, 0x04, 0xdd, 0x6e, 0x97, 0xa2, 0x28, 0x5a, 0xd8, 0xa8, 0xaa, 0x8a, 0x6d, 0xdb, 0x38, 0x8e, 0xc3, 0x7a, 0xbd, 0x46, 0xba, 0xbf, 0xbf, 0x77, 0xb3, 0x2c, 0xa3, 0xd3, 0xe9, 0x30, 0x9f, 0xcf, 0xa9, 0xaa, 0x8a, 0x7e, 0xbf, 0x8f, 0xae, 0xeb, 0xe8, 0xba, 0x4e, 0x5d, 0xd7, 0x6c, 0xb7, 0x5b, 0x1c, 0xc7, 0x01, 0xc0, 0x75, 0x5d, 0x92, 0x24, 0xa1, 0x28, 0x0a, 0x9a, 0xa6, 0x69, 0x6d, 0x35, 0x99, 0x4c, 0x30, 0x0c, 0x83, 0xf9, 0x7c, 0x8e, 0xeb, 0xba, 0xe4, 0x79, 0x4e, 0x59, 0x96, 0xcc, 0x66, 0x33, 0x2c, 0xcb, 0xe2, 0xed, 0xed, 0x8d, 0xfd, 0x7e, 0x8f, 0x6d, 0xdb, 0x00, 0xc8, 0xaf, 0xaf, 0xaf, 0x5c, 0x5f, 0x5f, 0xe3, 0xfb, 0x3e, 0x86, 0x61, 0xd0, 0xe9, 0x74, 0x58, 0xad, 0x56, 0x2d, 0xdc, 0x93, 0x24, 0xe1, 0xed, 0xed, 0xad, 0x2d, 0x78, 0xbe, 0xef, 0x73, 0x7d, 0x7d, 0x4d, 0xaf, 0xd7, 0x03, 0x20, 0xcf, 0x73, 0xea, 0xba, 0xc6, 0x71, 0x1c, 0x0c, 0xc3, 0x60, 0x3a, 0x9d, 0x92, 0xa6, 0x29, 0x9b, 0xcd, 0x06, 0x59, 0x96, 0xc9, 0xb2, 0xac, 0x15, 0x95, 0xae, 0xeb, 0x44, 0x51, 0xf4, 0x8d, 0xef, 0x97, 0x97, 0x97, 0xed, 0x3e, 0x8f, 0xc7, 0x23, 0x42, 0x08, 0xce, 0xcf, 0xcf, 0x5b, 0xb1, 0x05, 0x41, 0x80, 0xe7, 0x79, 0x2c, 0x97, 0x4b, 0xf6, 0xfb, 0x3d, 0x59, 0x96, 0xb5, 0xd6, 0x89, 0xe3, 0x18, 0xd7, 0x75, 0x09, 0x82, 0x80, 0x28, 0x8a, 0xda, 0xbe, 0x9d, 0xa6, 0x29, 0xef, 0x4e, 0xd9, 0x6c, 0x36, 0xa8, 0xaa, 0xda, 0xb6, 0xd6, 0x77, 0xaa, 0x49, 0x7f, 0xfc, 0xf1, 0x87, 0x1b, 0x86, 0x21, 0x9d, 0x4e, 0x07, 0x45, 0x51, 0xd0, 0x75, 0x9d, 0x7e, 0xbf, 0xcf, 0x97, 0x2f, 0x5f, 0xda, 0x93, 0xe8, 0xba, 0xde, 0x96, 0xbd, 0x2c, 0xcb, 0x58, 0xad, 0x56, 0x38, 0x8e, 0xd3, 0x16, 0xbc, 0x3c, 0xcf, 0xc9, 0xf3, 0x1c, 0xd3, 0x34, 0x91, 0x24, 0x89, 0x5e, 0xaf, 0x87, 0x69, 0x9a, 0x44, 0x51, 0xd4, 0x36, 0x55, 0x21, 0x04, 0xfd, 0x7e, 0x9f, 0x2c, 0xcb, 0x58, 0xaf, 0xd7, 0xc8, 0xef, 0xb5, 0xd6, 0x75, 0x5d, 0x66, 0xb3, 0x19, 0x57, 0x57, 0x57, 0x74, 0x3a, 0x1d, 0x6c, 0xdb, 0x6e, 0x5b, 0xe4, 0x64, 0x32, 0xa1, 0xd7, 0xeb, 0xe1, 0x38, 0x0e, 0xcb, 0xe5, 0x12, 0xcb, 0xb2, 0x50, 0x55, 0xb5, 0xb5, 0x47, 0x10, 0x04, 0xc8, 0xb2, 0xdc, 0x7e, 0xc0, 0xfb, 0x7e, 0xdf, 0x83, 0x24, 0x8e, 0xe3, 0x36, 0x4a, 0x83, 0x20, 0x60, 0x32, 0x99, 0xa0, 0xfc, 0xf6, 0xdb, 0x6f, 0xc6, 0xfb, 0x57, 0x79, 0x9e, 0x47, 0x18, 0x86, 0x94, 0x65, 0x89, 0x24, 0x49, 0xed, 0x58, 0xde, 0xbd, 0x97, 0xa6, 0x69, 0x9b, 0xad, 0x9a, 0xa6, 0x7d, 0xfb, 0x15, 0xf9, 0x3f, 0x2b, 0x99, 0xa6, 0xc9, 0xf1, 0x78, 0xc4, 0xf3, 0x3c, 0xaa, 0xaa, 0x22, 0x8a, 0x22, 0xa2, 0x28, 0x6a, 0xbb, 0xd7, 0x6a, 0xb5, 0x6a, 0x7b, 0x76, 0x9e, 0xe7, 0xfc, 0x0f, 0xef, 0xbb, 0x4f, 0xb3, 0xe6, 0x79, 0x1d, 0xd6, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82, }; static const int bg_stripe_png_len = 2365; static const unsigned char pic32mz_jpg[] = { 0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10, 0x4a, 0x46, 0x49, 0x46, 0x00, 0x01, 0x01, 0x01, 0x00, 0x48, 0x00, 0x48, 0x00, 0x00, 0xff, 0xfe, 0x00, 0x13, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68, 0x20, 0x47, 0x49, 0x4d, 0x50, 0xff, 0xdb, 0x00, 0x43, 0x00, 0x03, 0x02, 0x02, 0x03, 0x02, 0x02, 0x03, 0x03, 0x03, 0x03, 0x04, 0x03, 0x03, 0x04, 0x05, 0x08, 0x05, 0x05, 0x04, 0x04, 0x05, 0x0a, 0x07, 0x07, 0x06, 0x08, 0x0c, 0x0a, 0x0c, 0x0c, 0x0b, 0x0a, 0x0b, 0x0b, 0x0d, 0x0e, 0x12, 0x10, 0x0d, 0x0e, 0x11, 0x0e, 0x0b, 0x0b, 0x10, 0x16, 0x10, 0x11, 0x13, 0x14, 0x15, 0x15, 0x15, 0x0c, 0x0f, 0x17, 0x18, 0x16, 0x14, 0x18, 0x12, 0x14, 0x15, 0x14, 0xff, 0xdb, 0x00, 0x43, 0x01, 0x03, 0x04, 0x04, 0x05, 0x04, 0x05, 0x09, 0x05, 0x05, 0x09, 0x14, 0x0d, 0x0b, 0x0d, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0xff, 0xc2, 0x00, 0x11, 0x08, 0x00, 0x6e, 0x00, 0x96, 0x03, 0x01, 0x11, 0x00, 0x02, 0x11, 0x01, 0x03, 0x11, 0x01, 0xff, 0xc4, 0x00, 0x1c, 0x00, 0x00, 0x02, 0x02, 0x03, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x05, 0x06, 0x07, 0x02, 0x03, 0x08, 0x01, 0x00, 0xff, 0xc4, 0x00, 0x19, 0x01, 0x00, 0x03, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x00, 0x04, 0x05, 0xff, 0xda, 0x00, 0x0c, 0x03, 0x01, 0x00, 0x02, 0x10, 0x03, 0x10, 0x00, 0x00, 0x01, 0xe9, 0xf5, 0x35, 0x3f, 0x17, 0x99, 0x10, 0x6f, 0x29, 0x6b, 0xc8, 0x91, 0xd1, 0x96, 0xb6, 0x06, 0x4c, 0xa5, 0xd2, 0x25, 0xfd, 0x33, 0x4b, 0x6a, 0xcd, 0x88, 0x4d, 0x87, 0x08, 0x13, 0xdc, 0x71, 0xd8, 0xd2, 0xca, 0x29, 0x7b, 0x54, 0x2a, 0xf9, 0xd2, 0xac, 0xc4, 0x53, 0x8b, 0x53, 0xf0, 0x6f, 0x06, 0x5a, 0x78, 0x17, 0x27, 0x0d, 0x63, 0x7e, 0xb9, 0x3e, 0x5c, 0x88, 0x05, 0x43, 0x4d, 0x53, 0x00, 0xb0, 0x0e, 0xaa, 0x97, 0x89, 0x5b, 0xd8, 0x87, 0xf4, 0xfa, 0x09, 0x10, 0x63, 0x58, 0x49, 0x3a, 0x36, 0x31, 0x18, 0xa4, 0x6c, 0x00, 0x5a, 0x79, 0xf6, 0xcf, 0xce, 0xa9, 0xfa, 0x3a, 0x1e, 0xe7, 0x31, 0x91, 0x32, 0x79, 0xd2, 0x71, 0xd5, 0x2b, 0xd5, 0x7a, 0x5a, 0x18, 0x63, 0x5f, 0xe1, 0x9b, 0xfa, 0x5d, 0x13, 0x34, 0x1a, 0x96, 0x8b, 0x62, 0x20, 0x06, 0xc9, 0xfd, 0x53, 0x8e, 0x00, 0x68, 0xb1, 0x4f, 0x3a, 0xad, 0xe8, 0x67, 0x81, 0xe4, 0xc1, 0x11, 0xac, 0x57, 0x1a, 0xed, 0x33, 0x95, 0xa5, 0xb1, 0x3d, 0x11, 0xa6, 0x8a, 0x0a, 0x76, 0x74, 0x12, 0x23, 0xe4, 0xb5, 0x34, 0x4e, 0xda, 0x6d, 0xfb, 0x66, 0xad, 0xe2, 0x81, 0x97, 0x99, 0xaa, 0x70, 0xd6, 0xd4, 0x3b, 0x9c, 0x19, 0x95, 0xfa, 0x54, 0xd6, 0x68, 0x1e, 0x95, 0x89, 0x3b, 0x84, 0x9e, 0x82, 0xd7, 0xe1, 0x80, 0x74, 0x74, 0xf4, 0x52, 0x23, 0x33, 0x58, 0x5c, 0xd6, 0x10, 0xf1, 0x54, 0xca, 0x78, 0x62, 0x40, 0xde, 0x39, 0xd8, 0x4b, 0x96, 0x12, 0xd7, 0xde, 0xfd, 0x72, 0x72, 0xe4, 0x8d, 0xbf, 0x18, 0x93, 0x70, 0xbc, 0x9a, 0x06, 0xd7, 0x8e, 0x09, 0x0f, 0x5f, 0x4f, 0xa0, 0x52, 0x7d, 0x01, 0x76, 0xa6, 0x39, 0xf9, 0xea, 0xf4, 0xe7, 0x8f, 0xec, 0xc5, 0x8c, 0x75, 0x37, 0xa4, 0x96, 0x66, 0x94, 0xe2, 0xe9, 0xe9, 0x14, 0xe6, 0x69, 0xb5, 0x66, 0x0d, 0x87, 0x2e, 0x27, 0x09, 0x65, 0xa9, 0xd8, 0x8e, 0xbe, 0x65, 0x7f, 0x6e, 0xde, 0x88, 0x9a, 0x74, 0x2d, 0xda, 0x20, 0x84, 0x35, 0xdc, 0xca, 0x25, 0x67, 0x65, 0x89, 0x22, 0xc6, 0x1a, 0x71, 0xf7, 0xe3, 0x35, 0x52, 0x4a, 0xde, 0xd9, 0x4c, 0x7e, 0xcc, 0x91, 0x6a, 0x4a, 0x78, 0x98, 0x4f, 0x3c, 0x5e, 0xc8, 0x8d, 0x38, 0xa3, 0xb6, 0xf5, 0x7a, 0x16, 0x69, 0xd0, 0x97, 0x6a, 0x86, 0x5a, 0x1e, 0xa6, 0xbd, 0xa9, 0x89, 0xa7, 0x24, 0xaa, 0x6c, 0xc9, 0xe6, 0xa0, 0x82, 0x0f, 0x23, 0x0d, 0xeb, 0x6e, 0x66, 0xd6, 0x1a, 0x0a, 0xbd, 0x52, 0x94, 0xf0, 0x75, 0x65, 0x6f, 0x3e, 0xd5, 0x14, 0xe6, 0x81, 0xdb, 0xbf, 0xa3, 0x64, 0xbd, 0x07, 0x76, 0xe7, 0x48, 0xad, 0x4e, 0x81, 0xbb, 0x3a, 0x35, 0x91, 0x2d, 0x03, 0xce, 0x64, 0x06, 0xd3, 0x25, 0x5b, 0xab, 0x33, 0x7c, 0x76, 0xf0, 0x6c, 0xd7, 0xcf, 0x90, 0x6e, 0xb5, 0xb1, 0xea, 0x11, 0xb8, 0x6b, 0xee, 0x9e, 0xbe, 0x8c, 0x54, 0xbf, 0x6a, 0xdc, 0xad, 0x17, 0x80, 0xe6, 0x8e, 0xb8, 0x31, 0x27, 0x2d, 0x9c, 0x34, 0x57, 0x83, 0x25, 0x0f, 0x96, 0xd2, 0x12, 0xc8, 0xb4, 0xc9, 0x2d, 0xe2, 0xe8, 0x99, 0xe7, 0x03, 0x29, 0x7a, 0xfa, 0xe6, 0x62, 0x3d, 0x3e, 0x9f, 0x49, 0x2a, 0xdf, 0x74, 0x6e, 0x43, 0x46, 0x80, 0xe6, 0xf7, 0x10, 0x96, 0x12, 0xf5, 0xe5, 0x68, 0xdc, 0x8d, 0xe7, 0xe8, 0x30, 0x69, 0x10, 0xef, 0x01, 0x1c, 0x80, 0xa7, 0x31, 0x39, 0xe4, 0x0d, 0xda, 0x84, 0x49, 0xf4, 0xde, 0xb7, 0xaa, 0x78, 0xfe, 0x9f, 0x45, 0x05, 0xbd, 0xaa, 0x79, 0x92, 0x34, 0x86, 0x02, 0x11, 0x00, 0x89, 0xb8, 0x1c, 0x8c, 0xf2, 0xb0, 0xe7, 0xe8, 0xf9, 0x76, 0x8e, 0x99, 0xab, 0x4f, 0x41, 0xa3, 0xf9, 0x68, 0xc7, 0x21, 0x55, 0xf5, 0x55, 0x67, 0xc6, 0x5e, 0x7a, 0x97, 0x98, 0x15, 0xf5, 0x7a, 0x39, 0x16, 0xf6, 0xa9, 0xab, 0xa6, 0xb5, 0xda, 0x06, 0x47, 0x0c, 0x17, 0xd3, 0x88, 0xc3, 0x66, 0xdb, 0xdb, 0x2e, 0x1b, 0x6a, 0xf5, 0x30, 0x6e, 0x70, 0x74, 0xf6, 0xe7, 0xf3, 0x1c, 0xd5, 0x7e, 0x25, 0x2d, 0x2d, 0x69, 0x01, 0xff, 0xc4, 0x00, 0x29, 0x10, 0x00, 0x02, 0x02, 0x01, 0x03, 0x04, 0x01, 0x04, 0x02, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x04, 0x01, 0x02, 0x05, 0x00, 0x06, 0x13, 0x07, 0x11, 0x12, 0x15, 0x14, 0x16, 0x17, 0x21, 0x22, 0x10, 0x32, 0x24, 0x33, 0x34, 0xff, 0xda, 0x00, 0x08, 0x01, 0x01, 0x00, 0x01, 0x05, 0x02, 0x33, 0x03, 0x0c, 0x64, 0xb2, 0x19, 0x4e, 0x77, 0xb7, 0x1e, 0x6d, 0x1d, 0x07, 0x78, 0x65, 0xcf, 0xaf, 0xa9, 0xb3, 0x7d, 0xfe, 0xa0, 0xcf, 0x4e, 0xa9, 0xb9, 0x33, 0x64, 0xd1, 0x37, 0x7b, 0xf8, 0x64, 0xc3, 0xd5, 0x46, 0x98, 0x25, 0x3a, 0x96, 0xcd, 0x97, 0xfb, 0xa0, 0xc6, 0x89, 0xd5, 0x06, 0x47, 0x01, 0xea, 0x5b, 0xec, 0x52, 0x3a, 0xac, 0xc6, 0xbe, 0xea, 0xb5, 0xaf, 0xba, 0xad, 0x68, 0x3d, 0x4e, 0x31, 0x42, 0xd7, 0x54, 0xb2, 0x14, 0xb6, 0xd1, 0xdd, 0x24, 0xdc, 0x43, 0x32, 0x99, 0x27, 0x35, 0xed, 0x5f, 0x2e, 0x42, 0x73, 0x0d, 0x96, 0xdf, 0x28, 0xfd, 0xea, 0xcb, 0x1c, 0x84, 0x64, 0xfc, 0x2e, 0xbf, 0x60, 0x21, 0x99, 0x34, 0xb1, 0xb7, 0xa9, 0x69, 0xad, 0x96, 0x03, 0x2d, 0x2c, 0xe2, 0x37, 0x4b, 0x4d, 0xc5, 0x49, 0x75, 0x88, 0xa0, 0x94, 0xda, 0xc0, 0x5f, 0xda, 0x65, 0x32, 0x26, 0xba, 0x94, 0xf0, 0xf1, 0x3f, 0x85, 0x74, 0xef, 0x97, 0x97, 0x4d, 0xbc, 0xbb, 0x64, 0x4e, 0x71, 0xb3, 0x29, 0x86, 0x2f, 0x21, 0xa8, 0xa2, 0x2b, 0x1e, 0x74, 0xed, 0x26, 0xb4, 0xf7, 0x03, 0xd4, 0xa5, 0x95, 0xcb, 0x50, 0x7e, 0x87, 0xe4, 0xc2, 0xd7, 0x4c, 0xe5, 0x90, 0x12, 0xc7, 0x1e, 0xa8, 0x4a, 0xcd, 0x71, 0x08, 0xac, 0xec, 0x29, 0x88, 0x02, 0x4f, 0xe6, 0xa6, 0xcf, 0x27, 0x38, 0x24, 0x87, 0x43, 0x4f, 0x94, 0x3b, 0xc7, 0xcb, 0xd3, 0x5e, 0xdc, 0x79, 0xe9, 0x8f, 0x6b, 0x7d, 0x5b, 0x53, 0xfa, 0xda, 0x3f, 0x42, 0x5a, 0xdd, 0xc2, 0xc7, 0x8f, 0xc3, 0xca, 0xc7, 0x26, 0x1a, 0xe8, 0xaf, 0x4b, 0x41, 0x16, 0x15, 0x42, 0xca, 0x7c, 0x06, 0xc7, 0x2c, 0x4b, 0x7c, 0x54, 0xf5, 0x02, 0x02, 0xc7, 0x8c, 0x2c, 0xd8, 0xce, 0x62, 0x15, 0x30, 0xb2, 0xd8, 0xaa, 0xa4, 0xa3, 0xde, 0x7a, 0xe9, 0xac, 0xcf, 0x67, 0xb1, 0xf8, 0xb2, 0x04, 0xad, 0x56, 0xae, 0xd6, 0xf5, 0x21, 0x7f, 0x89, 0x9f, 0xd5, 0x9f, 0xf8, 0x2e, 0x5b, 0x53, 0x09, 0x92, 0xa4, 0x43, 0x40, 0xcb, 0xbb, 0x52, 0x7b, 0x27, 0x85, 0x68, 0xb8, 0x14, 0x95, 0xcb, 0xde, 0x44, 0xf1, 0x92, 0x61, 0x5c, 0xbd, 0xef, 0x91, 0x35, 0xe9, 0x08, 0x18, 0x2a, 0x5e, 0x8f, 0x45, 0x39, 0x3a, 0x65, 0xfe, 0xbc, 0xce, 0x1c, 0xf4, 0x66, 0xc3, 0x81, 0x69, 0xdc, 0x94, 0x04, 0xe2, 0xcd, 0x1a, 0x66, 0x72, 0x06, 0xd0, 0xdb, 0x3d, 0xac, 0x5b, 0xd9, 0xc1, 0xae, 0x5e, 0xf8, 0x46, 0x4d, 0xf2, 0xa9, 0x8d, 0x66, 0x88, 0x4d, 0x33, 0xaa, 0x4e, 0xbd, 0xea, 0x93, 0x17, 0xdc, 0x8b, 0xda, 0xc4, 0x9e, 0xc0, 0x76, 0x05, 0x72, 0xbd, 0x2d, 0x5c, 0x45, 0x54, 0xa3, 0x55, 0xea, 0x5e, 0x6b, 0xd3, 0x48, 0xed, 0x5b, 0xd2, 0x2d, 0x19, 0x85, 0xc8, 0x43, 0xbf, 0x8a, 0x79, 0x72, 0xe5, 0x2f, 0x38, 0xeb, 0xcd, 0x72, 0x55, 0xad, 0x73, 0x8d, 0xf8, 0x63, 0xf7, 0x13, 0x0d, 0xc5, 0x99, 0x33, 0x98, 0x80, 0x0e, 0xc3, 0x1e, 0x58, 0x73, 0x56, 0xb0, 0x36, 0xa0, 0xf2, 0x5b, 0x93, 0xe6, 0x4a, 0xdd, 0xbf, 0x2b, 0x84, 0x65, 0xac, 0x89, 0x6b, 0x35, 0x7b, 0x8f, 0xd7, 0x65, 0x3b, 0xb7, 0x8d, 0x7f, 0xc3, 0x93, 0xa6, 0x5d, 0xa2, 0x97, 0xfe, 0xab, 0xfe, 0x47, 0x93, 0xb7, 0x82, 0x58, 0xfb, 0x05, 0xb7, 0xbd, 0xf2, 0xe5, 0xbe, 0x73, 0x0a, 0x0c, 0x51, 0x87, 0x8e, 0x02, 0x78, 0xfb, 0x01, 0x98, 0x80, 0xda, 0x60, 0xae, 0xc0, 0x97, 0xcc, 0x12, 0xe8, 0x4c, 0x9d, 0x85, 0x4d, 0x56, 0x2e, 0x9c, 0xa8, 0xf4, 0xc8, 0xf1, 0xeb, 0x39, 0xc0, 0xdc, 0xb4, 0x63, 0x08, 0xf9, 0x46, 0x58, 0x0e, 0x42, 0x2f, 0xe5, 0xd3, 0x48, 0xed, 0x5b, 0x7f, 0x57, 0x73, 0x25, 0xc7, 0x99, 0xcd, 0xec, 0x3a, 0x69, 0xb4, 0x45, 0x8e, 0x31, 0x85, 0x14, 0xd2, 0x2d, 0x11, 0xf1, 0xbf, 0xc0, 0xbb, 0x0a, 0x29, 0x36, 0x3b, 0x6a, 0x70, 0xcb, 0x46, 0x1a, 0x59, 0xe4, 0x37, 0x55, 0x81, 0x19, 0x1c, 0xba, 0xe4, 0xd5, 0xaf, 0x33, 0xa7, 0x22, 0xd0, 0x8e, 0x19, 0x2f, 0x90, 0xc5, 0x52, 0xa9, 0x98, 0xca, 0xe3, 0xc2, 0xa0, 0xdf, 0xf0, 0xe4, 0xe9, 0xa4, 0x47, 0x1e, 0xb7, 0xeb, 0xab, 0x59, 0xfb, 0xd7, 0x1f, 0x6d, 0x0d, 0xa4, 0x6b, 0x5c, 0x8c, 0x2e, 0xc0, 0x97, 0x13, 0x00, 0x5c, 0xb6, 0x29, 0x6a, 0xb2, 0x35, 0x4a, 0xb9, 0x2e, 0x50, 0xa7, 0x21, 0x2e, 0x64, 0xf5, 0xdb, 0xc4, 0xb4, 0xc6, 0xde, 0xbc, 0xc5, 0xf0, 0x17, 0x1d, 0x51, 0xc8, 0x45, 0x21, 0x57, 0xc0, 0xc1, 0x99, 0xb8, 0x44, 0xac, 0xd9, 0x31, 0xeb, 0x21, 0xe5, 0xe5, 0xd3, 0x6a, 0x76, 0x5e, 0x75, 0xba, 0xec, 0x8c, 0x6e, 0x3c, 0xc5, 0x93, 0x23, 0x53, 0xde, 0x67, 0x1d, 0xe1, 0xca, 0x9d, 0xe9, 0xe1, 0x51, 0xc0, 0x04, 0x7f, 0x8a, 0x06, 0xc7, 0x50, 0x31, 0x61, 0x6d, 0xf1, 0x9c, 0x32, 0x84, 0x8e, 0x7d, 0x3a, 0x97, 0xae, 0x0e, 0x96, 0xb5, 0x1c, 0x0f, 0x05, 0xc5, 0xfe, 0x15, 0xcb, 0x92, 0xab, 0xb6, 0xe6, 0x0a, 0xf0, 0xfc, 0x53, 0x9b, 0xa6, 0xdf, 0x84, 0x67, 0x5b, 0xd9, 0x13, 0xbf, 0xb8, 0x8f, 0x8b, 0x32, 0x44, 0x09, 0xaa, 0x0a, 0x0f, 0xb4, 0x0f, 0x04, 0xb4, 0x83, 0x54, 0x01, 0xea, 0x2b, 0xaf, 0xcc, 0x62, 0x5a, 0x0d, 0x8f, 0x03, 0xe3, 0xc6, 0x80, 0xc4, 0x67, 0x29, 0x35, 0xbf, 0x6b, 0xae, 0xcb, 0x00, 0x8c, 0x97, 0xca, 0x55, 0x45, 0xd2, 0x13, 0x57, 0xf4, 0xf4, 0x4d, 0x3a, 0xc4, 0xdc, 0xb9, 0x0a, 0xdf, 0xbf, 0x4e, 0x62, 0x7e, 0x1c, 0xeb, 0x74, 0xab, 0x92, 0xae, 0x71, 0xbc, 0x7e, 0x5b, 0x21, 0x7f, 0xa7, 0x1f, 0x99, 0x6f, 0x0c, 0xe2, 0x2b, 0xe2, 0x38, 0xa1, 0x51, 0xb2, 0x46, 0xa4, 0x35, 0xb5, 0x34, 0x7f, 0x02, 0xd3, 0xe2, 0xd6, 0xab, 0x05, 0x3b, 0x07, 0x4a, 0x63, 0x6b, 0x58, 0xab, 0x6c, 0x2b, 0x39, 0xcb, 0x45, 0x6c, 0x95, 0xab, 0x66, 0x32, 0xb2, 0x3e, 0x61, 0x02, 0xd6, 0xd3, 0xb1, 0x4e, 0x5e, 0x9c, 0xd7, 0xb2, 0x1a, 0xdc, 0xfb, 0x6c, 0x59, 0x4b, 0x7d, 0xbf, 0x57, 0x48, 0xed, 0x2f, 0x59, 0x69, 0xd9, 0x63, 0x92, 0x1b, 0x65, 0x50, 0xe5, 0x06, 0xcd, 0x85, 0x48, 0x3d, 0xaa, 0x41, 0xd7, 0xe9, 0x83, 0xea, 0xdb, 0x22, 0x97, 0xbc, 0x6c, 0xe8, 0xad, 0xc3, 0xb7, 0x4c, 0xbc, 0xd7, 0x66, 0xc5, 0x23, 0xe9, 0x0f, 0xd6, 0x36, 0x8f, 0x6d, 0x57, 0x68, 0xfe, 0x27, 0x67, 0x44, 0xc3, 0x1b, 0x1a, 0xb7, 0xd6, 0xd8, 0xc3, 0x7a, 0xc0, 0x7f, 0xff, 0xc4, 0x00, 0x32, 0x11, 0x00, 0x02, 0x01, 0x03, 0x02, 0x06, 0x00, 0x05, 0x02, 0x05, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x11, 0x12, 0x21, 0x31, 0x04, 0x10, 0x13, 0x22, 0x41, 0x51, 0x14, 0x20, 0x32, 0x61, 0x71, 0x05, 0xf0, 0x24, 0x33, 0x42, 0x43, 0x52, 0x63, 0x81, 0xa1, 0xb1, 0xf1, 0xff, 0xda, 0x00, 0x08, 0x01, 0x03, 0x01, 0x01, 0x3f, 0x01, 0xb5, 0xca, 0xb4, 0xf8, 0xb9, 0x4d, 0xf4, 0xf6, 0x38, 0x8a, 0xfc, 0x5f, 0x0f, 0x2c, 0x64, 0xca, 0x7c, 0x4f, 0x19, 0x59, 0xda, 0x05, 0xff, 0x00, 0x51, 0xbe, 0xdf, 0xf5, 0xf8, 0x3f, 0x8f, 0x7f, 0xb4, 0x5b, 0xf5, 0x13, 0x86, 0xa9, 0x5d, 0x4b, 0x0a, 0xdb, 0xff, 0x00, 0xe1, 0x9b, 0xf4, 0x27, 0x29, 0x6c, 0x77, 0xfa, 0x25, 0x37, 0x1f, 0x02, 0x94, 0x9f, 0x83, 0xa8, 0xce, 0xa7, 0xd8, 0xea, 0x0a, 0x7c, 0xbc, 0x99, 0x35, 0xa2, 0x2e, 0xfc, 0x8f, 0xee, 0x24, 0x97, 0x3e, 0x21, 0x2b, 0x2b, 0xff, 0x00, 0xc1, 0x05, 0x69, 0xdf, 0xf7, 0xe0, 0xbe, 0x97, 0x2f, 0x25, 0xf4, 0x92, 0x9c, 0xe2, 0xae, 0x29, 0xb9, 0x6a, 0xc5, 0x52, 0xc2, 0x69, 0xb1, 0xb7, 0xb0, 0xaa, 0x4a, 0xcc, 0x83, 0x6c, 0x5b, 0x1e, 0x59, 0xa3, 0x12, 0xb7, 0xcb, 0x51, 0x26, 0x7f, 0x71, 0xdb, 0xd1, 0x1b, 0x58, 0x8b, 0x8d, 0xca, 0xad, 0x36, 0x84, 0xa6, 0xa5, 0xdb, 0xb1, 0x0b, 0x39, 0x58, 0xc7, 0x54, 0x49, 0x65, 0x6d, 0x47, 0x49, 0x63, 0xab, 0x29, 0xac, 0x4f, 0x07, 0x96, 0x2f, 0x9a, 0x63, 0xfe, 0x6b, 0xfc, 0x1b, 0xe8, 0x68, 0x8b, 0xab, 0x09, 0x24, 0xf7, 0x12, 0x5e, 0xca, 0x90, 0x5b, 0x90, 0xa3, 0x96, 0x37, 0x2a, 0xd1, 0xc0, 0x51, 0xf2, 0x78, 0x3c, 0xb1, 0x5f, 0xe6, 0xad, 0x2b, 0x2d, 0xaf, 0xf8, 0x22, 0xef, 0x3b, 0xd8, 0x9e, 0x92, 0xb8, 0xe7, 0x21, 0xcd, 0xa1, 0xca, 0x11, 0xef, 0x15, 0x45, 0x26, 0x4a, 0x4e, 0x3a, 0x9c, 0x3d, 0x46, 0xdd, 0x99, 0xc4, 0xcd, 0x54, 0x77, 0x63, 0x51, 0x8c, 0xb4, 0x67, 0x83, 0xcb, 0x2f, 0xa1, 0x9c, 0x6e, 0xee, 0xc9, 0xd6, 0x49, 0xd9, 0x6a, 0x2e, 0x21, 0x79, 0x3a, 0xf1, 0x3e, 0x22, 0x25, 0x4a, 0xb1, 0xa9, 0xa1, 0x4a, 0x49, 0xd4, 0x6a, 0x3b, 0x15, 0x35, 0xb3, 0x23, 0x4d, 0x5b, 0x53, 0x08, 0x9d, 0x38, 0x7a, 0x30, 0x89, 0x37, 0x6e, 0xd9, 0x22, 0x3f, 0xe9, 0x96, 0x96, 0xd3, 0x1a, 0x77, 0xb8, 0xb6, 0x3f, 0xab, 0x94, 0xa8, 0xe6, 0xf7, 0x3e, 0x11, 0x27, 0xb9, 0x2e, 0x1a, 0x2b, 0xcb, 0xfd, 0xff, 0x00, 0xb1, 0xd1, 0x8f, 0xb6, 0x42, 0x94, 0x67, 0xa5, 0xc9, 0xf0, 0xf0, 0x87, 0x7a, 0x21, 0x4e, 0x30, 0x59, 0x41, 0x19, 0x68, 0x85, 0xf2, 0x54, 0xfa, 0xd5, 0xca, 0x16, 0xc8, 0xe2, 0xe0, 0xa1, 0x3c, 0x50, 0xd3, 0xd5, 0x72, 0xf2, 0xfe, 0x49, 0x2d, 0x4f, 0xb1, 0x8b, 0xa6, 0xf2, 0x45, 0x5a, 0x8d, 0xc4, 0x79, 0x28, 0xb4, 0xee, 0x27, 0xb5, 0x85, 0xb7, 0x24, 0x9b, 0x76, 0x44, 0xe8, 0x55, 0xa6, 0xb2, 0x9c, 0x5a, 0x5f, 0x83, 0x8a, 0x76, 0x65, 0x2a, 0xaa, 0x12, 0x3e, 0x21, 0xcf, 0xba, 0x02, 0xab, 0x29, 0xcb, 0x5f, 0x22, 0xd8, 0xf2, 0xf9, 0x79, 0xb1, 0x78, 0xad, 0xc6, 0x86, 0xe5, 0x95, 0x8b, 0xcf, 0x07, 0x0f, 0x65, 0x4e, 0xe9, 0x7d, 0x3b, 0x12, 0x9c, 0xdb, 0xb1, 0x35, 0x66, 0xa7, 0x72, 0x3b, 0x72, 0x8b, 0xc5, 0xe4, 0x56, 0xe2, 0xaa, 0x71, 0x0a, 0xd3, 0x38, 0x9d, 0xf4, 0x38, 0x6a, 0x4a, 0x6e, 0xd2, 0x2a, 0xf0, 0xea, 0x9b, 0x49, 0x2b, 0x18, 0x24, 0x2d, 0x8f, 0x2f, 0x93, 0xa7, 0x9d, 0xae, 0xc7, 0xc3, 0x46, 0x5a, 0xe4, 0x42, 0x86, 0x0d, 0xbc, 0x87, 0x4f, 0xa6, 0x9b, 0x52, 0x1d, 0x49, 0xc5, 0x67, 0x72, 0x53, 0xa8, 0xf6, 0x7f, 0x72, 0x7e, 0x99, 0x53, 0x48, 0xdc, 0xa5, 0x59, 0x49, 0x19, 0xc7, 0xd9, 0x9c, 0x7d, 0x99, 0xc5, 0x79, 0x3a, 0x8a, 0x72, 0xbf, 0x83, 0x87, 0x94, 0x5b, 0x38, 0xa9, 0xa9, 0xcf, 0x21, 0xf4, 0xf3, 0xed, 0x62, 0xd8, 0x7b, 0xbe, 0x4b, 0x9c, 0xfe, 0x93, 0x08, 0xda, 0xd7, 0x16, 0x11, 0x51, 0x6e, 0x3a, 0x6a, 0x76, 0xa9, 0x2f, 0x44, 0x94, 0x65, 0x23, 0xe1, 0xd6, 0x2c, 0x8d, 0x27, 0x96, 0xba, 0x9d, 0x28, 0xdc, 0xa5, 0x1f, 0x48, 0x94, 0x71, 0xee, 0x3b, 0xb2, 0xba, 0x66, 0x4e, 0xcf, 0x2d, 0x59, 0x45, 0xac, 0x90, 0xb6, 0x3c, 0xbf, 0x96, 0xaf, 0xd2, 0xca, 0x6f, 0x0f, 0x26, 0x13, 0x76, 0xbb, 0x14, 0x61, 0xfe, 0x03, 0xdb, 0x42, 0x2d, 0x5b, 0x1b, 0x15, 0x61, 0x51, 0xf6, 0x8a, 0xf2, 0x23, 0x29, 0x2d, 0x05, 0x4e, 0xac, 0xa2, 0x7c, 0x34, 0xf7, 0x15, 0x27, 0x83, 0x93, 0x23, 0xa4, 0x95, 0xc8, 0xde, 0xc7, 0x97, 0xc9, 0x1b, 0xf2, 0x9f, 0xd2, 0x26, 0x87, 0xdf, 0x65, 0x27, 0xa2, 0xfc, 0x14, 0xfa, 0xb6, 0xbc, 0x5a, 0x25, 0x42, 0x73, 0xf4, 0x53, 0xa6, 0xd4, 0xad, 0x73, 0x89, 0xe0, 0x1c, 0x52, 0xee, 0xcb, 0xdf, 0xd8, 0xe9, 0x6f, 0x1b, 0x0a, 0xa3, 0xbe, 0x8c, 0x86, 0xc4, 0xb6, 0x3b, 0x75, 0xd4, 0x8b, 0xd4, 0x5b, 0x1e, 0x79, 0x35, 0x73, 0x14, 0x63, 0xf7, 0x67, 0x4d, 0x3f, 0x2c, 0x74, 0xd3, 0xd4, 0x54, 0xa2, 0x8c, 0x22, 0x74, 0xe2, 0x74, 0xe2, 0xca, 0x95, 0x6a, 0x56, 0x49, 0x54, 0x95, 0xec, 0x28, 0xa4, 0x74, 0x21, 0xe8, 0x54, 0xd4, 0x76, 0x30, 0x3a, 0x51, 0x3a, 0x51, 0xe7, 0xff, 0xc4, 0x00, 0x2c, 0x11, 0x00, 0x02, 0x02, 0x00, 0x04, 0x04, 0x06, 0x02, 0x02, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x11, 0x10, 0x12, 0x21, 0x31, 0x13, 0x41, 0x51, 0x61, 0x03, 0x20, 0x32, 0x42, 0x62, 0xf0, 0x22, 0x52, 0x14, 0xb1, 0x30, 0x43, 0x81, 0xff, 0xda, 0x00, 0x08, 0x01, 0x02, 0x01, 0x01, 0x3f, 0x01, 0x72, 0x8a, 0xdd, 0x8e, 0x76, 0xdf, 0xe4, 0x45, 0xe6, 0x75, 0x98, 0xcb, 0x5e, 0xe3, 0x5f, 0xd8, 0xaf, 0x91, 0x5f, 0x22, 0xe4, 0xa5, 0xa3, 0xb3, 0x34, 0xcc, 0xd3, 0x33, 0x4c, 0xcd, 0x32, 0xe6, 0x66, 0x99, 0x9a, 0x66, 0x69, 0x19, 0xa4, 0x5b, 0x23, 0x26, 0xdd, 0x31, 0xc7, 0x99, 0x57, 0xb9, 0x92, 0x38, 0x3a, 0x16, 0xe5, 0xeb, 0x47, 0xfb, 0x17, 0xf8, 0x1c, 0x79, 0x8b, 0x08, 0xfa, 0x9f, 0xde, 0xa5, 0x15, 0x87, 0x21, 0xec, 0x73, 0x3d, 0xc2, 0xb5, 0xe2, 0x79, 0xb6, 0x47, 0x37, 0xe4, 0x8e, 0xef, 0xef, 0x5f, 0x27, 0x5c, 0x39, 0x9e, 0xe1, 0x7a, 0xd7, 0x91, 0x61, 0xca, 0x85, 0xa3, 0x6c, 0x52, 0xb1, 0x61, 0x1d, 0xdf, 0xde, 0xa4, 0xe7, 0x05, 0xa3, 0x95, 0x10, 0x76, 0xb4, 0x95, 0x8b, 0x5f, 0x23, 0xf5, 0x1e, 0xf1, 0x3d, 0x47, 0x45, 0x95, 0xca, 0xc4, 0x2d, 0xc4, 0x25, 0x94, 0x83, 0x6f, 0x74, 0x7f, 0xc2, 0x3e, 0xa7, 0xf7, 0xa9, 0x4d, 0x31, 0xcd, 0xad, 0x91, 0x17, 0x29, 0x6e, 0x6a, 0x6a, 0x6a, 0x53, 0x3d, 0xe7, 0xbc, 0x6a, 0xcc, 0xac, 0xca, 0xcc, 0xaf, 0x08, 0x96, 0x76, 0x39, 0xee, 0x47, 0xd4, 0xfe, 0xf5, 0xc2, 0x49, 0xde, 0x8c, 0xca, 0xfa, 0x8a, 0x2f, 0xa9, 0x91, 0xf5, 0x1c, 0x6b, 0x99, 0x91, 0xf5, 0x17, 0x86, 0x93, 0xbb, 0x3d, 0xcc, 0x8f, 0x97, 0x91, 0x07, 0x62, 0xdf, 0x08, 0xfa, 0x9f, 0xde, 0xb8, 0xbc, 0x5e, 0xba, 0x09, 0x75, 0xc3, 0x9b, 0x23, 0x8d, 0xa7, 0x82, 0x44, 0xe0, 0xaa, 0xa4, 0x28, 0xa8, 0xe8, 0xb9, 0x61, 0x1f, 0x53, 0xfb, 0xd7, 0x06, 0xe8, 0xb2, 0x1a, 0xac, 0x1c, 0x23, 0x99, 0x4d, 0xee, 0x2d, 0x30, 0x5d, 0x08, 0xe2, 0xa2, 0xa3, 0xb6, 0x17, 0x66, 0xea, 0x8e, 0xe7, 0x32, 0x3e, 0xa7, 0xf7, 0xae, 0x12, 0x6e, 0xf4, 0x45, 0xcb, 0xf5, 0xfe, 0x8c, 0xf2, 0xfd, 0x7f, 0xa3, 0x33, 0xbd, 0x51, 0xa6, 0xc5, 0x22, 0xce, 0xc2, 0x66, 0x63, 0x31, 0x9b, 0x09, 0x09, 0x34, 0x88, 0xb6, 0xd7, 0xe6, 0xb0, 0x8e, 0xef, 0x07, 0xcc, 0x5d, 0xf0, 0x96, 0xe8, 0xd6, 0xf5, 0x46, 0xe5, 0xb7, 0xb1, 0xcf, 0x52, 0x99, 0x46, 0xe2, 0xd7, 0x73, 0x74, 0x5b, 0x10, 0x8d, 0x45, 0xbe, 0x17, 0x4d, 0x97, 0x83, 0xe4, 0x3d, 0x77, 0xc3, 0x6b, 0xd7, 0x0a, 0xd4, 0x4b, 0x0d, 0x39, 0x09, 0x58, 0xed, 0x21, 0xbb, 0x74, 0xc6, 0x69, 0x64, 0x7b, 0x60, 0xea, 0xdd, 0x96, 0x91, 0x99, 0x16, 0x9d, 0x60, 0x92, 0xdd, 0x1e, 0x24, 0xe1, 0x79, 0x64, 0xac, 0xfe, 0x44, 0x6a, 0xa8, 0xcd, 0xa5, 0xa4, 0x3f, 0x15, 0x2b, 0x6c, 0xbc, 0xca, 0xc4, 0x84, 0x3d, 0x8d, 0x6c, 0x78, 0x2e, 0xf8, 0x4a, 0x19, 0xb5, 0xb3, 0x87, 0xf2, 0x67, 0x0b, 0xb9, 0xc2, 0xee, 0x70, 0xfb, 0x9c, 0x3e, 0xe7, 0x0f, 0xb9, 0x93, 0xe4, 0xce, 0x1f, 0x73, 0x84, 0x8e, 0x1f, 0x71, 0xf8, 0x7d, 0xce, 0x1a, 0xea, 0x64, 0xee, 0xce, 0x14, 0x45, 0xe1, 0xae, 0xa6, 0x51, 0x46, 0x8f, 0xff, 0xc4, 0x00, 0x40, 0x10, 0x00, 0x02, 0x01, 0x02, 0x04, 0x04, 0x03, 0x04, 0x07, 0x06, 0x04, 0x07, 0x01, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x00, 0x11, 0x04, 0x12, 0x21, 0x31, 0x13, 0x22, 0x41, 0x51, 0x32, 0x61, 0x81, 0x14, 0x71, 0x91, 0xa1, 0x10, 0x23, 0x42, 0x52, 0xc1, 0xd1, 0xf0, 0x05, 0x34, 0x62, 0x92, 0xb1, 0xe1, 0x15, 0x82, 0xb2, 0xf1, 0x24, 0x33, 0x35, 0x53, 0x72, 0x93, 0xa2, 0xd2, 0xff, 0xda, 0x00, 0x08, 0x01, 0x01, 0x00, 0x06, 0x3f, 0x02, 0xe7, 0x75, 0x5f, 0x79, 0xa6, 0x6c, 0x2c, 0xb1, 0x2c, 0x5f, 0xc4, 0xfa, 0xd0, 0xcf, 0xa8, 0x22, 0xfa, 0x5f, 0x4a, 0x39, 0x08, 0x36, 0x5c, 0xdb, 0xf4, 0xab, 0x5d, 0x6f, 0xb7, 0x88, 0x77, 0xb7, 0x7e, 0xe6, 0x81, 0xcc, 0x9a, 0xda, 0xdf, 0x58, 0xbd, 0x7d, 0x68, 0x59, 0x93, 0xbf, 0x8c, 0x7d, 0xd2, 0xdf, 0xd0, 0x50, 0xc4, 0x62, 0x15, 0x66, 0x97, 0x88, 0x63, 0x29, 0x9b, 0x4d, 0x94, 0xd0, 0x44, 0xc0, 0x44, 0xcc, 0x7a, 0x5c, 0xd0, 0x9b, 0xd9, 0x60, 0x08, 0x5c, 0xa0, 0xd5, 0xb7, 0x00, 0x1f, 0xc6, 0xbf, 0x76, 0x80, 0xfa, 0xb5, 0x21, 0x38, 0x38, 0x6c, 0xc2, 0xe3, 0x98, 0xf7, 0xa6, 0x68, 0xbf, 0x66, 0xac, 0x8a, 0x9a, 0xb3, 0x2e, 0x6b, 0x0a, 0xfd, 0xce, 0x1f, 0xe6, 0x35, 0xfb, 0x8c, 0x5f, 0xcc, 0x6b, 0xf7, 0x28, 0x7f, 0x98, 0xd4, 0x8e, 0x61, 0xc3, 0xc6, 0xcb, 0xb4, 0x64, 0x9b, 0xb6, 0x94, 0xdc, 0x38, 0x30, 0xbc, 0xad, 0x6c, 0xac, 0x8e, 0x7e, 0x77, 0xa9, 0x8c, 0xb1, 0xa2, 0x18, 0xf2, 0xea, 0x97, 0xd7, 0xe3, 0x53, 0xe2, 0x16, 0x45, 0x54, 0xcc, 0x6d, 0xcd, 0xad, 0xbe, 0x14, 0x98, 0x48, 0x64, 0x66, 0x67, 0x6c, 0x8a, 0xd9, 0xac, 0x2f, 0x52, 0x2c, 0x93, 0xc8, 0x5a, 0x37, 0x31, 0x9b, 0xbd, 0xec, 0x69, 0x2d, 0x3b, 0x8c, 0xdd, 0x9e, 0x88, 0x38, 0x99, 0x3f, 0x9c, 0xd6, 0x6f, 0x68, 0x92, 0xf7, 0xb7, 0x8a, 0xa1, 0xd5, 0xda, 0x52, 0xee, 0x49, 0xca, 0x18, 0x91, 0xa5, 0xb7, 0xbf, 0xf1, 0x54, 0x0c, 0xc1, 0x94, 0xf1, 0x2f, 0xce, 0xa1, 0x7b, 0x76, 0xae, 0xa2, 0x84, 0x71, 0x40, 0xd2, 0xc4, 0x1c, 0xb7, 0x87, 0xad, 0x85, 0xff, 0x00, 0xa0, 0xa8, 0xc4, 0x98, 0x61, 0x19, 0x65, 0x1e, 0x21, 0xb9, 0xab, 0x28, 0x0a, 0xab, 0xca, 0xa0, 0x51, 0x47, 0x59, 0xb8, 0x86, 0xfa, 0xa9, 0xd2, 0x97, 0xda, 0x00, 0x93, 0xfe, 0xda, 0x95, 0xb8, 0x2f, 0xd2, 0xfe, 0x55, 0xff, 0x00, 0x14, 0x89, 0x07, 0xd5, 0x34, 0x4c, 0xf6, 0xd4, 0x49, 0xd5, 0x7d, 0xc4, 0x0a, 0xc9, 0xf7, 0xfe, 0xf1, 0x5b, 0xd5, 0xb9, 0xef, 0xfc, 0x54, 0x79, 0x02, 0x8e, 0x27, 0x8c, 0x8f, 0x7e, 0x95, 0x8c, 0xbe, 0x87, 0x97, 0x4e, 0xd5, 0x88, 0x84, 0xe2, 0x71, 0x11, 0xa6, 0x6f, 0x02, 0x48, 0x40, 0xac, 0xf6, 0x7c, 0xe3, 0x50, 0x73, 0x9f, 0xce, 0x88, 0x45, 0xcb, 0x73, 0x73, 0x49, 0xcd, 0x9b, 0xcb, 0xb5, 0x3d, 0xe8, 0x76, 0xbd, 0x42, 0x5c, 0xda, 0xc5, 0xba, 0xfb, 0xbc, 0xfc, 0xea, 0xcb, 0xaa, 0x2f, 0x50, 0x6f, 0xdb, 0xf8, 0xbf, 0x5d, 0xa8, 0x16, 0x89, 0x66, 0xfa, 0xbb, 0x73, 0x7f, 0x5a, 0x2b, 0x19, 0x2a, 0xc5, 0x8b, 0x70, 0xd4, 0xda, 0xdb, 0x54, 0x7c, 0x5b, 0x86, 0x6d, 0x10, 0x31, 0xbf, 0x55, 0xa0, 0x0a, 0xd9, 0xbc, 0xaa, 0x6f, 0x68, 0x9c, 0x41, 0x6b, 0x65, 0x37, 0xf5, 0x3f, 0x2b, 0xfa, 0xda, 0xa2, 0x96, 0x2c, 0x59, 0x25, 0x64, 0x7b, 0x32, 0x14, 0xb2, 0x81, 0x70, 0x3a, 0xd4, 0x6b, 0x36, 0x3f, 0x3c, 0x7c, 0x3e, 0x21, 0x58, 0xd6, 0x31, 0xc4, 0x6d, 0x3c, 0xfc, 0xfe, 0x55, 0x9d, 0xbf, 0x68, 0xa1, 0x02, 0xde, 0x0b, 0x1e, 0xa7, 0xbf, 0xba, 0xad, 0x7b, 0xe5, 0xda, 0xbc, 0x45, 0xcf, 0x13, 0xc3, 0x6f, 0x9d, 0x62, 0xad, 0xd9, 0x75, 0xef, 0x58, 0x8b, 0x77, 0xfa, 0x62, 0xe9, 0xef, 0xa7, 0x63, 0xf1, 0xb5, 0x01, 0xd6, 0xf4, 0x97, 0xbe, 0x8e, 0xdb, 0x7f, 0x97, 0xca, 0x99, 0x01, 0xd5, 0x96, 0xcb, 0x9c, 0x1f, 0xd7, 0x4a, 0xb3, 0x62, 0xd5, 0x64, 0x45, 0xf0, 0x95, 0x3b, 0xd7, 0x09, 0xe4, 0x85, 0x8a, 0x95, 0x02, 0xd1, 0xe5, 0x6f, 0xe9, 0xe6, 0x4f, 0xa5, 0x44, 0x07, 0xb3, 0xe6, 0x4b, 0x73, 0xe4, 0x3c, 0xba, 0x0f, 0xe1, 0xf2, 0xf9, 0x53, 0x64, 0xc6, 0x20, 0x75, 0x21, 0x6d, 0x90, 0xd3, 0x5b, 0x1b, 0xa8, 0xfe, 0x03, 0x63, 0x51, 0x14, 0xc4, 0x89, 0x36, 0xcd, 0xcb, 0x6b, 0x56, 0x0a, 0x19, 0x78, 0x72, 0x80, 0x1a, 0xe0, 0x35, 0xae, 0x17, 0x53, 0xee, 0x15, 0x86, 0x92, 0x28, 0x78, 0x2a, 0xf2, 0xb4, 0x57, 0x81, 0xcb, 0x66, 0x39, 0x6f, 0xb1, 0xed, 0xa7, 0xc6, 0xb8, 0x8b, 0x1c, 0xeb, 0x73, 0xe2, 0x93, 0x66, 0x1f, 0xab, 0x51, 0xe4, 0x0a, 0x38, 0x9e, 0x3f, 0xc2, 0xb1, 0x77, 0xd0, 0xd9, 0x34, 0x1d, 0x2b, 0x11, 0x34, 0xb8, 0x9c, 0x98, 0xab, 0x9b, 0xa8, 0x93, 0xf0, 0xa5, 0x8d, 0xd9, 0xa3, 0x4c, 0xc0, 0x36, 0x55, 0x27, 0x4e, 0xfb, 0x56, 0x23, 0x21, 0x66, 0x89, 0x65, 0x2b, 0x1b, 0x30, 0xb1, 0x2b, 0xd0, 0xfd, 0x1b, 0xfa, 0x7d, 0x0a, 0x4c, 0x2d, 0x2f, 0xd6, 0xb0, 0xe5, 0x50, 0x4e, 0xcb, 0xe4, 0x6b, 0x3a, 0xab, 0xc2, 0x46, 0x51, 0x91, 0xed, 0x19, 0x22, 0xf6, 0xed, 0x4e, 0xc3, 0xa3, 0x93, 0x70, 0x6f, 0xd6, 0x8f, 0x3f, 0x38, 0x3d, 0x2a, 0x57, 0x91, 0xc2, 0x92, 0xdc, 0xc2, 0xda, 0xdc, 0x5f, 0xff, 0x00, 0xd1, 0xa1, 0x8d, 0x0b, 0x79, 0x9d, 0xaf, 0xc2, 0x12, 0x73, 0x6e, 0x6d, 0x7a, 0x8e, 0x18, 0xf8, 0xde, 0xd2, 0x06, 0x5e, 0x03, 0x44, 0x1b, 0x9f, 0x9a, 0xc2, 0x9e, 0x54, 0xb2, 0xc9, 0xee, 0xf3, 0xa8, 0x04, 0xed, 0xc8, 0x52, 0x4d, 0x7e, 0xee, 0xf5, 0x0c, 0x26, 0x78, 0xee, 0x31, 0x5c, 0x42, 0x43, 0x69, 0x62, 0xb6, 0xdc, 0x54, 0xd7, 0xc4, 0x47, 0x35, 0xc0, 0x3a, 0x49, 0xa0, 0x23, 0x37, 0x7f, 0x4f, 0x75, 0x31, 0xb9, 0x66, 0xcf, 0xb5, 0xab, 0x14, 0x00, 0xb0, 0xb2, 0xfa, 0xd4, 0xae, 0x36, 0x63, 0x7b, 0xd1, 0x38, 0xb9, 0x84, 0x11, 0x7d, 0x96, 0xcb, 0x7d, 0x69, 0x92, 0x06, 0x5c, 0x4e, 0xd6, 0xcb, 0xd6, 0xb9, 0xa3, 0x44, 0x04, 0x68, 0x4d, 0xf5, 0xab, 0x84, 0x46, 0x1d, 0xec, 0xde, 0x5f, 0x9d, 0x10, 0x51, 0x17, 0xaf, 0x85, 0xbb, 0xff, 0x00, 0x7a, 0x8f, 0x0f, 0x90, 0xe5, 0xbf, 0x12, 0xc0, 0x1e, 0xb7, 0xd7, 0xe0, 0xab, 0x4e, 0xa1, 0x5e, 0x44, 0x57, 0x4c, 0xea, 0xa2, 0xe7, 0xb9, 0x1a, 0xda, 0x9a, 0x45, 0xb9, 0xcf, 0x7b, 0x5f, 0x7d, 0xcd, 0x4c, 0x26, 0xc3, 0x26, 0x23, 0x30, 0x00, 0x5c, 0xed, 0xb5, 0x5d, 0xff, 0x00, 0x65, 0xc2, 0xe2, 0xf9, 0x8d, 0xdb, 0x7f, 0x95, 0x7f, 0xd2, 0xe1, 0x27, 0x29, 0x17, 0xbf, 0x9f, 0xba, 0x9d, 0xbf, 0xc3, 0x62, 0x0e, 0xfd, 0x73, 0x75, 0xbf, 0xba, 0xa3, 0x13, 0xc0, 0xbc, 0x1d, 0xf3, 0xc4, 0x35, 0x6d, 0xfa, 0xfa, 0xfc, 0xaa, 0x05, 0xc1, 0xab, 0xf1, 0x77, 0x0f, 0x23, 0x05, 0x09, 0xeb, 0xf8, 0xd2, 0x2c, 0xe1, 0x31, 0x80, 0x8b, 0xc4, 0x51, 0xc1, 0xc9, 0xa1, 0xbf, 0x87, 0x6d, 0xaf, 0xe9, 0x45, 0xca, 0xd9, 0x47, 0x2d, 0x3b, 0x18, 0xc0, 0x5e, 0x2d, 0xb8, 0xbf, 0x1e, 0x5f, 0xd7, 0x6a, 0xc5, 0xdc, 0x5b, 0x44, 0xd2, 0xb5, 0xae, 0x08, 0xe6, 0xc3, 0xdd, 0x9a, 0xc1, 0x01, 0xb1, 0xf5, 0xa6, 0xf6, 0x4f, 0xd9, 0xcb, 0x2c, 0x5a, 0x59, 0xb2, 0x28, 0x3e, 0xbe, 0xb5, 0x1a, 0x70, 0x62, 0xcf, 0x9c, 0x85, 0x46, 0x8c, 0x02, 0x07, 0x43, 0xeb, 0x52, 0x2d, 0xf0, 0x1c, 0x8b, 0xaa, 0x00, 0xdd, 0x01, 0xf2, 0xf2, 0xa7, 0x95, 0xd6, 0x0e, 0x50, 0x35, 0x09, 0xe5, 0x7f, 0xc0, 0x54, 0xd2, 0x45, 0x1c, 0x2b, 0x3c, 0x6b, 0x9b, 0x55, 0xdf, 0xf4, 0x2f, 0xf0, 0xa9, 0x75, 0x8e, 0x11, 0xe3, 0xb4, 0x51, 0x91, 0x73, 0xef, 0xbd, 0x61, 0xac, 0xd9, 0x7b, 0xd6, 0xba, 0xe8, 0x36, 0xf7, 0x54, 0x25, 0xa1, 0xf6, 0x86, 0x27, 0x2a, 0x47, 0xdd, 0x8e, 0xd5, 0x1f, 0xf8, 0x8a, 0x15, 0x65, 0xbc, 0x68, 0xf9, 0x77, 0x65, 0xdf, 0xd0, 0xdf, 0xe5, 0x5e, 0xea, 0xc0, 0xfb, 0x44, 0xb1, 0x88, 0x84, 0x77, 0xca, 0xfb, 0x6f, 0x6e, 0xde, 0x74, 0xd2, 0x45, 0xc2, 0x21, 0x20, 0x94, 0x65, 0xd0, 0xdc, 0x8e, 0xbf, 0xfc, 0xfc, 0xeb, 0x03, 0x2b, 0xaa, 0x96, 0xe2, 0x38, 0x26, 0xf9, 0x6f, 0xa1, 0xfc, 0x34, 0xa9, 0x64, 0x5c, 0xb1, 0x00, 0xda, 0xa1, 0x94, 0xb6, 0x9b, 0xfa, 0xf8, 0x87, 0xc2, 0x9b, 0xc4, 0x5b, 0x37, 0x6e, 0x95, 0x8a, 0xb6, 0xd6, 0x4d, 0x6d, 0x6a, 0x35, 0xeb, 0x53, 0x36, 0x9c, 0xab, 0x7d, 0x68, 0x4f, 0x8c, 0x7e, 0x2f, 0x88, 0x17, 0x91, 0x0b, 0x74, 0xd2, 0xa2, 0xc3, 0x02, 0xf3, 0xa4, 0x84, 0x46, 0x64, 0xca, 0x0a, 0x6b, 0xde, 0x9b, 0x29, 0x2d, 0x0c, 0xe0, 0xb3, 0x24, 0x8b, 0x94, 0xad, 0xaf, 0xb7, 0xeb, 0xcb, 0xce, 0x8b, 0xc4, 0x55, 0x52, 0x5f, 0x18, 0x63, 0x63, 0x6d, 0x39, 0x7a, 0xd3, 0xa0, 0x59, 0x42, 0xa7, 0x2b, 0xad, 0xb6, 0xa8, 0x78, 0x6d, 0x91, 0x94, 0x58, 0x8d, 0xae, 0x0d, 0x2f, 0x1a, 0x3c, 0xd1, 0xdb, 0x55, 0x5d, 0x6f, 0xc9, 0xa7, 0xce, 0x95, 0xfd, 0x86, 0x48, 0xfb, 0xae, 0x53, 0xf7, 0x74, 0xb6, 0xbf, 0xef, 0x4a, 0xcf, 0x04, 0xce, 0xa3, 0x2d, 0x8c, 0x81, 0x8f, 0x2f, 0x51, 0x7c, 0xdd, 0xeb, 0x2c, 0x38, 0x69, 0x16, 0x5d, 0x39, 0x9c, 0xde, 0xdf, 0xaf, 0x75, 0x61, 0x2f, 0x94, 0x29, 0x5b, 0xdd, 0x40, 0x27, 0xc5, 0xef, 0xa5, 0x92, 0xe6, 0x33, 0xc3, 0xcb, 0x7b, 0x5e, 0xd7, 0xff, 0x00, 0x7a, 0x47, 0xc1, 0x4a, 0x64, 0xe1, 0x73, 0x31, 0x96, 0x3c, 0xa0, 0x1d, 0x76, 0x14, 0xca, 0xf2, 0x67, 0x13, 0x78, 0xf9, 0x47, 0x6b, 0xfe, 0x5f, 0x0a, 0x62, 0x47, 0x2e, 0x7f, 0x1d, 0xab, 0x19, 0xd0, 0xd9, 0x34, 0xa3, 0x42, 0x05, 0x85, 0x18, 0x9c, 0xde, 0x36, 0x23, 0xf0, 0xa9, 0x21, 0xc5, 0x42, 0x6e, 0x37, 0x11, 0x2b, 0x1f, 0x8d, 0xea, 0x48, 0xa0, 0x8d, 0xe2, 0x8e, 0xfa, 0x2b, 0x9f, 0x21, 0xf9, 0x54, 0x4c, 0xf1, 0xbf, 0x09, 0x97, 0x2e, 0x6b, 0xd8, 0x06, 0xef, 0x53, 0x47, 0x0c, 0x8d, 0x94, 0xe8, 0x0c, 0xad, 0x72, 0xa2, 0xdd, 0x74, 0x3a, 0x5f, 0xcf, 0xb5, 0x4a, 0xb8, 0xb8, 0x9a, 0x78, 0xbc, 0x69, 0x22, 0xcb, 0xa5, 0xfc, 0xbb, 0x9d, 0xa9, 0x64, 0xc1, 0xcb, 0x12, 0x9d, 0x82, 0x49, 0x28, 0xb9, 0x3b, 0xed, 0x51, 0x62, 0xd7, 0x12, 0x78, 0xaf, 0x26, 0x5d, 0x8a, 0x1f, 0x3f, 0xca, 0xa1, 0x9a, 0x50, 0xed, 0x1c, 0x6c, 0xae, 0x55, 0xb7, 0xd8, 0x77, 0xa6, 0x12, 0xa5, 0xc6, 0x52, 0x6f, 0x72, 0xc4, 0xbd, 0x88, 0x1b, 0x9f, 0x3e, 0x95, 0x8c, 0x78, 0x31, 0x78, 0xb6, 0xe3, 0x0c, 0x8b, 0x01, 0x40, 0x11, 0x56, 0xe3, 0xcc, 0xf4, 0x1f, 0x46, 0x0c, 0x2e, 0x65, 0xce, 0xa7, 0x56, 0x5b, 0xdf, 0xff, 0x00, 0x1f, 0xed, 0x52, 0x23, 0x01, 0x32, 0xa4, 0x25, 0xc2, 0xb9, 0xb2, 0x9b, 0x11, 0xbf, 0xc4, 0xd6, 0x0a, 0x45, 0x89, 0x22, 0x8e, 0x52, 0xe9, 0x96, 0x12, 0x79, 0x88, 0x52, 0x6e, 0x6f, 0xe9, 0xf0, 0xa5, 0xf1, 0x17, 0xcc, 0x6d, 0xdb, 0xaf, 0xe5, 0x4d, 0xab, 0x66, 0xcf, 0xe1, 0x3b, 0x56, 0x2a, 0xda, 0x8c, 0xa9, 0x63, 0x6b, 0x7d, 0x0b, 0x0c, 0xd3, 0x18, 0x59, 0x45, 0xc7, 0x0c, 0x77, 0xae, 0x6c, 0x5c, 0x8d, 0xe6, 0xc0, 0xfe, 0x54, 0xff, 0x00, 0x5e, 0xd3, 0x17, 0x03, 0x9e, 0x4b, 0xdc, 0x6f, 0x7b, 0x69, 0x52, 0x7b, 0x3c, 0x96, 0x51, 0xaf, 0x08, 0x13, 0x61, 0xaf, 0x9f, 0x4a, 0x92, 0x75, 0x11, 0xc4, 0xb2, 0x42, 0xb7, 0x53, 0x19, 0xfe, 0xbe, 0x97, 0xf5, 0xab, 0x48, 0x04, 0x9c, 0x04, 0x59, 0xfc, 0x1b, 0xdf, 0xa7, 0xba, 0xa6, 0x4c, 0xdc, 0xe9, 0x9a, 0x51, 0x63, 0x66, 0x1a, 0x5b, 0xed, 0x7b, 0xe9, 0x71, 0x0f, 0x88, 0x59, 0xe5, 0x86, 0x4c, 0xb7, 0xfb, 0xd7, 0x5b, 0xfc, 0x86, 0x95, 0x2b, 0x16, 0x54, 0x28, 0x88, 0x49, 0x3e, 0x63, 0xc8, 0x52, 0x8e, 0x34, 0x62, 0xf6, 0x1d, 0x6a, 0xfc, 0x78, 0xf6, 0x27, 0xaf, 0x7a, 0x76, 0x33, 0xc5, 0xca, 0x2f, 0xd7, 0xbd, 0xaa, 0x33, 0x3b, 0xa0, 0x85, 0x16, 0xc8, 0x72, 0x5f, 0x5e, 0xda, 0x6b, 0x58, 0x8c, 0x92, 0x25, 0xce, 0x1c, 0xa7, 0x24, 0x45, 0x46, 0xb9, 0x45, 0x60, 0xa3, 0x69, 0x90, 0xa8, 0x91, 0x89, 0x6b, 0x5d, 0x75, 0xfe, 0xd5, 0x26, 0x59, 0xe2, 0x61, 0x27, 0xda, 0x11, 0xe9, 0x71, 0x7d, 0x40, 0xf5, 0xa6, 0xb8, 0x5c, 0xb9, 0xfc, 0x5d, 0x7d, 0xd5, 0x88, 0x63, 0xa3, 0x1b, 0x02, 0x07, 0x90, 0x1f, 0x9f, 0xd1, 0x7c, 0x68, 0x66, 0x4c, 0xba, 0xe5, 0x3a, 0xfe, 0xb7, 0xa4, 0xff, 0x00, 0x0d, 0x0d, 0x1c, 0x39, 0x7e, 0xd5, 0xc1, 0xcd, 0xef, 0xfe, 0xf5, 0xae, 0xf5, 0x2f, 0x10, 0x66, 0x4c, 0x9a, 0x8b, 0xdb, 0xad, 0x61, 0xd0, 0xcc, 0x5a, 0x29, 0x32, 0x67, 0x43, 0x2e, 0x8a, 0x3e, 0xef, 0x96, 0xc3, 0xe1, 0xb5, 0x61, 0xa5, 0x74, 0x46, 0x8c, 0xc8, 0xc3, 0x94, 0x06, 0xbe, 0xfe, 0xb5, 0x84, 0xb8, 0x22, 0x28, 0xf2, 0xe7, 0x4b, 0x78, 0x88, 0xdf, 0x4f, 0xd6, 0xf5, 0x66, 0x53, 0x12, 0x97, 0x55, 0x52, 0xab, 0x93, 0x29, 0xb1, 0xde, 0xa4, 0x8f, 0x8c, 0xbc, 0x9a, 0xab, 0x2c, 0x9b, 0x0b, 0x6d, 0xda, 0x9e, 0x4c, 0x43, 0x02, 0x10, 0x70, 0x95, 0x43, 0xdc, 0x66, 0x0b, 0x75, 0x37, 0xb0, 0xe5, 0xef, 0x43, 0x12, 0x23, 0xc5, 0x65, 0xe1, 0x59, 0x8a, 0xb2, 0x6e, 0x3a, 0x6b, 0xad, 0x4a, 0xc2, 0x08, 0x25, 0xfa, 0xd4, 0x5b, 0xc8, 0x6d, 0xd4, 0x79, 0x76, 0xf8, 0x54, 0x92, 0x5d, 0x4e, 0x76, 0xe7, 0xc3, 0xed, 0xbe, 0xba, 0x0a, 0x13, 0x44, 0xcb, 0x9c, 0x1b, 0xc6, 0xc5, 0xac, 0x45, 0x3f, 0xb4, 0xc7, 0xed, 0x73, 0x91, 0x95, 0x1c, 0x9d, 0xa9, 0x03, 0xc0, 0xb3, 0x30, 0x6b, 0x7b, 0xb4, 0xda, 0x9f, 0xc5, 0x9b, 0x36, 0xc6, 0xa5, 0xb1, 0xb8, 0xbe, 0x9f, 0x05, 0xfa, 0x0a, 0xc1, 0x1b, 0x4a, 0xf9, 0x6d, 0x64, 0x04, 0x93, 0xe8, 0x28, 0x26, 0x20, 0x70, 0x1e, 0xd7, 0xca, 0xfb, 0xda, 0xa7, 0x43, 0x14, 0x72, 0x97, 0x4c, 0xb9, 0x9f, 0xec, 0xf9, 0x8f, 0x3a, 0x9e, 0xfa, 0xf2, 0x6d, 0xea, 0x28, 0x4c, 0x31, 0x48, 0xa1, 0xca, 0xc8, 0x16, 0xe4, 0x75, 0x3a, 0x6d, 0x51, 0x33, 0xcd, 0x14, 0xb9, 0x1f, 0x38, 0xd7, 0x9a, 0xcc, 0xd6, 0xb8, 0xea, 0x4f, 0xeb, 0xdd, 0xc9, 0x85, 0x8d, 0x9c, 0x0b, 0x1c, 0xf1, 0x82, 0x6f, 0x9f, 0xce, 0xad, 0x0c, 0x69, 0x24, 0xbc, 0xa5, 0xa3, 0xcd, 0x6c, 0xd6, 0xdc, 0x69, 0xfd, 0x3f, 0x2a, 0xfa, 0xec, 0x02, 0x09, 0x0d, 0xc5, 0x83, 0x66, 0xca, 0x02, 0xde, 0xe2, 0xff, 0x00, 0x9d, 0x7b, 0x3c, 0x47, 0x89, 0x1a, 0x8c, 0xd9, 0x6c, 0x17, 0xde, 0x7c, 0xeb, 0x44, 0x66, 0x5d, 0x6c, 0xab, 0xd7, 0x6a, 0xd2, 0xd1, 0x59, 0xf8, 0x84, 0xe6, 0x1d, 0x3f, 0xde, 0x8c, 0x13, 0xc9, 0x12, 0xac, 0x9f, 0x68, 0xa6, 0x72, 0x40, 0xae, 0x1a, 0xca, 0xa5, 0xda, 0xfb, 0x45, 0xf8, 0xd8, 0x54, 0xd2, 0xe5, 0x39, 0xd5, 0x4f, 0x39, 0x61, 0xca, 0x7c, 0xfe, 0x54, 0x34, 0xb9, 0xd4, 0x93, 0x52, 0x13, 0x97, 0x28, 0x93, 0xc5, 0xd4, 0x54, 0xd7, 0x19, 0x4e, 0x6d, 0x40, 0xf7, 0x2f, 0xd0, 0xd3, 0x60, 0xd5, 0xed, 0x6f, 0x12, 0xd0, 0x7c, 0x44, 0x1c, 0x59, 0x00, 0xcb, 0x9d, 0xb4, 0x36, 0xf4, 0xa3, 0x6c, 0x3b, 0x7c, 0x6a, 0x57, 0x96, 0x12, 0xa8, 0x45, 0xaf, 0xea, 0x2a, 0xd2, 0x48, 0x10, 0xaa, 0x6c, 0x65, 0x2b, 0xf6, 0xfb, 0x7c, 0x2b, 0xeb, 0x24, 0xce, 0x89, 0x88, 0x21, 0x6c, 0x13, 0xb1, 0xd6, 0xfb, 0x9a, 0x8b, 0x11, 0x23, 0x61, 0xcc, 0xa5, 0x73, 0x5b, 0xa6, 0xf7, 0xf7, 0x74, 0xa6, 0x8c, 0x4a, 0x8a, 0x97, 0xfb, 0xe7, 0xf5, 0xf6, 0x7f, 0x44, 0xd3, 0xf1, 0x31, 0x12, 0x4a, 0x15, 0x9e, 0xca, 0x5f, 0x4f, 0x00, 0xf9, 0xeb, 0x51, 0x89, 0xa0, 0x49, 0xcc, 0xc2, 0xd1, 0xda, 0x6c, 0x99, 0x74, 0x3e, 0x7a, 0xf4, 0xdf, 0xb5, 0x3a, 0x7b, 0x2c, 0x4f, 0x9b, 0xbc, 0xe7, 0xf0, 0x36, 0x1e, 0xb5, 0x20, 0x8a, 0x50, 0x99, 0xc5, 0xb5, 0x5b, 0xd4, 0x5f, 0x56, 0x07, 0xf9, 0x23, 0x1f, 0xe9, 0x34, 0x96, 0x5b, 0xda, 0xfd, 0x14, 0xff, 0x00, 0xab, 0x4a, 0x94, 0x5f, 0x5b, 0xdf, 0x94, 0x2d, 0xbe, 0x5a, 0x56, 0x60, 0x84, 0xd9, 0x6e, 0x7c, 0x87, 0x7a, 0x93, 0x46, 0x12, 0x66, 0xda, 0xda, 0x5a, 0x9e, 0xc4, 0x95, 0x26, 0xeb, 0xf2, 0xfc, 0x6f, 0xf4, 0x02, 0xf6, 0xef, 0x5b, 0x2f, 0xc4, 0xd3, 0x36, 0x16, 0x5e, 0x09, 0x6d, 0x0e, 0x53, 0xbd, 0x33, 0x97, 0xbb, 0xb1, 0xbb, 0x31, 0x63, 0xad, 0x19, 0x1e, 0x4c, 0xce, 0xdb, 0x9b, 0xd7, 0x12, 0x39, 0x32, 0xb8, 0xeb, 0x59, 0x53, 0x17, 0x22, 0x2f, 0x60, 0xe6, 0xbf, 0x7e, 0x9b, 0xff, 0x00, 0x6b, 0x51, 0x76, 0x97, 0x33, 0x1d, 0xc9, 0x3b, 0xd0, 0x61, 0x2f, 0x30, 0xeb, 0x44, 0xa6, 0x28, 0x8b, 0xb6, 0x6f, 0x5d, 0xaa, 0xc2, 0x41, 0x6d, 0xea, 0xdc, 0x41, 0x6a, 0xd2, 0x41, 0x5f, 0xf3, 0x00, 0xa7, 0x1c, 0x45, 0xe7, 0xf1, 0x69, 0xbd, 0x30, 0xe3, 0xd8, 0x13, 0x9b, 0xd7, 0xdf, 0x4c, 0xb9, 0xf3, 0x5e, 0xbf, 0xff, 0xc4, 0x00, 0x26, 0x10, 0x01, 0x00, 0x02, 0x02, 0x01, 0x04, 0x02, 0x02, 0x03, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x11, 0x21, 0x00, 0x31, 0x41, 0x51, 0x61, 0x71, 0x81, 0x91, 0xa1, 0xb1, 0xc1, 0xd1, 0xf0, 0xf1, 0xe1, 0x10, 0xff, 0xda, 0x00, 0x08, 0x01, 0x01, 0x00, 0x01, 0x3f, 0x21, 0xb0, 0x0b, 0xa2, 0x09, 0xc6, 0xb1, 0x2a, 0x87, 0xe2, 0x19, 0x27, 0x8a, 0x14, 0x51, 0xdf, 0x13, 0x1c, 0xc1, 0x87, 0x95, 0xb8, 0xab, 0x2a, 0x1d, 0x1b, 0x8f, 0xd4, 0x7c, 0xe0, 0x68, 0x91, 0xd8, 0x13, 0x28, 0x3e, 0x98, 0x22, 0x8c, 0x90, 0x9d, 0x1d, 0xc7, 0x53, 0xfa, 0xe4, 0xbe, 0xa2, 0x14, 0x48, 0x0d, 0x3b, 0xb7, 0x35, 0xce, 0x21, 0x94, 0x35, 0x69, 0x33, 0xb1, 0x2a, 0x3a, 0x1f, 0xbc, 0x7a, 0x1b, 0xa9, 0x14, 0x6e, 0x7e, 0x09, 0xf1, 0x8d, 0xd3, 0x38, 0x3a, 0xa2, 0x3c, 0xd7, 0xd9, 0x82, 0xbc, 0xac, 0x03, 0xd5, 0xe9, 0x8b, 0xb9, 0xb0, 0x4a, 0x3c, 0xbf, 0xf8, 0xd3, 0x21, 0xab, 0x60, 0xe4, 0x9a, 0x75, 0xb2, 0x3a, 0xde, 0x0b, 0x8b, 0x64, 0x11, 0x77, 0x02, 0x7a, 0xc3, 0x36, 0x90, 0x10, 0x4c, 0xb6, 0x15, 0x61, 0x07, 0x39, 0x4d, 0xc3, 0xb4, 0xf2, 0x08, 0x72, 0x09, 0xc9, 0x8e, 0x99, 0x64, 0xa1, 0x06, 0x1b, 0xd6, 0x08, 0x7a, 0xf4, 0xf6, 0x27, 0x24, 0x9b, 0x11, 0x66, 0x00, 0x83, 0xa3, 0x9f, 0x7f, 0xe3, 0x1e, 0x95, 0x51, 0x8a, 0x48, 0x93, 0x08, 0x7e, 0xcf, 0x5c, 0x9f, 0x91, 0x25, 0x46, 0xb8, 0x02, 0xba, 0x65, 0x5d, 0x5d, 0x31, 0x58, 0x2a, 0x45, 0xa2, 0x81, 0x88, 0x9f, 0x14, 0xff, 0x00, 0x38, 0x8b, 0x63, 0x02, 0x77, 0x39, 0xeb, 0x90, 0x90, 0xfc, 0x0c, 0x4a, 0xfe, 0x57, 0x1e, 0x34, 0xe4, 0x5f, 0x1a, 0xfe, 0xef, 0x5d, 0x60, 0xe8, 0x22, 0x4b, 0x55, 0x41, 0xc8, 0xdf, 0xac, 0x88, 0xa0, 0xdd, 0x67, 0x64, 0xa7, 0xb2, 0x74, 0xae, 0x0c, 0x1a, 0x49, 0x48, 0x84, 0x6f, 0xa2, 0xce, 0x69, 0x08, 0x58, 0x60, 0x7e, 0x32, 0xec, 0x59, 0xcd, 0x85, 0xea, 0x4f, 0xbc, 0x88, 0xe3, 0x05, 0x72, 0x14, 0x7f, 0xdf, 0x78, 0xe7, 0x6a, 0x87, 0xa1, 0xec, 0x61, 0x7e, 0x50, 0x67, 0x30, 0x11, 0xca, 0x45, 0xca, 0xed, 0x70, 0x31, 0x58, 0x5c, 0x7a, 0x30, 0xa0, 0xb8, 0xab, 0xac, 0x49, 0x11, 0xc2, 0x7c, 0xe4, 0x4c, 0x80, 0xd8, 0xe7, 0xa0, 0x61, 0x89, 0x5b, 0x9a, 0x06, 0x2f, 0xb4, 0xfc, 0xb8, 0x27, 0x46, 0x04, 0xd0, 0x67, 0xf8, 0x66, 0xb6, 0xb5, 0xf0, 0xc3, 0xb7, 0x4f, 0xac, 0xb5, 0x97, 0xe4, 0x59, 0xeb, 0xa6, 0x21, 0x72, 0xa6, 0xc7, 0xcc, 0xff, 0x00, 0x6b, 0x12, 0x9c, 0xba, 0x24, 0xee, 0x4f, 0x48, 0x60, 0xc5, 0xa4, 0x54, 0xa4, 0xc6, 0xf2, 0xc1, 0xc4, 0x43, 0x87, 0x91, 0x94, 0x10, 0xa2, 0x24, 0x92, 0x49, 0x7c, 0xa3, 0x00, 0x1c, 0x15, 0xa3, 0xab, 0x50, 0x98, 0x83, 0x1d, 0xf9, 0xcb, 0x0b, 0x2a, 0xfd, 0xa4, 0xe3, 0x8c, 0x72, 0x6c, 0x53, 0xc5, 0xbd, 0xb5, 0xda, 0x33, 0x5b, 0xad, 0xb1, 0x1a, 0x3f, 0x8d, 0x57, 0x4c, 0x74, 0x89, 0x29, 0xe1, 0x8c, 0x8a, 0x74, 0xee, 0xe7, 0xc7, 0x0e, 0xd4, 0x82, 0x66, 0x10, 0x56, 0x24, 0x0a, 0xdc, 0x22, 0x93, 0x96, 0x1b, 0xb2, 0x3e, 0x70, 0xcb, 0x10, 0xe6, 0x1f, 0x78, 0x5d, 0x7b, 0x79, 0xe3, 0x07, 0x58, 0x32, 0x44, 0xc4, 0xc1, 0x3f, 0x96, 0x39, 0x14, 0x01, 0xa9, 0xf4, 0x9c, 0xb0, 0xa6, 0x26, 0x0d, 0x2b, 0x2e, 0x4f, 0xe8, 0xef, 0x7f, 0x85, 0x0e, 0xca, 0x47, 0x6a, 0x2d, 0x77, 0xf2, 0xc3, 0xd4, 0xb8, 0xc4, 0xdc, 0x37, 0xb6, 0xfc, 0xf3, 0xd8, 0xc4, 0x08, 0x69, 0x08, 0xa5, 0x65, 0xdf, 0x8b, 0xb3, 0x2e, 0x7c, 0xcd, 0x43, 0x4b, 0xf3, 0x09, 0x75, 0xfc, 0x67, 0xd3, 0x37, 0xfe, 0x95, 0x85, 0x4e, 0xf2, 0x7d, 0x28, 0x58, 0x10, 0x21, 0x92, 0x92, 0xec, 0xbd, 0x04, 0x1a, 0x61, 0xc9, 0x78, 0xa3, 0xfd, 0xb9, 0x60, 0x97, 0xac, 0x6e, 0x6f, 0x79, 0x8b, 0xdc, 0x44, 0xd6, 0x22, 0x39, 0x6c, 0x51, 0xa3, 0xfe, 0xfb, 0xc0, 0x39, 0x44, 0xb3, 0x3c, 0x72, 0x70, 0x41, 0xe0, 0x18, 0xb5, 0xec, 0xc5, 0x07, 0x2d, 0x65, 0xf0, 0x60, 0x4f, 0xac, 0x96, 0xc9, 0x42, 0xcd, 0xb3, 0x55, 0xe3, 0x21, 0x11, 0x99, 0xa6, 0x3c, 0xd8, 0x1d, 0x0b, 0x87, 0x00, 0x8a, 0x14, 0x93, 0x7b, 0xef, 0x8b, 0x02, 0x46, 0x52, 0x43, 0xd6, 0xa7, 0x46, 0x32, 0x00, 0x94, 0xc2, 0x75, 0xe1, 0xf1, 0xf3, 0x8e, 0x82, 0xff, 0x00, 0x91, 0x02, 0xa3, 0x49, 0xf6, 0x76, 0xc4, 0x15, 0x36, 0xd8, 0x3b, 0x82, 0xb4, 0xfa, 0xc9, 0x39, 0x4a, 0xa8, 0x9f, 0x01, 0x9f, 0x3b, 0xe3, 0x79, 0x20, 0x45, 0x66, 0x4b, 0x1b, 0x6b, 0xd6, 0x6c, 0x0e, 0x91, 0xe5, 0x17, 0xf3, 0xf7, 0xf3, 0x6f, 0xa9, 0x64, 0x68, 0x20, 0x97, 0x5c, 0x19, 0x11, 0xac, 0x52, 0x1c, 0x42, 0xbd, 0x9a, 0xe1, 0xbc, 0x6d, 0xc7, 0x1d, 0xb9, 0x6e, 0x79, 0xc8, 0x02, 0x02, 0x3a, 0x8e, 0x5f, 0xe7, 0xac, 0x2a, 0xda, 0x34, 0x29, 0xe2, 0xb5, 0x8d, 0xea, 0x20, 0x29, 0x74, 0x2d, 0x19, 0x5f, 0xce, 0x52, 0xef, 0x96, 0x7d, 0x0e, 0xc0, 0x71, 0x5e, 0x71, 0xa0, 0xa4, 0x30, 0x22, 0x63, 0x7f, 0xb7, 0xc6, 0x24, 0x70, 0x28, 0xcb, 0x10, 0x27, 0xe0, 0x3e, 0xcc, 0x5c, 0x03, 0x00, 0xd5, 0x50, 0x4d, 0x4a, 0x7e, 0x47, 0x47, 0x08, 0xbc, 0xda, 0x4a, 0x5b, 0xcd, 0x22, 0x37, 0xc1, 0xd7, 0x03, 0x64, 0xbe, 0x54, 0xc1, 0xcb, 0x7e, 0xf2, 0x3a, 0x79, 0x0b, 0x84, 0xb8, 0x77, 0x18, 0x89, 0x00, 0x43, 0xa8, 0x97, 0xdf, 0x08, 0x56, 0x4f, 0xc7, 0x32, 0xa4, 0x7c, 0x66, 0x30, 0x25, 0xa8, 0x3b, 0xec, 0x9c, 0x74, 0x3b, 0x07, 0x98, 0xd5, 0xe3, 0x3d, 0x5e, 0xb8, 0x69, 0x93, 0xdb, 0xa2, 0x19, 0xe8, 0x97, 0x90, 0x6b, 0x1e, 0xb9, 0x42, 0x3e, 0xb0, 0xb8, 0x1f, 0x5c, 0xbd, 0xbc, 0x94, 0x97, 0x2f, 0x1f, 0xbf, 0x5e, 0x70, 0x3a, 0x9a, 0x06, 0xbb, 0x9a, 0xbb, 0x7f, 0xd6, 0x47, 0xe4, 0x7a, 0xb4, 0xfe, 0xbf, 0x38, 0x8c, 0x03, 0xe7, 0x14, 0xd3, 0xc9, 0x11, 0xea, 0x21, 0x76, 0xbc, 0xe4, 0xeb, 0x0e, 0x40, 0x53, 0x49, 0xc4, 0xeb, 0x75, 0x24, 0x1a, 0xf8, 0xdb, 0xe3, 0x26, 0x64, 0xa3, 0x42, 0x18, 0x91, 0xd0, 0x3f, 0x8c, 0x3c, 0x22, 0x71, 0x73, 0x0c, 0x3c, 0xf4, 0xfa, 0xba, 0x65, 0xbc, 0x14, 0xd2, 0x37, 0x73, 0xdc, 0xff, 0x00, 0xac, 0x6c, 0x4d, 0xb3, 0xd0, 0x52, 0x3a, 0x11, 0xcf, 0x7c, 0x8e, 0x3d, 0xc6, 0xb4, 0x17, 0xd3, 0xeb, 0x10, 0x88, 0x5b, 0x7c, 0x19, 0x0a, 0x30, 0x54, 0x42, 0xa2, 0x53, 0x55, 0x3f, 0x31, 0x9a, 0xe8, 0x4e, 0x09, 0xf0, 0xbb, 0x88, 0x7b, 0x34, 0xa5, 0xc8, 0x25, 0x41, 0x74, 0xed, 0x85, 0xca, 0x44, 0x36, 0x6a, 0x1d, 0xb7, 0xc1, 0xff, 0x00, 0x84, 0x45, 0x3d, 0x6c, 0x07, 0x75, 0xb6, 0xf1, 0x26, 0xc8, 0x11, 0x34, 0x6d, 0x3b, 0xbe, 0x5c, 0x82, 0x2d, 0xa6, 0x44, 0x80, 0xda, 0xbc, 0x48, 0xee, 0xde, 0x65, 0xc8, 0xdc, 0x65, 0x48, 0x42, 0x59, 0xe7, 0x00, 0xf5, 0xac, 0xac, 0xa7, 0xf7, 0x3f, 0x19, 0xf4, 0xf2, 0x69, 0xdd, 0x7e, 0x71, 0xc1, 0x6d, 0x16, 0xc1, 0x17, 0xfa, 0xca, 0x09, 0x4e, 0x32, 0x3c, 0x84, 0x53, 0xf5, 0xe3, 0x08, 0x2b, 0x65, 0x4a, 0xa2, 0x7a, 0x4d, 0xb0, 0x9a, 0xc8, 0xc1, 0xba, 0xd1, 0x00, 0x84, 0x71, 0x28, 0x15, 0x24, 0xf4, 0x08, 0xc3, 0x53, 0x35, 0x86, 0x10, 0xd6, 0x58, 0xb9, 0xd7, 0x11, 0x2b, 0x02, 0x59, 0x22, 0x84, 0xda, 0x21, 0xd6, 0xf3, 0xaf, 0xac, 0x99, 0x66, 0x4d, 0xf7, 0xd7, 0xfd, 0xc6, 0x43, 0x26, 0x0c, 0x91, 0x85, 0x3c, 0x8c, 0x74, 0xcd, 0x1e, 0xd5, 0x02, 0xa1, 0xc9, 0x2b, 0x1c, 0xbb, 0xe2, 0x67, 0xa3, 0x00, 0x92, 0xa5, 0x09, 0x74, 0x74, 0x15, 0x1c, 0xe3, 0x9b, 0x09, 0x74, 0x48, 0x99, 0x6a, 0x79, 0xe1, 0xb9, 0xce, 0xda, 0xde, 0x06, 0x5a, 0xb7, 0xe3, 0x8e, 0xd9, 0x1c, 0x4b, 0x01, 0x0c, 0x41, 0x62, 0x62, 0x76, 0xaa, 0x9c, 0x8d, 0x0b, 0x4e, 0xf9, 0x0f, 0xc7, 0x2b, 0xba, 0xc2, 0x1c, 0xa9, 0xa5, 0x4f, 0x30, 0x45, 0xc6, 0x2c, 0x02, 0x26, 0x43, 0x46, 0xea, 0x7f, 0x5d, 0xb1, 0x26, 0x1b, 0x80, 0x44, 0x57, 0xf1, 0x19, 0x6f, 0x06, 0x37, 0x09, 0x82, 0xd3, 0x17, 0x50, 0xb1, 0x41, 0x2f, 0xa3, 0xcf, 0x01, 0x93, 0x82, 0x36, 0x51, 0x28, 0x6e, 0x6c, 0x95, 0x88, 0x38, 0x88, 0x29, 0x66, 0x97, 0x89, 0xc9, 0x57, 0x57, 0x50, 0x9c, 0xba, 0x26, 0x38, 0x4c, 0xe9, 0xc5, 0x62, 0xd6, 0xf7, 0x86, 0x9c, 0x1c, 0x08, 0x2b, 0x6e, 0x52, 0x97, 0x38, 0xc6, 0xbb, 0x48, 0xd7, 0x7b, 0xa9, 0xc9, 0x19, 0x52, 0xd6, 0x46, 0xac, 0xf5, 0x7c, 0xbe, 0xb0, 0x3c, 0x98, 0x0a, 0xa1, 0x02, 0xda, 0x9c, 0x93, 0xe6, 0x31, 0x29, 0xcb, 0x30, 0x16, 0xa8, 0x65, 0x25, 0x1e, 0x94, 0xa1, 0x7a, 0x01, 0x41, 0xf0, 0xb9, 0x12, 0x4e, 0x20, 0xf0, 0xeb, 0xb5, 0x31, 0x09, 0x98, 0xdb, 0xfe, 0x32, 0x90, 0x92, 0x91, 0xe1, 0x2e, 0x22, 0xc9, 0xc3, 0x49, 0xc1, 0xbe, 0xc5, 0x0b, 0x86, 0xf5, 0xf2, 0xb9, 0x81, 0x42, 0xc4, 0xc2, 0x27, 0xb1, 0x1d, 0x6c, 0xae, 0x4c, 0xb7, 0x10, 0xa2, 0x0b, 0x12, 0xdc, 0xfc, 0x57, 0x9c, 0x24, 0xa5, 0x51, 0x24, 0xd3, 0xb3, 0xcc, 0xfc, 0x63, 0xac, 0x69, 0xd2, 0x54, 0x98, 0xa5, 0xbe, 0x9c, 0xb7, 0x52, 0xb6, 0x1d, 0x0f, 0x88, 0x7c, 0x64, 0x90, 0x78, 0x99, 0xdf, 0x04, 0x9e, 0xeb, 0x1f, 0x5d, 0xa9, 0x72, 0x61, 0x55, 0x22, 0xce, 0x43, 0x58, 0xb2, 0x91, 0x24, 0xc0, 0xb9, 0xa3, 0xb7, 0x94, 0x1c, 0x11, 0x82, 0x83, 0x68, 0x6e, 0x9f, 0xd3, 0xe7, 0x08, 0x35, 0xa1, 0x6b, 0xe6, 0x20, 0x6b, 0xe0, 0xf3, 0x59, 0xd2, 0x58, 0x5b, 0x33, 0x93, 0xd8, 0x0f, 0x4c, 0x12, 0x98, 0x44, 0x08, 0x18, 0x4d, 0xd4, 0xec, 0xd2, 0x58, 0xe9, 0xc6, 0x55, 0xe9, 0x37, 0xa0, 0x21, 0xd3, 0x23, 0x12, 0x37, 0x7e, 0x06, 0xbd, 0xe3, 0x25, 0x68, 0x8c, 0xfa, 0xc8, 0x86, 0xf8, 0x7e, 0x72, 0x54, 0xd4, 0x0d, 0x17, 0x12, 0x5e, 0x43, 0x47, 0x39, 0x27, 0xb5, 0x2f, 0x76, 0xe3, 0x92, 0x11, 0xef, 0x08, 0x84, 0xfb, 0x41, 0x0b, 0x8f, 0x6f, 0x8c, 0xeb, 0xb0, 0xa9, 0x21, 0xbd, 0xb2, 0x07, 0xc9, 0x34, 0x01, 0x2c, 0x8c, 0x69, 0x8e, 0x6d, 0x80, 0x01, 0x13, 0x5c, 0x93, 0xed, 0x38, 0x88, 0x6c, 0x41, 0xbb, 0x33, 0xd1, 0xd3, 0x12, 0x9e, 0xf5, 0x67, 0xef, 0x9c, 0x76, 0x7d, 0x62, 0x7d, 0x1a, 0x7a, 0xd5, 0x77, 0x8d, 0xe9, 0xa9, 0xe8, 0x49, 0xa6, 0x64, 0x1c, 0xba, 0xd8, 0x57, 0xc3, 0x5b, 0x1a, 0x87, 0x28, 0x9d, 0x49, 0xc7, 0x63, 0x37, 0xa5, 0xb1, 0x25, 0x53, 0x2b, 0x56, 0xf7, 0x5d, 0x5b, 0x70, 0xa7, 0x5f, 0xd3, 0x32, 0x9a, 0x9f, 0xc7, 0xde, 0x16, 0x22, 0x1d, 0x24, 0xb6, 0xb5, 0x44, 0x4f, 0x7f, 0x78, 0xcc, 0x54, 0x02, 0x00, 0x9e, 0xb3, 0xc8, 0xe6, 0xf1, 0x88, 0x82, 0xbe, 0x07, 0xc3, 0x51, 0x03, 0xcd, 0x1e, 0xc5, 0xc0, 0x4c, 0x5b, 0x08, 0xa0, 0x45, 0x56, 0x97, 0x85, 0xf1, 0x80, 0xc4, 0xf9, 0x80, 0x41, 0xb3, 0x6d, 0x11, 0xa2, 0x30, 0xd6, 0xb0, 0x42, 0xb4, 0xcc, 0x29, 0x09, 0x5f, 0x38, 0xe0, 0xa4, 0xbc, 0xe2, 0xd1, 0xda, 0x5c, 0x00, 0x18, 0xed, 0x10, 0x1a, 0xe8, 0xf3, 0xfb, 0x99, 0xde, 0x48, 0x4a, 0x5d, 0x54, 0x93, 0xb9, 0xf5, 0x90, 0xea, 0x26, 0x42, 0x7b, 0x9e, 0xe7, 0x34, 0x72, 0x82, 0xd0, 0xba, 0x8a, 0xc4, 0x8b, 0x92, 0x55, 0xb8, 0x4b, 0x37, 0x1b, 0xeb, 0x88, 0x33, 0x44, 0xad, 0xfd, 0x5f, 0xd7, 0x39, 0x25, 0x11, 0x81, 0xfd, 0x5e, 0x70, 0x04, 0x9f, 0x0d, 0x40, 0x9e, 0x19, 0x99, 0x88, 0xe8, 0xd3, 0x19, 0xc1, 0x21, 0x9c, 0x03, 0x32, 0x94, 0xf4, 0xd0, 0x60, 0xe1, 0x83, 0xad, 0x34, 0x05, 0x24, 0xc4, 0x54, 0x77, 0x89, 0x76, 0xa9, 0x62, 0x59, 0xd9, 0x68, 0xbb, 0x55, 0x0e, 0x3e, 0x71, 0x53, 0x11, 0x65, 0x58, 0x41, 0x81, 0x98, 0xc1, 0x18, 0x81, 0x1a, 0xe6, 0x75, 0x72, 0xdf, 0xce, 0x38, 0xcf, 0x2d, 0x44, 0x41, 0x25, 0xe3, 0xd5, 0xfb, 0xc5, 0xf2, 0xe2, 0x10, 0x29, 0x88, 0xdb, 0x52, 0xae, 0xd9, 0x2d, 0x11, 0x5c, 0x60, 0x26, 0xe3, 0x65, 0xee, 0xf8, 0x72, 0x22, 0x42, 0x01, 0xcb, 0x4a, 0xda, 0x0d, 0x75, 0xf7, 0x95, 0xd4, 0x1e, 0x80, 0x8d, 0x25, 0xab, 0xd3, 0xae, 0x30, 0xc8, 0x6c, 0xe6, 0x48, 0xfe, 0x71, 0xe0, 0x3b, 0xc6, 0x24, 0x66, 0x0f, 0xa7, 0x04, 0x1c, 0x78, 0x54, 0xee, 0xae, 0xd1, 0x9a, 0x60, 0x99, 0x70, 0x37, 0x3d, 0x3e, 0x03, 0x13, 0x31, 0x10, 0x8b, 0x4b, 0x16, 0x0d, 0xaf, 0x13, 0x79, 0x34, 0xf0, 0xa0, 0xfe, 0xf0, 0x8d, 0x22, 0xc1, 0x0c, 0x11, 0x86, 0x29, 0x67, 0xb2, 0x10, 0xdd, 0x7e, 0x16, 0x63, 0x38, 0x26, 0x44, 0x90, 0x72, 0x40, 0x91, 0x0b, 0x8b, 0xec, 0xe0, 0x56, 0x96, 0x9e, 0x0c, 0x87, 0xb3, 0x4d, 0x69, 0x89, 0x30, 0xd0, 0x5a, 0x22, 0x58, 0x13, 0x88, 0xa6, 0x0f, 0x1c, 0xf6, 0x32, 0xda, 0xcf, 0x00, 0xf4, 0x74, 0x9b, 0x39, 0xd4, 0x56, 0xcc, 0xd9, 0x37, 0x13, 0x68, 0xbd, 0xc5, 0xfc, 0x4b, 0x71, 0x72, 0x66, 0x95, 0x22, 0x66, 0x0b, 0xa0, 0x18, 0x94, 0x71, 0xab, 0x94, 0xb8, 0x33, 0x0d, 0x30, 0x93, 0xba, 0x39, 0xe9, 0xa7, 0x12, 0x67, 0xc2, 0x23, 0x6f, 0xdd, 0x3e, 0xe3, 0xf3, 0x9d, 0x91, 0x03, 0x26, 0x9e, 0x11, 0xcb, 0x9f, 0xce, 0x57, 0x62, 0x22, 0x00, 0x56, 0x9f, 0xd5, 0x39, 0x38, 0xad, 0xa3, 0x36, 0xe9, 0xf4, 0xd9, 0xf9, 0xc1, 0xec, 0x0c, 0x45, 0xb1, 0x96, 0x70, 0xa7, 0xc2, 0x9a, 0x24, 0x20, 0x5c, 0x76, 0x7d, 0x31, 0xc2, 0xe2, 0x2b, 0x21, 0xab, 0xf5, 0xff, 0x00, 0x80, 0x48, 0xe8, 0x2d, 0x7f, 0x4c, 0x95, 0x61, 0x30, 0x2e, 0x66, 0xfa, 0xde, 0x52, 0xb8, 0x5a, 0xb8, 0x23, 0xa7, 0x6c, 0x08, 0x39, 0x80, 0x56, 0x49, 0xa7, 0x8e, 0x98, 0x08, 0x83, 0x47, 0x9f, 0x18, 0x61, 0x0c, 0xef, 0x7c, 0x97, 0xca, 0x72, 0x25, 0x52, 0xc4, 0x9a, 0xe3, 0xf6, 0xe3, 0x80, 0x64, 0xde, 0xe0, 0xcb, 0x5d, 0x17, 0x37, 0xd9, 0x51, 0xbb, 0xf8, 0xc7, 0xe9, 0xf8, 0xff, 0x00, 0x98, 0x2e, 0x42, 0xf5, 0x3f, 0xcc, 0x12, 0x86, 0xe8, 0x19, 0x05, 0x40, 0xc4, 0x2d, 0x71, 0xb7, 0xd1, 0x8e, 0xf4, 0x16, 0x09, 0x3d, 0x13, 0x1d, 0xb2, 0x99, 0x10, 0x71, 0x04, 0xf5, 0xac, 0xff, 0xda, 0x00, 0x0c, 0x03, 0x01, 0x00, 0x02, 0x00, 0x03, 0x00, 0x00, 0x00, 0x10, 0x9c, 0xee, 0xab, 0x04, 0x01, 0x44, 0xb0, 0xdb, 0x70, 0x75, 0x5b, 0x60, 0x56, 0x8a, 0x0c, 0xa8, 0x7a, 0x3e, 0x01, 0x78, 0xa3, 0x42, 0x3c, 0xba, 0xb1, 0xb5, 0x86, 0xbd, 0xab, 0x41, 0x1d, 0xd4, 0x2a, 0xa9, 0x1b, 0xf7, 0x1b, 0x5d, 0xdc, 0x91, 0xb8, 0xde, 0x08, 0x52, 0xff, 0x00, 0x92, 0xe7, 0xdd, 0x65, 0x0d, 0x32, 0x0c, 0x99, 0x03, 0x0e, 0x9d, 0x6f, 0x15, 0x1f, 0x3c, 0x07, 0xf9, 0xee, 0x35, 0x4b, 0xb6, 0xb7, 0x20, 0x32, 0xca, 0xb6, 0x02, 0x46, 0x1b, 0x95, 0x94, 0xf5, 0x97, 0x49, 0x91, 0x78, 0x16, 0xbf, 0xef, 0x3f, 0x80, 0x2b, 0x88, 0xb4, 0x4f, 0x7e, 0x2d, 0x38, 0xba, 0x18, 0xd9, 0xd8, 0x41, 0x72, 0x8b, 0xff, 0xc4, 0x00, 0x27, 0x11, 0x01, 0x00, 0x02, 0x01, 0x02, 0x04, 0x07, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x11, 0x21, 0x31, 0x41, 0x51, 0x61, 0x91, 0xf0, 0x71, 0x81, 0xa1, 0xb1, 0xc1, 0xd1, 0xe1, 0x10, 0xf1, 0x20, 0xff, 0xda, 0x00, 0x08, 0x01, 0x03, 0x01, 0x01, 0x3f, 0x10, 0x16, 0x82, 0x2c, 0x30, 0xdb, 0x77, 0x7e, 0x92, 0x8d, 0xd6, 0xb6, 0x1f, 0xb8, 0x91, 0xc5, 0x0b, 0xd8, 0xc5, 0xd6, 0xf5, 0x79, 0xef, 0x12, 0x80, 0x3e, 0xae, 0x23, 0x8b, 0x8b, 0xf3, 0xa6, 0x60, 0x86, 0x86, 0x6b, 0x7d, 0xd8, 0x37, 0xef, 0x78, 0x2e, 0x6c, 0x3a, 0x70, 0x5e, 0x3c, 0x08, 0xef, 0x28, 0xbe, 0x94, 0xf6, 0xf1, 0x96, 0x18, 0xf5, 0x42, 0x2c, 0x1d, 0x65, 0x6e, 0x1d, 0x62, 0x54, 0xfa, 0xbf, 0x20, 0x36, 0x7a, 0xa5, 0x5b, 0x7a, 0xb2, 0xe5, 0x5f, 0xab, 0xf2, 0x2c, 0xc5, 0x7a, 0xb1, 0x1d, 0xaa, 0x00, 0x9a, 0xcb, 0x2c, 0x1a, 0x10, 0x15, 0x10, 0xd8, 0x57, 0x4f, 0xa8, 0x2f, 0x20, 0x76, 0xd0, 0x94, 0x14, 0x07, 0x94, 0x02, 0xe9, 0x94, 0x86, 0xbe, 0xff, 0x00, 0x70, 0x95, 0x1a, 0xe0, 0x0e, 0xce, 0x1f, 0x90, 0x6a, 0xde, 0x47, 0x52, 0x9d, 0x99, 0xac, 0x62, 0xb8, 0x69, 0xe1, 0x04, 0xd1, 0x03, 0x45, 0xe0, 0xe6, 0x1a, 0x66, 0x94, 0xaa, 0x03, 0x1d, 0xf4, 0x95, 0x6c, 0x03, 0x5e, 0xb1, 0x20, 0xe8, 0xd6, 0xc5, 0xe3, 0x92, 0xdf, 0xa6, 0x91, 0x5a, 0xaf, 0x68, 0xb0, 0x6a, 0x55, 0x12, 0x70, 0xf9, 0x94, 0x17, 0x07, 0x44, 0x61, 0xb4, 0x35, 0x63, 0xa4, 0x22, 0x9f, 0x74, 0xf6, 0x8a, 0x1b, 0x43, 0x99, 0xdc, 0xe6, 0xfb, 0xc0, 0xb2, 0x98, 0x08, 0x09, 0xe1, 0xee, 0x43, 0x8b, 0xb8, 0x4a, 0xe0, 0xf9, 0xfc, 0x88, 0x1a, 0xf4, 0x7a, 0x46, 0xc9, 0xec, 0xcc, 0xbb, 0x37, 0x35, 0x98, 0x1c, 0xff, 0x00, 0x3b, 0xe5, 0x07, 0x0c, 0xce, 0x77, 0x0f, 0x99, 0xa2, 0x0c, 0x75, 0x9c, 0x3f, 0x9b, 0x4c, 0xc9, 0x97, 0x73, 0x52, 0x52, 0x9b, 0x4c, 0x15, 0x15, 0xc3, 0x5e, 0xf3, 0x11, 0x51, 0xd7, 0x26, 0x7f, 0x73, 0xce, 0xff, 0x00, 0x35, 0x24, 0x58, 0x06, 0x6b, 0xe9, 0xf9, 0xa9, 0x64, 0x2d, 0x0a, 0xef, 0xfd, 0xd3, 0x10, 0x05, 0x05, 0x32, 0x86, 0x02, 0x86, 0x25, 0xeb, 0x72, 0xf9, 0x8a, 0x9a, 0x7f, 0x1e, 0x30, 0x65, 0xff, 0x00, 0x32, 0x42, 0x5d, 0xb8, 0x31, 0x59, 0xa3, 0x1a, 0x35, 0x7a, 0x9c, 0x23, 0x48, 0x3a, 0xc3, 0xe8, 0x69, 0xac, 0x31, 0xa2, 0xbf, 0x38, 0x78, 0xe9, 0x13, 0x28, 0xdf, 0x0c, 0x2e, 0xb8, 0xc3, 0xce, 0x2b, 0x03, 0x2e, 0x6a, 0xa0, 0x08, 0xd6, 0x13, 0xdc, 0xb8, 0x13, 0x11, 0x8d, 0x5f, 0xa8, 0xb4, 0x04, 0xa2, 0xa9, 0x5d, 0x35, 0xd6, 0x15, 0x90, 0xcc, 0x62, 0x78, 0x7c, 0xc0, 0x61, 0xbc, 0x08, 0x0c, 0xa7, 0x8f, 0xdc, 0xb7, 0xa4, 0x5d, 0x0c, 0x08, 0xeb, 0x1f, 0x30, 0xdc, 0xf6, 0x79, 0x72, 0xda, 0x06, 0x35, 0x34, 0xd0, 0x79, 0xc7, 0x51, 0x40, 0x6b, 0xc7, 0x57, 0xa2, 0x4b, 0x0e, 0x44, 0xd2, 0x3a, 0xfb, 0x45, 0xdc, 0x91, 0x6c, 0xc6, 0x65, 0xac, 0xcb, 0x8c, 0x86, 0xec, 0xb2, 0xfe, 0x77, 0x98, 0x99, 0x6d, 0xf4, 0xf8, 0x62, 0x86, 0x8a, 0xc7, 0xcf, 0xc9, 0xf5, 0xac, 0x0a, 0x31, 0x2b, 0x2b, 0xe0, 0x7c, 0xff, 0x00, 0x31, 0x17, 0xa7, 0x5d, 0x3e, 0x99, 0xbe, 0x2b, 0xcb, 0xea, 0x2e, 0x17, 0x74, 0xd2, 0x10, 0x33, 0xe8, 0x7d, 0x44, 0xe8, 0xbd, 0x3e, 0xa1, 0xf6, 0x3e, 0x37, 0xdf, 0x38, 0xf2, 0xa5, 0xe6, 0x51, 0x51, 0xef, 0xca, 0x2b, 0x07, 0xfe, 0x33, 0xb9, 0x8f, 0xf0, 0x99, 0xf5, 0x5d, 0xd4, 0x4c, 0x98, 0x38, 0xb1, 0x56, 0x14, 0x9c, 0xef, 0x6f, 0xd2, 0x14, 0x96, 0x31, 0xad, 0x65, 0xd3, 0xe7, 0xfa, 0x19, 0x8a, 0xdc, 0x26, 0xad, 0xa3, 0xb5, 0xb0, 0x12, 0xd5, 0x74, 0xbf, 0x46, 0x1d, 0x2a, 0x6d, 0xc3, 0xba, 0xc4, 0xad, 0xe1, 0x1a, 0x7b, 0xbc, 0xf8, 0x4c, 0x45, 0xff, 0x00, 0x09, 0x15, 0xae, 0x9b, 0xee, 0x1a, 0x19, 0xbc, 0xe8, 0x13, 0x27, 0x22, 0xad, 0x41, 0xd6, 0xab, 0xbc, 0x4a, 0xb7, 0x6f, 0xd1, 0x8a, 0x9e, 0xf6, 0xfb, 0x96, 0x32, 0xd9, 0xc7, 0xf6, 0xf1, 0xce, 0x2c, 0x55, 0xea, 0xd3, 0x89, 0xdf, 0x48, 0x98, 0x6f, 0xa5, 0xf3, 0xfc, 0x12, 0x89, 0xd6, 0x2d, 0xa5, 0x28, 0x97, 0x00, 0xc4, 0x48, 0x07, 0x6f, 0x26, 0x04, 0xad, 0x39, 0x3c, 0xb9, 0x68, 0x17, 0xe7, 0x31, 0xc8, 0x78, 0xb9, 0xe3, 0x9e, 0x14, 0x75, 0x67, 0x1c, 0x0f, 0x87, 0x43, 0xf3, 0x8c, 0xa5, 0x6b, 0xd6, 0x54, 0x72, 0x01, 0x66, 0x72, 0x70, 0xd2, 0x04, 0x5b, 0x0d, 0x28, 0xa3, 0x86, 0xdd, 0xb1, 0xa1, 0x15, 0x5f, 0x2b, 0xf0, 0xf5, 0x62, 0x30, 0x52, 0xbd, 0x2e, 0xf9, 0xd7, 0xa7, 0x49, 0x80, 0x03, 0x68, 0xd7, 0xbe, 0x7e, 0xa7, 0xe4, 0xac, 0x01, 0x8b, 0x97, 0xcf, 0xf0, 0xee, 0xa2, 0xbc, 0x7e, 0x23, 0x16, 0xb7, 0x5f, 0xa9, 0x62, 0x5c, 0x78, 0xdf, 0x3e, 0x5e, 0x70, 0xef, 0x4e, 0x59, 0xf9, 0xcc, 0xc0, 0x6a, 0xe0, 0x8d, 0xd7, 0x8c, 0x52, 0xc7, 0x01, 0x40, 0x37, 0xf5, 0x3c, 0xb6, 0xc4, 0x54, 0xdf, 0x69, 0x69, 0xa7, 0x0e, 0x1e, 0x7c, 0x6a, 0x04, 0x1b, 0x75, 0xa5, 0xf8, 0x7b, 0x79, 0x92, 0xbc, 0xe2, 0xab, 0xd7, 0x49, 0x9a, 0xbf, 0x8c, 0xde, 0xbd, 0x10, 0x6d, 0xa1, 0xb3, 0x9c, 0x42, 0x89, 0x8f, 0x13, 0xde, 0x0b, 0xd0, 0x2e, 0x6f, 0x3b, 0x04, 0xbb, 0x09, 0x1d, 0x28, 0xa3, 0x1c, 0x35, 0xf3, 0x9a, 0x4c, 0x0e, 0x6e, 0x5e, 0xdf, 0xcd, 0x11, 0x21, 0x69, 0x98, 0x0b, 0x0e, 0x9f, 0xa4, 0xbe, 0x9b, 0x15, 0x9c, 0xd4, 0x45, 0xc4, 0x21, 0xc5, 0xd9, 0x58, 0x31, 0xce, 0xab, 0x9c, 0x16, 0x53, 0x1a, 0xb3, 0x8e, 0x5d, 0x4c, 0xe8, 0x59, 0xe3, 0x29, 0x80, 0x86, 0xdc, 0xb6, 0xdf, 0xc6, 0x2b, 0x92, 0xbd, 0xf4, 0xef, 0x68, 0x3b, 0xa5, 0x02, 0x57, 0x3c, 0x3a, 0xd1, 0xf9, 0x32, 0x1a, 0x74, 0xa7, 0x26, 0xa5, 0x73, 0xe5, 0x28, 0x1a, 0x12, 0xcb, 0xb7, 0x9d, 0x7b, 0x44, 0xd4, 0x39, 0x95, 0xed, 0xf9, 0x58, 0x09, 0x90, 0x05, 0x9a, 0x36, 0x1e, 0xe9, 0xa6, 0x8f, 0x1d, 0xb1, 0x98, 0xdd, 0x64, 0x60, 0xcf, 0xc7, 0xec, 0x16, 0x22, 0xfd, 0xb0, 0xca, 0x82, 0x3b, 0x1c, 0xbd, 0xbf, 0x81, 0x61, 0x2a, 0xb7, 0x8c, 0x16, 0x4f, 0x79, 0x25, 0x04, 0x30, 0xf1, 0xcf, 0xb4, 0x40, 0x85, 0x07, 0x14, 0xd9, 0x9d, 0xef, 0x7b, 0xda, 0x38, 0x1c, 0x9d, 0xd4, 0x38, 0xd7, 0xb4, 0xce, 0x83, 0xcb, 0x94, 0x35, 0x22, 0xfa, 0xf9, 0xde, 0xbe, 0xb3, 0x18, 0x7a, 0x6b, 0x9d, 0x52, 0x52, 0xd5, 0x6e, 0xf4, 0xc6, 0x9a, 0xba, 0xeb, 0xde, 0xb1, 0xac, 0x74, 0x6f, 0xbe, 0xf6, 0xe7, 0x28, 0x16, 0x67, 0x95, 0xe3, 0xd7, 0xd6, 0x22, 0xe8, 0x7c, 0xb3, 0xed, 0x10, 0x1e, 0x9c, 0x79, 0x79, 0xc7, 0x54, 0x6b, 0x7c, 0x6f, 0x4e, 0x7e, 0x77, 0x30, 0x58, 0x8e, 0x6e, 0x5e, 0xdf, 0xc7, 0x82, 0x23, 0xb2, 0x54, 0x68, 0xae, 0x13, 0x11, 0xd7, 0x24, 0x70, 0x0f, 0x9b, 0x50, 0x82, 0x41, 0xe2, 0xec, 0xdf, 0xc4, 0x01, 0x17, 0x76, 0xef, 0x1a, 0xf9, 0xf1, 0xe1, 0x9a, 0xbb, 0x56, 0xb5, 0x79, 0x6a, 0xae, 0x9a, 0xdb, 0x5e, 0x7b, 0xf5, 0x8b, 0x94, 0x57, 0x40, 0xb2, 0xdc, 0x2d, 0x69, 0x30, 0xde, 0x76, 0xde, 0x54, 0xb0, 0xe3, 0x0e, 0x4f, 0x88, 0x15, 0x41, 0x7c, 0xb9, 0xf8, 0xd6, 0x9c, 0x73, 0x19, 0x98, 0x7a, 0x07, 0xb3, 0x00, 0xbc, 0x77, 0xed, 0x04, 0x5d, 0x17, 0x7d, 0xdd, 0x15, 0xde, 0xda, 0x4b, 0x38, 0xfa, 0xfb, 0x68, 0x72, 0x84, 0xac, 0x68, 0x75, 0xfc, 0x1d, 0x7b, 0x4e, 0x73, 0xd6, 0x04, 0x6c, 0xea, 0x7e, 0x47, 0x51, 0xd4, 0xfc, 0x89, 0x5a, 0xef, 0xc7, 0xf2, 0x64, 0x2d, 0xeb, 0x1b, 0xaa, 0xde, 0xb3, 0xc6, 0xeb, 0x37, 0x17, 0xd6, 0x2d, 0xe3, 0xa4, 0x5c, 0x69, 0x5a, 0x7d, 0xdc, 0xd1, 0x57, 0xac, 0xa6, 0xf8, 0xb3, 0xe7, 0xdf, 0xfb, 0x0a, 0xab, 0x9e, 0x7f, 0x92, 0x9b, 0xaf, 0x58, 0x5a, 0xb5, 0xea, 0xc0, 0x15, 0x0a, 0x60, 0xd1, 0x51, 0xa5, 0xb6, 0x7f, 0xff, 0xc4, 0x00, 0x26, 0x11, 0x01, 0x00, 0x02, 0x01, 0x01, 0x07, 0x05, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x11, 0x21, 0x31, 0x41, 0x51, 0x61, 0x71, 0x81, 0x91, 0xd1, 0x10, 0xa1, 0xc1, 0xe1, 0xf0, 0xb1, 0xf1, 0xff, 0xda, 0x00, 0x08, 0x01, 0x02, 0x01, 0x01, 0x3f, 0x10, 0xd0, 0x62, 0x2a, 0x8c, 0x26, 0xc2, 0x9e, 0x91, 0x59, 0x2f, 0xb1, 0x39, 0xbd, 0x88, 0xa3, 0x6f, 0xb1, 0xe2, 0x73, 0x7f, 0x74, 0x81, 0x7a, 0x81, 0xbb, 0xe9, 0xca, 0x72, 0x7b, 0x7d, 0xcb, 0x37, 0x76, 0x7c, 0xce, 0x47, 0x67, 0xcc, 0x78, 0x5d, 0xbe, 0xe5, 0xe6, 0xcf, 0xdd, 0x65, 0x5b, 0xbd, 0xfc, 0xce, 0x57, 0xbf, 0x99, 0xcb, 0xf7, 0xf3, 0x05, 0xdd, 0xef, 0xe6, 0x01, 0xa9, 0x11, 0x96, 0x80, 0xf7, 0x8a, 0xad, 0x73, 0xbe, 0xd3, 0xf9, 0x2b, 0xa1, 0x9e, 0x6c, 0x37, 0x33, 0x14, 0xd9, 0x28, 0x2c, 0x25, 0x1d, 0x13, 0x0a, 0xa5, 0xd8, 0x73, 0xfe, 0x12, 0xa0, 0xa6, 0x08, 0x2d, 0xd4, 0x56, 0x58, 0x99, 0x25, 0xe1, 0x65, 0xaf, 0x1f, 0xdb, 0x65, 0x89, 0xaa, 0xb9, 0xd7, 0x7a, 0xa8, 0x10, 0xbc, 0x4d, 0x1a, 0xbd, 0x26, 0xc8, 0xde, 0x08, 0x54, 0xac, 0xa0, 0xd2, 0x2a, 0xe5, 0x1e, 0x04, 0x23, 0x4e, 0x8f, 0x31, 0x02, 0xb5, 0xa7, 0xe2, 0x03, 0x98, 0x20, 0xc1, 0x1b, 0xa8, 0x9c, 0x60, 0x59, 0x1a, 0x4a, 0x66, 0xc1, 0xd8, 0xce, 0x30, 0x6d, 0x86, 0xb5, 0x53, 0x96, 0xc1, 0x17, 0x97, 0xd1, 0xf4, 0x6a, 0x15, 0x01, 0xca, 0x39, 0x1c, 0xbc, 0xcb, 0x77, 0xbe, 0x20, 0xb5, 0x83, 0xd3, 0x36, 0xcc, 0x02, 0xe2, 0x56, 0x2e, 0x25, 0xa1, 0x99, 0xcc, 0x8f, 0xc1, 0x01, 0x3b, 0x62, 0xa6, 0xa1, 0x57, 0xac, 0xd9, 0xb3, 0x82, 0x15, 0x46, 0xb7, 0x28, 0x3d, 0x98, 0x56, 0xe4, 0x6d, 0xaf, 0xa2, 0x2d, 0xa8, 0xe2, 0x62, 0x56, 0x65, 0xcb, 0x0e, 0xc8, 0x96, 0x39, 0x33, 0x28, 0x94, 0x69, 0x00, 0x34, 0x45, 0x20, 0xa9, 0xaf, 0xf2, 0x50, 0x2a, 0xf3, 0x2f, 0x52, 0x59, 0x1a, 0xde, 0x7f, 0x23, 0x17, 0x17, 0xfe, 0x43, 0x46, 0x93, 0x8e, 0xbd, 0x65, 0xe7, 0x38, 0x6f, 0x96, 0xd0, 0xac, 0x10, 0xda, 0x80, 0x8f, 0x7f, 0x7c, 0x31, 0x24, 0x47, 0xa1, 0xe6, 0x01, 0x78, 0x76, 0x88, 0x8b, 0x19, 0x50, 0x90, 0x1b, 0x99, 0x9d, 0x46, 0xff, 0x00, 0xe4, 0x0a, 0xd5, 0xb6, 0x2d, 0x69, 0x80, 0x37, 0x71, 0xde, 0x4a, 0xb6, 0xca, 0x04, 0x48, 0x4c, 0xd4, 0x05, 0x59, 0x33, 0x60, 0x3f, 0x12, 0xca, 0x6d, 0x56, 0x91, 0x36, 0x19, 0xc1, 0x1a, 0x44, 0xe4, 0x56, 0xdc, 0x0f, 0xf4, 0x86, 0xd9, 0x7e, 0xe5, 0x15, 0xb5, 0xed, 0xe2, 0x59, 0xb7, 0xed, 0xe2, 0x57, 0xb1, 0x5e, 0x9b, 0x3c, 0x40, 0xda, 0x5f, 0x4a, 0xf1, 0x05, 0xdc, 0xbd, 0x3c, 0x7c, 0xcc, 0x71, 0x26, 0x9f, 0x46, 0x54, 0x1c, 0xa4, 0x2a, 0xc1, 0xbf, 0xcc, 0x71, 0x6c, 0xd9, 0x4a, 0x57, 0x48, 0xdc, 0x98, 0xc1, 0xea, 0x6d, 0x59, 0x01, 0x07, 0x13, 0x5b, 0xc5, 0x44, 0x37, 0x44, 0xa1, 0xb5, 0x69, 0xde, 0x1a, 0x97, 0x59, 0x9a, 0x59, 0xb7, 0xfb, 0xfb, 0xc6, 0xeb, 0xd1, 0xe9, 0x70, 0xc4, 0x18, 0x0a, 0xa4, 0x73, 0x5c, 0xdb, 0xf5, 0x12, 0xf4, 0x1a, 0xbc, 0xef, 0xff, 0x00, 0x18, 0x48, 0x15, 0x4f, 0xaf, 0x32, 0x81, 0xcb, 0x28, 0x50, 0xde, 0x0f, 0x43, 0x3d, 0x22, 0xd3, 0x9f, 0x18, 0xac, 0xb9, 0x77, 0x64, 0x51, 0x18, 0x63, 0x57, 0xf9, 0xa4, 0x08, 0xc3, 0x1a, 0xd7, 0x74, 0x5b, 0x05, 0x8f, 0x6f, 0xa9, 0xa2, 0x5c, 0x69, 0x23, 0x58, 0x4b, 0x37, 0x5f, 0x58, 0xd9, 0x61, 0x50, 0xcc, 0x3b, 0xcc, 0xdb, 0xbc, 0x7c, 0xcc, 0xc5, 0xdb, 0x37, 0x1e, 0x8d, 0xb1, 0x57, 0x2f, 0x98, 0x6f, 0xc7, 0x5f, 0x28, 0x01, 0xab, 0xf3, 0x9c, 0x2b, 0x60, 0x1d, 0xf5, 0xf0, 0xb2, 0xd2, 0xfc, 0xa5, 0x1b, 0x38, 0x6a, 0xc7, 0xa3, 0xde, 0x0e, 0x6b, 0x2b, 0x2e, 0xb6, 0xbd, 0x33, 0x1a, 0x6a, 0x4e, 0x49, 0x86, 0xa4, 0x01, 0x69, 0xc2, 0x40, 0xe9, 0x1d, 0x56, 0x66, 0x78, 0x09, 0xb3, 0x5d, 0x7a, 0x12, 0xf3, 0x57, 0x08, 0x35, 0xfe, 0xb7, 0xd2, 0xd6, 0x08, 0x2a, 0x39, 0x7a, 0x0b, 0x68, 0xc1, 0x7c, 0x73, 0x01, 0x58, 0xe9, 0xfb, 0x7c, 0x40, 0xed, 0x71, 0x80, 0x54, 0xd7, 0x5e, 0x23, 0x81, 0x34, 0x77, 0x97, 0xf2, 0x42, 0xa2, 0x3c, 0x33, 0xf5, 0x1b, 0x87, 0x7b, 0xe0, 0x89, 0x9b, 0xb3, 0xc7, 0x8f, 0x08, 0x30, 0x08, 0x9b, 0xca, 0x58, 0x10, 0xd7, 0x49, 0x95, 0xb9, 0xa8, 0xd9, 0xba, 0xc4, 0xd6, 0xc5, 0x7f, 0xac, 0x74, 0x88, 0xbb, 0xbe, 0x36, 0xd2, 0x23, 0x86, 0x66, 0xf3, 0x47, 0x62, 0x99, 0xe5, 0x06, 0xca, 0x0a, 0x21, 0x68, 0x22, 0xbe, 0x89, 0xb6, 0xdf, 0xdf, 0xbc, 0x47, 0x02, 0xfe, 0xf8, 0x88, 0x61, 0xd7, 0x64, 0x5a, 0x11, 0x6b, 0x4d, 0x6f, 0x6b, 0x2c, 0x67, 0x2d, 0x9a, 0x3e, 0x22, 0x41, 0xfb, 0x8f, 0x98, 0x24, 0xf9, 0xd7, 0x1c, 0xe6, 0x86, 0xf4, 0x9b, 0x1b, 0xcc, 0x62, 0xba, 0xbf, 0xd7, 0xd2, 0xa0, 0x5a, 0xc3, 0x48, 0xcd, 0xf3, 0x14, 0x51, 0x96, 0x69, 0x0d, 0x61, 0x97, 0x8e, 0xd8, 0x3b, 0xce, 0x4a, 0xad, 0xda, 0x59, 0xf7, 0x01, 0xb1, 0x6c, 0x36, 0x70, 0xe3, 0xc7, 0xae, 0x76, 0x10, 0x35, 0xe8, 0xb4, 0xc7, 0x76, 0x00, 0x3a, 0x0e, 0xb8, 0xe4, 0x40, 0x11, 0x79, 0x34, 0xc2, 0x0c, 0x9f, 0xbb, 0x4b, 0xbf, 0xbe, 0xa0, 0x45, 0x73, 0x49, 0x0c, 0x6f, 0x61, 0x03, 0x71, 0xfb, 0xf7, 0x59, 0x9b, 0xe1, 0x1b, 0x6a, 0x33, 0xc3, 0x9b, 0xe9, 0x7c, 0xb0, 0xad, 0xd5, 0xe1, 0x97, 0x3e, 0x8f, 0x12, 0xdb, 0xfd, 0x8f, 0x12, 0xd7, 0xaf, 0xdb, 0xc4, 0x1e, 0xff, 0x00, 0xb7, 0x89, 0xcf, 0xf6, 0x82, 0xda, 0xe0, 0xea, 0x1c, 0xcf, 0x6f, 0x10, 0x3c, 0x8b, 0x2b, 0xbd, 0x07, 0x6a, 0xef, 0x38, 0x8e, 0xe7, 0x89, 0x57, 0xc8, 0x78, 0x9c, 0x47, 0xdb, 0xc4, 0x06, 0x05, 0xde, 0x6a, 0xbb, 0x85, 0x98, 0xeb, 0xfb, 0xe6, 0x7f, 0xff, 0xc4, 0x00, 0x25, 0x10, 0x01, 0x01, 0x01, 0x00, 0x02, 0x03, 0x00, 0x02, 0x02, 0x02, 0x03, 0x01, 0x00, 0x00, 0x00, 0x00, 0x01, 0x11, 0x21, 0x00, 0x31, 0x41, 0x51, 0x61, 0x71, 0x81, 0x91, 0xa1, 0xc1, 0xf0, 0xb1, 0xd1, 0xe1, 0xf1, 0xff, 0xda, 0x00, 0x08, 0x01, 0x01, 0x00, 0x01, 0x3f, 0x10, 0x08, 0xf4, 0x85, 0x2f, 0xc0, 0x7b, 0xe2, 0xb2, 0xb1, 0x50, 0x8b, 0x83, 0xb0, 0xc0, 0x28, 0x79, 0xfb, 0xc2, 0x5b, 0x76, 0x9a, 0x0c, 0x5a, 0x04, 0x29, 0x2b, 0x8c, 0xe2, 0xe1, 0x51, 0x42, 0xcb, 0x11, 0x0b, 0xb9, 0x0d, 0xf9, 0xc1, 0xa4, 0x18, 0x1a, 0xa2, 0xd2, 0x3a, 0x37, 0xae, 0xdd, 0x57, 0x8c, 0x81, 0x67, 0x60, 0x11, 0xbe, 0x55, 0x7d, 0x08, 0xb2, 0xf2, 0x4d, 0x4d, 0x03, 0xfe, 0x02, 0xb4, 0xec, 0x40, 0xec, 0x0a, 0xa7, 0x0a, 0x06, 0x9d, 0x31, 0x32, 0xfd, 0xbe, 0x27, 0x1a, 0x92, 0xc0, 0xef, 0xf6, 0xe1, 0xf5, 0xe2, 0x6d, 0xa7, 0x23, 0x03, 0x40, 0x58, 0xd5, 0xec, 0xa8, 0x15, 0x1e, 0x9b, 0x68, 0x7c, 0x07, 0xb0, 0x19, 0x4e, 0xbf, 0xcb, 0x38, 0x94, 0x47, 0x2d, 0xc4, 0xd3, 0x0f, 0x26, 0x58, 0x53, 0x70, 0xf2, 0xdc, 0xa2, 0x21, 0xa9, 0x83, 0x1d, 0x79, 0x4c, 0x13, 0xe0, 0xcf, 0xcd, 0x79, 0x61, 0x11, 0x22, 0xe8, 0x7c, 0xe1, 0xd0, 0xe1, 0xeb, 0x0f, 0xef, 0x80, 0x52, 0x60, 0x70, 0x77, 0xd9, 0x19, 0xad, 0x0c, 0xea, 0xa8, 0x9d, 0x11, 0x11, 0xd3, 0xee, 0x80, 0x40, 0xba, 0x3c, 0xd8, 0xa7, 0x9b, 0xb3, 0x48, 0x8a, 0x43, 0x5e, 0x9d, 0x79, 0x87, 0x2a, 0x2a, 0x89, 0x1c, 0x11, 0x3a, 0xaf, 0xbc, 0xe4, 0xf0, 0x6f, 0xe5, 0x67, 0xb0, 0x85, 0x67, 0xfd, 0x5e, 0x15, 0x85, 0x7a, 0x06, 0x01, 0x50, 0x35, 0xfc, 0xd7, 0xdf, 0x1f, 0x7e, 0x54, 0xe4, 0xe9, 0xe0, 0x13, 0x54, 0x95, 0x7a, 0x7f, 0x23, 0x40, 0x1c, 0x05, 0x25, 0x5c, 0x76, 0x43, 0xed, 0xbf, 0x61, 0x86, 0x14, 0xbc, 0x3e, 0x8f, 0x74, 0xfd, 0xbf, 0x1c, 0x39, 0x7e, 0x93, 0x26, 0xe1, 0x43, 0x20, 0x4f, 0x5a, 0xae, 0x64, 0xbb, 0x05, 0x3a, 0x81, 0xd4, 0x14, 0xe8, 0x38, 0x8d, 0x07, 0x51, 0x54, 0xe9, 0x14, 0xf1, 0xdd, 0xde, 0x38, 0x50, 0x3e, 0x28, 0x14, 0x17, 0x4d, 0xd0, 0x8c, 0xe3, 0x37, 0x62, 0xb0, 0x01, 0xd7, 0xb5, 0x14, 0xf6, 0x9e, 0xf9, 0x67, 0x48, 0x12, 0x02, 0xcc, 0x5a, 0xad, 0x17, 0xba, 0xf0, 0xf4, 0x94, 0x12, 0xd1, 0x02, 0xd1, 0x7b, 0x74, 0x4f, 0x0f, 0x27, 0x81, 0x5c, 0x9d, 0xf4, 0x0b, 0xd6, 0x85, 0x63, 0x68, 0xbb, 0x5e, 0x09, 0x28, 0x68, 0xd3, 0x40, 0xa2, 0x04, 0x11, 0x64, 0x45, 0x12, 0xa2, 0x07, 0xd0, 0xfc, 0x09, 0x02, 0xbf, 0x37, 0x25, 0xbc, 0x0c, 0x8c, 0xb0, 0x68, 0x27, 0x74, 0x44, 0x4f, 0x4f, 0x9e, 0xce, 0x02, 0x8c, 0xce, 0xed, 0x2f, 0x02, 0x27, 0x48, 0x38, 0x6c, 0xe3, 0x32, 0x16, 0x69, 0x18, 0x00, 0xf5, 0x7d, 0x33, 0x87, 0x18, 0x91, 0xfc, 0x54, 0xa6, 0x2a, 0xb7, 0xae, 0x8c, 0xe0, 0x3c, 0x93, 0x4b, 0x86, 0xda, 0x76, 0xfb, 0xdf, 0x20, 0x8a, 0x89, 0xa6, 0x28, 0x6a, 0xac, 0x2a, 0xbc, 0x47, 0x0a, 0x18, 0x34, 0x68, 0x6a, 0xdf, 0x2f, 0x47, 0x0c, 0x5a, 0xa1, 0x43, 0x1a, 0x9d, 0xfd, 0xd7, 0xdf, 0x93, 0x77, 0x94, 0x89, 0x49, 0x92, 0x3b, 0xe9, 0xd7, 0xbf, 0xfe, 0xf1, 0x07, 0x08, 0x84, 0x21, 0xfc, 0xc5, 0x77, 0x4c, 0xea, 0xf0, 0x88, 0x00, 0x27, 0x40, 0xed, 0x35, 0x4a, 0x53, 0x7a, 0x48, 0x53, 0x30, 0x06, 0xba, 0x91, 0x3c, 0x84, 0x0d, 0xe9, 0xfc, 0x41, 0x0c, 0x6f, 0x7f, 0x01, 0x60, 0x5c, 0x7d, 0x0c, 0x40, 0x00, 0x82, 0x11, 0x48, 0x90, 0x6b, 0xd1, 0xcd, 0x56, 0x50, 0x9e, 0xb9, 0x52, 0x04, 0xd4, 0x65, 0x88, 0x48, 0xad, 0x28, 0x49, 0x33, 0xb7, 0x93, 0xbd, 0x32, 0xe6, 0x21, 0x0e, 0xc4, 0xea, 0x4a, 0x1b, 0x43, 0x83, 0xb6, 0x08, 0x10, 0x8d, 0x41, 0x41, 0x2c, 0x3e, 0xe7, 0x1b, 0xf6, 0x32, 0x15, 0x86, 0x49, 0xda, 0x81, 0xdb, 0x6a, 0x6b, 0x99, 0xa2, 0x37, 0x5a, 0x48, 0x30, 0x0b, 0x90, 0x84, 0x54, 0x14, 0x43, 0x08, 0x50, 0x7c, 0x78, 0x75, 0xea, 0x36, 0x1c, 0x45, 0xf3, 0xc5, 0xb1, 0x57, 0x66, 0x8e, 0x9d, 0xa3, 0x7a, 0xe4, 0xc5, 0x03, 0x76, 0x0e, 0x8a, 0x2a, 0x68, 0x7a, 0x8f, 0xcb, 0x93, 0xac, 0x8a, 0x07, 0x20, 0xa7, 0x16, 0x03, 0xe2, 0x1b, 0xc0, 0x18, 0x74, 0xea, 0x46, 0x70, 0x98, 0x0f, 0x30, 0x03, 0x1e, 0x1f, 0x87, 0x5f, 0xe5, 0xe0, 0x6b, 0x92, 0x0a, 0xbb, 0x1d, 0xbf, 0xee, 0xf0, 0xb1, 0x22, 0x4f, 0x67, 0xb7, 0xe7, 0x4f, 0xe3, 0x88, 0xa3, 0x48, 0x1b, 0x08, 0x25, 0x50, 0x7c, 0xf5, 0x9e, 0xd4, 0x0b, 0x01, 0xe4, 0x01, 0x9c, 0x51, 0x44, 0x08, 0x9a, 0xfc, 0xe4, 0x83, 0x00, 0xb0, 0xb7, 0x4d, 0x35, 0x49, 0x7d, 0xf9, 0x71, 0x22, 0x10, 0x10, 0x84, 0xea, 0x00, 0x81, 0xda, 0x0e, 0xa1, 0xc1, 0x1d, 0xb0, 0xc1, 0x96, 0xc0, 0x53, 0xa2, 0x82, 0x6d, 0x28, 0x78, 0xd8, 0xe0, 0x34, 0x28, 0x52, 0xab, 0x2b, 0xc2, 0x10, 0x22, 0x3c, 0x92, 0xb1, 0x84, 0xd1, 0x32, 0x85, 0x90, 0xd6, 0xb7, 0xfc, 0x81, 0x25, 0x28, 0xb5, 0x46, 0xc1, 0x80, 0xcb, 0x44, 0xa2, 0xa3, 0x5d, 0x25, 0x25, 0x9c, 0x08, 0x20, 0xa9, 0x0a, 0x3c, 0x03, 0xcb, 0x2a, 0xf9, 0x8c, 0x95, 0x58, 0x2a, 0xf1, 0x38, 0x9e, 0x60, 0xc6, 0x84, 0xf6, 0x7a, 0x17, 0x84, 0x76, 0xb0, 0x93, 0x63, 0xa9, 0xbf, 0xdf, 0x1c, 0x29, 0x7e, 0x01, 0xbc, 0x4b, 0xde, 0x00, 0x57, 0x44, 0x7d, 0x93, 0x0a, 0x72, 0x2b, 0x9a, 0xe1, 0x36, 0x54, 0x82, 0x81, 0xe3, 0x83, 0x79, 0xd3, 0x88, 0x1a, 0x2d, 0x9b, 0x3f, 0xae, 0xf9, 0x03, 0x46, 0x78, 0xca, 0x30, 0x45, 0x1f, 0x47, 0x9e, 0x41, 0x83, 0x70, 0x43, 0xaf, 0xe3, 0x86, 0xa2, 0x01, 0xaa, 0x17, 0xda, 0x3e, 0x7e, 0xbc, 0x88, 0x6a, 0xf4, 0x0f, 0xfc, 0xe1, 0x85, 0xe6, 0x42, 0xd5, 0xf1, 0x9e, 0xb4, 0x0f, 0x55, 0xde, 0x0b, 0xbf, 0x09, 0x93, 0x49, 0x11, 0xd2, 0x03, 0xca, 0xa4, 0x62, 0xf2, 0x4a, 0xe8, 0x2a, 0xc7, 0x80, 0x93, 0xa3, 0xac, 0x85, 0x17, 0x24, 0x71, 0x45, 0x1e, 0xc1, 0x5b, 0x05, 0xa8, 0x5a, 0xd4, 0x3b, 0x19, 0x86, 0x58, 0x88, 0x9e, 0xe0, 0x74, 0x5e, 0x09, 0x00, 0x08, 0xa0, 0xa4, 0x25, 0xb0, 0x56, 0x90, 0x28, 0x57, 0x90, 0xc1, 0x89, 0x7f, 0x83, 0x8e, 0xdd, 0x5a, 0x3a, 0xb2, 0x71, 0xd4, 0x7d, 0x01, 0x50, 0xc1, 0x53, 0xb8, 0xfc, 0x59, 0xc6, 0x9a, 0xaa, 0x38, 0x15, 0x40, 0x40, 0x32, 0x50, 0xea, 0x29, 0x5e, 0x26, 0xb0, 0xd9, 0xe6, 0x29, 0x08, 0xb3, 0x1a, 0x51, 0x65, 0xe2, 0xf8, 0xca, 0x96, 0x02, 0xed, 0x14, 0x00, 0xa0, 0x4a, 0x17, 0x4f, 0x24, 0xbe, 0xf8, 0x91, 0x18, 0xc5, 0x00, 0x9a, 0x2f, 0x8b, 0xc0, 0x72, 0x65, 0xeb, 0x8a, 0x62, 0xf8, 0x68, 0x48, 0x4e, 0x35, 0x37, 0x44, 0x67, 0xb3, 0x4f, 0x4f, 0x4f, 0x6f, 0x10, 0x3a, 0x26, 0xe9, 0x35, 0x0f, 0x81, 0xc2, 0xb8, 0x73, 0x61, 0xb9, 0x3e, 0xc6, 0x84, 0x58, 0x8a, 0x12, 0xd7, 0x7f, 0x3c, 0xbd, 0x57, 0x55, 0xe2, 0xc9, 0x48, 0xb1, 0x3d, 0xdf, 0x1d, 0xf1, 0x5e, 0x43, 0x33, 0x21, 0x0a, 0x04, 0x5d, 0x6c, 0xf3, 0x4a, 0x59, 0x4e, 0xf8, 0xcc, 0x73, 0x21, 0x8d, 0xbf, 0x5e, 0x46, 0x73, 0x7d, 0x71, 0xc8, 0xba, 0x70, 0xd5, 0xe8, 0x68, 0xf0, 0x7e, 0xaa, 0x1c, 0x1b, 0xd5, 0x16, 0x05, 0x40, 0x7b, 0x10, 0x68, 0xa5, 0x95, 0x65, 0x74, 0x68, 0xe9, 0x75, 0xdb, 0xdf, 0x28, 0x53, 0x81, 0x48, 0xd0, 0x9e, 0x02, 0x99, 0xd0, 0xf9, 0x9c, 0x46, 0x00, 0x18, 0x8a, 0x55, 0x55, 0x50, 0x4b, 0xea, 0xf3, 0x7e, 0xa1, 0x19, 0x52, 0x1a, 0x10, 0xc6, 0xf4, 0x3d, 0x59, 0xc3, 0x80, 0xa3, 0xa7, 0x01, 0xe2, 0xdc, 0x3a, 0x13, 0xcf, 0xbe, 0x4c, 0x42, 0xc9, 0x58, 0x95, 0x0b, 0x40, 0x30, 0xf4, 0x4a, 0x35, 0xeb, 0xd9, 0xec, 0x1b, 0x60, 0x0a, 0xfa, 0x0d, 0xa2, 0x9c, 0x17, 0x7a, 0x90, 0x08, 0x22, 0xc0, 0x10, 0x6e, 0xf0, 0xf0, 0x92, 0x2e, 0xfd, 0x9a, 0x88, 0x51, 0x80, 0x80, 0xd1, 0x7a, 0x67, 0x06, 0x94, 0xc9, 0x2a, 0x96, 0x15, 0x98, 0x91, 0x4b, 0xe1, 0x87, 0x0e, 0x6d, 0x75, 0x42, 0x16, 0xc7, 0x96, 0xd4, 0x3e, 0xb5, 0x3e, 0x95, 0x35, 0x26, 0x2f, 0x0f, 0xf0, 0xd8, 0x01, 0x46, 0x69, 0x5f, 0xe8, 0x6a, 0x51, 0x1a, 0xa0, 0x01, 0x80, 0x20, 0x95, 0x3f, 0x02, 0x2f, 0x7c, 0x76, 0x76, 0x5b, 0xc5, 0x5b, 0x60, 0x60, 0x83, 0x9a, 0x64, 0x0e, 0x2c, 0x9c, 0x91, 0x83, 0x1a, 0x0c, 0xb3, 0xa7, 0xa0, 0x68, 0x62, 0xd4, 0x44, 0x0a, 0x86, 0x18, 0x3d, 0xb2, 0x94, 0xf0, 0xcc, 0x30, 0x8c, 0x6b, 0xeb, 0x08, 0x8b, 0x44, 0x34, 0x7b, 0x70, 0xf4, 0x89, 0x98, 0x0d, 0x08, 0x7e, 0x06, 0x20, 0x3c, 0xa4, 0x31, 0x9a, 0xf0, 0x97, 0x14, 0xd1, 0x6c, 0x83, 0x58, 0x68, 0xb5, 0x30, 0x6c, 0x84, 0x3d, 0x7a, 0x1b, 0xfa, 0xe7, 0x4a, 0x5a, 0x46, 0x0c, 0x36, 0xec, 0x04, 0x9d, 0x93, 0xbe, 0x21, 0x86, 0xc6, 0x9a, 0x0c, 0x34, 0x7a, 0x9f, 0xb8, 0xb5, 0x1a, 0x2a, 0x4d, 0xf0, 0xa7, 0xf2, 0xf2, 0x32, 0xa5, 0x93, 0xa9, 0xe3, 0x00, 0xd1, 0x9d, 0xac, 0xaf, 0x03, 0xa6, 0x81, 0x08, 0x21, 0x80, 0x8e, 0xb4, 0x7a, 0x43, 0x8b, 0x6b, 0x1c, 0x16, 0x32, 0x16, 0x78, 0x15, 0x21, 0x4e, 0x00, 0xe0, 0x7c, 0x88, 0x71, 0xa0, 0xa7, 0x4e, 0x9a, 0x5a, 0x2b, 0xab, 0x77, 0x34, 0xa4, 0x5b, 0x6f, 0x73, 0x27, 0x8b, 0x78, 0xb7, 0x6f, 0x5b, 0x77, 0x14, 0xdf, 0x21, 0x7f, 0xe1, 0x39, 0xfd, 0xaf, 0xfc, 0x72, 0x01, 0x75, 0x75, 0xf6, 0xaa, 0xbc, 0x05, 0x24, 0x6f, 0x46, 0x14, 0x60, 0x97, 0x45, 0x2f, 0x9e, 0x34, 0x10, 0x43, 0xb7, 0x1b, 0x78, 0xb4, 0x19, 0x94, 0x05, 0x02, 0x07, 0x1f, 0x93, 0x56, 0x30, 0xee, 0x11, 0x03, 0x89, 0xc9, 0x47, 0x81, 0x44, 0x48, 0x01, 0x84, 0x90, 0xac, 0xde, 0x0b, 0x4a, 0x1c, 0x25, 0xac, 0xa9, 0x4d, 0x51, 0xd3, 0x2e, 0x4c, 0xe8, 0xb8, 0x85, 0xea, 0xc8, 0xac, 0x1f, 0x01, 0xeb, 0x86, 0x6f, 0x70, 0x38, 0xe0, 0x9d, 0xa2, 0x16, 0xe1, 0xad, 0x08, 0xdd, 0x52, 0xab, 0xed, 0x03, 0x16, 0x97, 0x72, 0x7e, 0xb8, 0xa6, 0xe0, 0xdf, 0x1c, 0x06, 0x14, 0xa6, 0x4d, 0x2c, 0xe1, 0x82, 0x62, 0x4a, 0x43, 0x40, 0xd0, 0x47, 0xb0, 0x15, 0x5c, 0xf6, 0x01, 0x86, 0x24, 0x34, 0x45, 0x03, 0xc0, 0x49, 0xc6, 0x25, 0xeb, 0xe8, 0xaa, 0x88, 0x17, 0xbb, 0x3e, 0x4f, 0x81, 0x44, 0x78, 0x04, 0x9a, 0x34, 0x41, 0xf6, 0x25, 0x03, 0x90, 0xb2, 0x03, 0x79, 0x4d, 0xb2, 0x28, 0x1b, 0x9c, 0xbb, 0x03, 0x33, 0x05, 0x1b, 0x36, 0xa0, 0x28, 0x84, 0x9a, 0x98, 0x59, 0xc5, 0x87, 0x82, 0xba, 0x31, 0x6e, 0xa9, 0x5a, 0xee, 0x1e, 0x87, 0x86, 0x03, 0x68, 0x13, 0xac, 0x93, 0xbb, 0x4b, 0xed, 0xf1, 0xc2, 0x80, 0xd5, 0x47, 0x1d, 0x88, 0x10, 0x52, 0xb8, 0x3c, 0x8d, 0x5b, 0x49, 0xd3, 0x70, 0x14, 0x84, 0xc7, 0x51, 0xe9, 0xe2, 0x33, 0x28, 0xed, 0x99, 0xc4, 0x5d, 0xcf, 0x6e, 0x3b, 0x39, 0xc2, 0xd7, 0xfc, 0x71, 0xcd, 0x26, 0x2d, 0x3b, 0x7a, 0x9a, 0x25, 0x20, 0xb3, 0xb7, 0x9d, 0x91, 0xfa, 0xa4, 0x9b, 0x20, 0x2d, 0x42, 0x23, 0x0f, 0x04, 0x9c, 0x14, 0x92, 0x2b, 0x25, 0x7a, 0x30, 0x42, 0x03, 0x50, 0x0c, 0xf0, 0xe1, 0xe5, 0x88, 0x70, 0x22, 0x58, 0x2d, 0xb7, 0x80, 0x5e, 0xad, 0x19, 0xd7, 0x61, 0x44, 0x80, 0xc2, 0x34, 0xa8, 0x7b, 0x18, 0xe4, 0xe6, 0xba, 0x20, 0x1d, 0xc0, 0x57, 0xc4, 0xe3, 0x48, 0x42, 0xf2, 0x31, 0x89, 0xa8, 0x80, 0xde, 0x8e, 0x59, 0x13, 0xb0, 0xa5, 0x3b, 0x20, 0x6b, 0x56, 0x96, 0x0e, 0x51, 0x6e, 0x3e, 0x32, 0xf2, 0xfe, 0x27, 0x4d, 0x08, 0x05, 0x64, 0xb4, 0x5a, 0x5e, 0x9c, 0x0a, 0xa5, 0x18, 0x99, 0xe1, 0x70, 0xc5, 0x5d, 0x06, 0x13, 0x81, 0x58, 0xa6, 0x12, 0x24, 0xac, 0x5c, 0x31, 0xa0, 0x5d, 0xe3, 0xce, 0xab, 0x2f, 0x31, 0x32, 0xb5, 0x4c, 0x02, 0x80, 0x80, 0x53, 0xe2, 0x96, 0x52, 0xb6, 0x71, 0x10, 0x63, 0x4a, 0xb9, 0xa1, 0x06, 0x4c, 0x16, 0xd3, 0x47, 0x48, 0x5b, 0x50, 0x33, 0x61, 0xdd, 0xca, 0x77, 0x6f, 0x90, 0x0e, 0x5b, 0x6c, 0xc3, 0x1a, 0x53, 0x78, 0xb3, 0xde, 0xca, 0x28, 0x1a, 0x2a, 0x80, 0x0f, 0x07, 0x4e, 0x14, 0xce, 0x95, 0x41, 0xa2, 0xc1, 0x74, 0xc1, 0xa3, 0xbc, 0x40, 0x43, 0xe3, 0x4a, 0x04, 0x41, 0x43, 0x59, 0x74, 0xf2, 0x1a, 0xe9, 0x52, 0x4c, 0x6b, 0x3e, 0x51, 0x09, 0x91, 0x38, 0x14, 0x51, 0xa7, 0x54, 0xab, 0x15, 0x26, 0x31, 0x47, 0xe4, 0x24, 0x5e, 0x14, 0xa8, 0xc5, 0x01, 0xa6, 0x2d, 0x08, 0x27, 0x87, 0xe7, 0xbb, 0xd3, 0x58, 0xec, 0x81, 0x90, 0xc4, 0x7d, 0xcd, 0x8c, 0x53, 0x06, 0x06, 0x44, 0xf3, 0x43, 0xbf, 0x34, 0xe2, 0x9b, 0x25, 0x1b, 0x12, 0xfc, 0x6a, 0xbf, 0x3a, 0xe0, 0x84, 0xe0, 0xfb, 0x52, 0xdf, 0xd2, 0x0f, 0xec, 0xe3, 0x80, 0xa8, 0xa2, 0x68, 0xd3, 0x03, 0xbd, 0xb2, 0x3f, 0x79, 0x51, 0xaa, 0x04, 0x94, 0x04, 0xce, 0xd5, 0xb2, 0x7c, 0x07, 0x31, 0xcd, 0x7a, 0x41, 0xea, 0x01, 0x30, 0xf2, 0x6f, 0x82, 0x1d, 0x81, 0x00, 0x07, 0x10, 0x50, 0x14, 0xf6, 0x2e, 0x50, 0xbe, 0x3c, 0x8e, 0x09, 0x59, 0x44, 0x5a, 0xde, 0x8f, 0x2e, 0x1b, 0x02, 0xfc, 0xd4, 0xfb, 0x1e, 0x31, 0x52, 0x4c, 0xf8, 0xf0, 0xc1, 0x6e, 0x90, 0x48, 0x85, 0xec, 0xb5, 0x7b, 0x7c, 0x1b, 0x70, 0xe7, 0x73, 0x94, 0x34, 0x21, 0x90, 0xb3, 0x60, 0xba, 0x01, 0xd1, 0xea, 0xf0, 0x21, 0xae, 0x2d, 0x47, 0x55, 0x38, 0xed, 0x07, 0x7b, 0xea, 0xe5, 0x35, 0xa0, 0x5b, 0x66, 0x0c, 0xf8, 0x6b, 0xf9, 0x6f, 0x0a, 0x75, 0x36, 0xcc, 0x02, 0xc1, 0xf9, 0x23, 0x60, 0x9c, 0x0f, 0x98, 0x5f, 0x1f, 0x4a, 0x35, 0x2a, 0x2a, 0x1e, 0x6e, 0xf8, 0xaa, 0xd1, 0x34, 0x98, 0xf0, 0x00, 0x8f, 0xe0, 0x21, 0x07, 0x27, 0xd5, 0xe4, 0xc8, 0xb2, 0xaa, 0x01, 0x14, 0x8c, 0x72, 0x3a, 0x28, 0x7b, 0x30, 0x98, 0x41, 0x5d, 0x04, 0x10, 0xaa, 0x3c, 0x75, 0xc4, 0xa2, 0x08, 0x60, 0xa4, 0xdf, 0x01, 0x4d, 0x18, 0xab, 0x92, 0xfd, 0x56, 0x46, 0x58, 0x87, 0x8c, 0xc7, 0x50, 0x5e, 0xe5, 0xf8, 0xf0, 0x80, 0x10, 0x19, 0x69, 0x2d, 0x5e, 0x02, 0x29, 0x5d, 0x6d, 0xfd, 0x47, 0x04, 0x71, 0xc2, 0xf0, 0xf1, 0x41, 0x21, 0xd2, 0x48, 0x9a, 0x34, 0x08, 0x85, 0x3c, 0x41, 0x71, 0x6f, 0x86, 0x14, 0x40, 0x75, 0xb4, 0x39, 0x11, 0xe5, 0xdb, 0x9b, 0x41, 0x20, 0x43, 0xa1, 0x51, 0x00, 0xa2, 0xee, 0x9c, 0x42, 0x38, 0x77, 0x01, 0x4b, 0x82, 0x18, 0x9b, 0xd4, 0x51, 0xc1, 0xc2, 0x25, 0x69, 0xbd, 0x74, 0xc4, 0x46, 0x26, 0xd3, 0x4c, 0xa0, 0xf4, 0x46, 0x88, 0x85, 0x92, 0x3c, 0xd6, 0x9d, 0x93, 0xe7, 0x3f, 0xad, 0xc3, 0x5a, 0x0a, 0x36, 0x88, 0x08, 0x04, 0x56, 0x40, 0x4b, 0xc1, 0xa9, 0xd8, 0x80, 0xa0, 0x23, 0x46, 0x83, 0xaf, 0x0c, 0x93, 0x8c, 0xbb, 0x8d, 0xae, 0x6d, 0x69, 0x09, 0x3f, 0x93, 0xa4, 0x3a, 0x56, 0xa3, 0x31, 0xbd, 0xf9, 0xfe, 0x8f, 0xcb, 0xc6, 0x85, 0xcc, 0x5d, 0x69, 0x58, 0xb4, 0x3d, 0x80, 0xa9, 0x04, 0x4a, 0x22, 0xb0, 0xd4, 0x10, 0x25, 0xc2, 0x62, 0xa4, 0xe2, 0x3f, 0xe9, 0xf2, 0xf9, 0x18, 0xcb, 0xcc, 0x41, 0x38, 0x27, 0x4b, 0x0b, 0x55, 0x30, 0x1d, 0xc6, 0x09, 0x41, 0x83, 0x83, 0xa6, 0xc9, 0x31, 0xb8, 0xc0, 0x15, 0x2d, 0x94, 0x21, 0x58, 0xf2, 0x4a, 0x53, 0x4c, 0x6c, 0x49, 0x60, 0xfe, 0x85, 0x38, 0x82, 0xe3, 0x10, 0xd4, 0x15, 0xec, 0x0d, 0x43, 0x19, 0xd1, 0x54, 0x2e, 0x2b, 0x58, 0xe0, 0xc7, 0x77, 0x64, 0x4c, 0xb5, 0x54, 0xe2, 0x80, 0xa2, 0xf2, 0x41, 0x83, 0x12, 0x82, 0x44, 0x1a, 0x02, 0xa3, 0x52, 0xf0, 0x11, 0x00, 0x14, 0xc2, 0xd6, 0x99, 0xc3, 0x6f, 0x75, 0xdd, 0xc1, 0x87, 0xe5, 0xd6, 0x9a, 0x9d, 0x72, 0x84, 0x0d, 0xd5, 0x0c, 0xba, 0x75, 0x5d, 0xd7, 0xb3, 0xd0, 0xb0, 0x4c, 0xc8, 0x94, 0xba, 0xb6, 0x22, 0x59, 0x33, 0xef, 0x09, 0xc8, 0x74, 0x4a, 0x38, 0x0f, 0x64, 0xaf, 0x96, 0xbe, 0x78, 0x77, 0xcc, 0x64, 0xbc, 0x9b, 0xf7, 0x4e, 0x26, 0x81, 0xa6, 0x5f, 0x3c, 0x35, 0x34, 0x24, 0xc0, 0xc3, 0x71, 0x15, 0xee, 0x55, 0x87, 0x12, 0x8d, 0x02, 0xbf, 0xe3, 0x3d, 0x2c, 0x53, 0x8f, 0x9f, 0x69, 0x71, 0x63, 0xa5, 0x9a, 0x79, 0xfd, 0xf7, 0xcc, 0xd3, 0xb7, 0x47, 0xd2, 0x12, 0x94, 0x67, 0x50, 0x18, 0xb8, 0xde, 0xb9, 0xae, 0x15, 0x5a, 0x18, 0xaa, 0xab, 0x38, 0x52, 0x50, 0x80, 0x1c, 0xf9, 0x7c, 0x0c, 0xa1, 0xec, 0x0a, 0xe3, 0x2a, 0xac, 0x08, 0x76, 0x09, 0x80, 0x0e, 0x80, 0x38, 0x1d, 0x6b, 0xdd, 0x93, 0x02, 0xa3, 0x57, 0x68, 0xa1, 0x69, 0x03, 0x7b, 0xc4, 0x60, 0x6c, 0x83, 0xa0, 0x67, 0xd0, 0xc4, 0x7b, 0x9f, 0xfa, 0xb9, 0xa7, 0x32, 0xad, 0x0a, 0x57, 0x02, 0x11, 0xcc, 0x6e, 0x20, 0x5e, 0x88, 0x40, 0x84, 0xfa, 0xce, 0x5a, 0xed, 0x72, 0xb8, 0x36, 0xf8, 0xff, 0x00, 0xab, 0x5e, 0x01, 0xc0, 0x90, 0x8e, 0x7d, 0xd4, 0x1f, 0x92, 0x90, 0x4a, 0x01, 0x15, 0xf7, 0xab, 0x30, 0x20, 0xe5, 0x0f, 0x71, 0xed, 0xa4, 0xe3, 0x29, 0xab, 0xa2, 0x11, 0x30, 0x81, 0x50, 0x3b, 0xee, 0xb2, 0x54, 0x90, 0x74, 0x46, 0x70, 0x50, 0xd1, 0xa0, 0x04, 0x46, 0xf8, 0x9c, 0x50, 0x22, 0x0e, 0xfa, 0xc0, 0x90, 0xf6, 0xb6, 0x57, 0x9e, 0x0a, 0x7a, 0xe3, 0x60, 0x9a, 0x9d, 0x44, 0x17, 0xe0, 0x53, 0x8b, 0x0c, 0xf8, 0x3f, 0xf8, 0x3c, 0x8e, 0x25, 0x40, 0x00, 0xea, 0x8a, 0x19, 0xbf, 0x75, 0xf7, 0xca, 0xd0, 0x60, 0x9f, 0x55, 0xa6, 0x9d, 0x37, 0xb6, 0xdf, 0x5c, 0x3b, 0x2a, 0x48, 0x0a, 0x02, 0xa0, 0x0b, 0x06, 0xf9, 0xed, 0xaa, 0xa9, 0x9b, 0x64, 0xe4, 0x18, 0x55, 0x15, 0x25, 0xf4, 0xa7, 0x4b, 0xca, 0xc9, 0x30, 0x2f, 0xb6, 0x01, 0x81, 0x55, 0xfd, 0xbc, 0x52, 0x3d, 0xa4, 0x3d, 0x1e, 0xbb, 0xeb, 0xe7, 0x5f, 0xc7, 0x23, 0xbb, 0x7e, 0x7e, 0x55, 0x5f, 0x3d, 0xfb, 0xe0, 0x55, 0x80, 0xce, 0xd0, 0xa9, 0x9d, 0xc0, 0xf9, 0x78, 0xc8, 0xae, 0xf4, 0xf6, 0xc5, 0xd6, 0x09, 0xd4, 0x7e, 0x71, 0xac, 0x4f, 0x62, 0x30, 0x14, 0xbd, 0xa1, 0xdf, 0xe3, 0xd7, 0x02, 0x1c, 0xed, 0x2d, 0x2f, 0xbf, 0xf5, 0xe7, 0x99, 0x82, 0xe1, 0x41, 0x3f, 0x7c, 0x47, 0x14, 0x20, 0x8c, 0xc3, 0xe7, 0xc3, 0xd7, 0x47, 0x36, 0xf8, 0x9c, 0x03, 0xa0, 0x15, 0xd4, 0x77, 0x61, 0xe3, 0x98, 0x96, 0x9b, 0xd3, 0x4c, 0x4c, 0x3e, 0xd0, 0x9a, 0x1b, 0x87, 0x0c, 0x6b, 0x42, 0x1c, 0x05, 0x80, 0x15, 0x85, 0xfc, 0x73, 0xff, 0xd9, }; static const int pic32mz_jpg_len = 12177; static const unsigned char board_js[] = { 0x76, 0x61, 0x72, 0x20, 0x75, 0x70, 0x64, 0x61, 0x74, 0x65, 0x5f, 0x73, 0x70, 0x65, 0x65, 0x64, 0x20, 0x3d, 0x20, 0x31, 0x30, 0x30, 0x30, 0x3b, 0x0d, 0x0a, 0x0d, 0x0a, 0x66, 0x75, 0x6e, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x75, 0x70, 0x64, 0x61, 0x74, 0x65, 0x42, 0x6f, 0x61, 0x72, 0x64, 0x49, 0x6e, 0x66, 0x6f, 0x28, 0x29, 0x0d, 0x0a, 0x7b, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x76, 0x61, 0x72, 0x20, 0x78, 0x6d, 0x6c, 0x68, 0x74, 0x74, 0x70, 0x20, 0x3d, 0x20, 0x6e, 0x65, 0x77, 0x20, 0x58, 0x4d, 0x4c, 0x48, 0x74, 0x74, 0x70, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x28, 0x29, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x78, 0x6d, 0x6c, 0x68, 0x74, 0x74, 0x70, 0x2e, 0x6f, 0x6e, 0x72, 0x65, 0x61, 0x64, 0x79, 0x73, 0x74, 0x61, 0x74, 0x65, 0x63, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x20, 0x3d, 0x20, 0x66, 0x75, 0x6e, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x28, 0x29, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x7b, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x69, 0x66, 0x20, 0x28, 0x78, 0x6d, 0x6c, 0x68, 0x74, 0x74, 0x70, 0x2e, 0x72, 0x65, 0x61, 0x64, 0x79, 0x53, 0x74, 0x61, 0x74, 0x65, 0x20, 0x3d, 0x3d, 0x20, 0x34, 0x20, 0x26, 0x26, 0x20, 0x78, 0x6d, 0x6c, 0x68, 0x74, 0x74, 0x70, 0x2e, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x20, 0x3d, 0x3d, 0x20, 0x32, 0x30, 0x30, 0x29, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x7b, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x76, 0x61, 0x72, 0x20, 0x69, 0x6e, 0x66, 0x6f, 0x20, 0x3d, 0x20, 0x4a, 0x53, 0x4f, 0x4e, 0x2e, 0x70, 0x61, 0x72, 0x73, 0x65, 0x28, 0x78, 0x6d, 0x6c, 0x68, 0x74, 0x74, 0x70, 0x2e, 0x72, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x54, 0x65, 0x78, 0x74, 0x29, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x64, 0x6f, 0x63, 0x75, 0x6d, 0x65, 0x6e, 0x74, 0x2e, 0x67, 0x65, 0x74, 0x45, 0x6c, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x42, 0x79, 0x49, 0x64, 0x28, 0x22, 0x75, 0x70, 0x74, 0x69, 0x6d, 0x65, 0x22, 0x29, 0x2e, 0x69, 0x6e, 0x6e, 0x65, 0x72, 0x48, 0x54, 0x4d, 0x4c, 0x20, 0x3d, 0x20, 0x69, 0x6e, 0x66, 0x6f, 0x2e, 0x75, 0x70, 0x74, 0x69, 0x6d, 0x65, 0x20, 0x2b, 0x22, 0x20, 0x73, 0x65, 0x63, 0x6f, 0x6e, 0x64, 0x73, 0x22, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x64, 0x6f, 0x63, 0x75, 0x6d, 0x65, 0x6e, 0x74, 0x2e, 0x67, 0x65, 0x74, 0x45, 0x6c, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x42, 0x79, 0x49, 0x64, 0x28, 0x22, 0x6c, 0x65, 0x64, 0x31, 0x5f, 0x73, 0x74, 0x61, 0x74, 0x65, 0x22, 0x29, 0x2e, 0x73, 0x74, 0x79, 0x6c, 0x65, 0x2e, 0x62, 0x61, 0x63, 0x6b, 0x67, 0x72, 0x6f, 0x75, 0x6e, 0x64, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x20, 0x3d, 0x20, 0x28, 0x69, 0x6e, 0x66, 0x6f, 0x2e, 0x6c, 0x31, 0x20, 0x3d, 0x3d, 0x20, 0x22, 0x6f, 0x6e, 0x22, 0x29, 0x20, 0x3f, 0x20, 0x22, 0x23, 0x46, 0x46, 0x30, 0x30, 0x30, 0x30, 0x22, 0x20, 0x3a, 0x20, 0x22, 0x23, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x22, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x64, 0x6f, 0x63, 0x75, 0x6d, 0x65, 0x6e, 0x74, 0x2e, 0x67, 0x65, 0x74, 0x45, 0x6c, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x42, 0x79, 0x49, 0x64, 0x28, 0x22, 0x6c, 0x65, 0x64, 0x32, 0x5f, 0x73, 0x74, 0x61, 0x74, 0x65, 0x22, 0x29, 0x2e, 0x73, 0x74, 0x79, 0x6c, 0x65, 0x2e, 0x62, 0x61, 0x63, 0x6b, 0x67, 0x72, 0x6f, 0x75, 0x6e, 0x64, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x20, 0x3d, 0x20, 0x28, 0x69, 0x6e, 0x66, 0x6f, 0x2e, 0x6c, 0x32, 0x20, 0x3d, 0x3d, 0x20, 0x22, 0x6f, 0x6e, 0x22, 0x29, 0x20, 0x3f, 0x20, 0x22, 0x23, 0x46, 0x46, 0x46, 0x46, 0x30, 0x30, 0x22, 0x20, 0x3a, 0x20, 0x22, 0x23, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x22, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x73, 0x65, 0x74, 0x54, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x28, 0x66, 0x75, 0x6e, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x28, 0x29, 0x7b, 0x75, 0x70, 0x64, 0x61, 0x74, 0x65, 0x42, 0x6f, 0x61, 0x72, 0x64, 0x49, 0x6e, 0x66, 0x6f, 0x28, 0x29, 0x3b, 0x7d, 0x2c, 0x20, 0x75, 0x70, 0x64, 0x61, 0x74, 0x65, 0x5f, 0x73, 0x70, 0x65, 0x65, 0x64, 0x29, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x7d, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x7d, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x78, 0x6d, 0x6c, 0x68, 0x74, 0x74, 0x70, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x28, 0x22, 0x47, 0x45, 0x54, 0x22, 0x2c, 0x22, 0x62, 0x6f, 0x61, 0x72, 0x64, 0x5f, 0x69, 0x6e, 0x66, 0x6f, 0x22, 0x2c, 0x74, 0x72, 0x75, 0x65, 0x29, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x78, 0x6d, 0x6c, 0x68, 0x74, 0x74, 0x70, 0x2e, 0x74, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x20, 0x3d, 0x20, 0x33, 0x30, 0x30, 0x30, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x78, 0x6d, 0x6c, 0x68, 0x74, 0x74, 0x70, 0x2e, 0x6f, 0x6e, 0x74, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x20, 0x3d, 0x20, 0x66, 0x75, 0x6e, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x28, 0x29, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x7b, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x75, 0x70, 0x64, 0x61, 0x74, 0x65, 0x42, 0x6f, 0x61, 0x72, 0x64, 0x49, 0x6e, 0x66, 0x6f, 0x28, 0x29, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x7d, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x78, 0x6d, 0x6c, 0x68, 0x74, 0x74, 0x70, 0x2e, 0x6f, 0x6e, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x20, 0x3d, 0x20, 0x66, 0x75, 0x6e, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x28, 0x65, 0x29, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x7b, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x73, 0x65, 0x74, 0x54, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x28, 0x66, 0x75, 0x6e, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x28, 0x29, 0x7b, 0x75, 0x70, 0x64, 0x61, 0x74, 0x65, 0x42, 0x6f, 0x61, 0x72, 0x64, 0x49, 0x6e, 0x66, 0x6f, 0x28, 0x29, 0x7d, 0x2c, 0x20, 0x31, 0x30, 0x30, 0x30, 0x29, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x7d, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x78, 0x6d, 0x6c, 0x68, 0x74, 0x74, 0x70, 0x2e, 0x73, 0x65, 0x6e, 0x64, 0x28, 0x29, 0x3b, 0x0d, 0x0a, 0x7d, 0x0d, 0x0a, 0x0d, 0x0a, 0x66, 0x75, 0x6e, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x74, 0x6f, 0x67, 0x67, 0x6c, 0x65, 0x5f, 0x6c, 0x65, 0x64, 0x31, 0x28, 0x29, 0x7b, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x76, 0x61, 0x72, 0x20, 0x61, 0x6a, 0x61, 0x78, 0x50, 0x6f, 0x73, 0x74, 0x20, 0x3d, 0x20, 0x6e, 0x65, 0x77, 0x20, 0x58, 0x4d, 0x4c, 0x48, 0x74, 0x74, 0x70, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x61, 0x6a, 0x61, 0x78, 0x50, 0x6f, 0x73, 0x74, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x28, 0x22, 0x47, 0x45, 0x54, 0x22, 0x2c, 0x22, 0x6c, 0x65, 0x64, 0x31, 0x22, 0x2c, 0x74, 0x72, 0x75, 0x65, 0x29, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x61, 0x6a, 0x61, 0x78, 0x50, 0x6f, 0x73, 0x74, 0x2e, 0x73, 0x65, 0x6e, 0x64, 0x28, 0x22, 0x22, 0x29, 0x3b, 0x0d, 0x0a, 0x7d, 0x0d, 0x0a, 0x0d, 0x0a, 0x66, 0x75, 0x6e, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x74, 0x6f, 0x67, 0x67, 0x6c, 0x65, 0x5f, 0x6c, 0x65, 0x64, 0x32, 0x28, 0x29, 0x7b, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x76, 0x61, 0x72, 0x20, 0x61, 0x6a, 0x61, 0x78, 0x50, 0x6f, 0x73, 0x74, 0x20, 0x3d, 0x20, 0x6e, 0x65, 0x77, 0x20, 0x58, 0x4d, 0x4c, 0x48, 0x74, 0x74, 0x70, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x61, 0x6a, 0x61, 0x78, 0x50, 0x6f, 0x73, 0x74, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x28, 0x22, 0x47, 0x45, 0x54, 0x22, 0x2c, 0x22, 0x6c, 0x65, 0x64, 0x32, 0x22, 0x2c, 0x74, 0x72, 0x75, 0x65, 0x29, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x61, 0x6a, 0x61, 0x78, 0x50, 0x6f, 0x73, 0x74, 0x2e, 0x73, 0x65, 0x6e, 0x64, 0x28, 0x22, 0x22, 0x29, 0x3b, 0x0d, 0x0a, 0x7d, 0x0d, 0x0a, 0x0d, 0x0a, 0x66, 0x75, 0x6e, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x67, 0x65, 0x74, 0x49, 0x70, 0x28, 0x29, 0x0d, 0x0a, 0x7b, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x76, 0x61, 0x72, 0x20, 0x78, 0x6d, 0x6c, 0x68, 0x74, 0x74, 0x70, 0x20, 0x3d, 0x20, 0x6e, 0x65, 0x77, 0x20, 0x58, 0x4d, 0x4c, 0x48, 0x74, 0x74, 0x70, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x28, 0x29, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x78, 0x6d, 0x6c, 0x68, 0x74, 0x74, 0x70, 0x2e, 0x6f, 0x6e, 0x72, 0x65, 0x61, 0x64, 0x79, 0x73, 0x74, 0x61, 0x74, 0x65, 0x63, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x20, 0x3d, 0x20, 0x66, 0x75, 0x6e, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x28, 0x29, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x7b, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x69, 0x66, 0x20, 0x28, 0x78, 0x6d, 0x6c, 0x68, 0x74, 0x74, 0x70, 0x2e, 0x72, 0x65, 0x61, 0x64, 0x79, 0x53, 0x74, 0x61, 0x74, 0x65, 0x20, 0x3d, 0x3d, 0x20, 0x34, 0x20, 0x26, 0x26, 0x20, 0x78, 0x6d, 0x6c, 0x68, 0x74, 0x74, 0x70, 0x2e, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x20, 0x3d, 0x3d, 0x20, 0x32, 0x30, 0x30, 0x29, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x7b, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x64, 0x6f, 0x63, 0x75, 0x6d, 0x65, 0x6e, 0x74, 0x2e, 0x67, 0x65, 0x74, 0x45, 0x6c, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x42, 0x79, 0x49, 0x64, 0x28, 0x22, 0x69, 0x70, 0x22, 0x29, 0x2e, 0x69, 0x6e, 0x6e, 0x65, 0x72, 0x48, 0x54, 0x4d, 0x4c, 0x20, 0x3d, 0x20, 0x78, 0x6d, 0x6c, 0x68, 0x74, 0x74, 0x70, 0x2e, 0x72, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x54, 0x65, 0x78, 0x74, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x7d, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x7d, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x78, 0x6d, 0x6c, 0x68, 0x74, 0x74, 0x70, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x28, 0x22, 0x47, 0x45, 0x54, 0x22, 0x2c, 0x22, 0x69, 0x70, 0x22, 0x2c, 0x74, 0x72, 0x75, 0x65, 0x29, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x78, 0x6d, 0x6c, 0x68, 0x74, 0x74, 0x70, 0x2e, 0x73, 0x65, 0x6e, 0x64, 0x28, 0x29, 0x3b, 0x0d, 0x0a, 0x7d, 0x0d, 0x0a, 0x0d, 0x0a, 0x66, 0x75, 0x6e, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x67, 0x65, 0x74, 0x4d, 0x41, 0x43, 0x28, 0x29, 0x0d, 0x0a, 0x7b, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x76, 0x61, 0x72, 0x20, 0x78, 0x6d, 0x6c, 0x68, 0x74, 0x74, 0x70, 0x20, 0x3d, 0x20, 0x6e, 0x65, 0x77, 0x20, 0x58, 0x4d, 0x4c, 0x48, 0x74, 0x74, 0x70, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x28, 0x29, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x78, 0x6d, 0x6c, 0x68, 0x74, 0x74, 0x70, 0x2e, 0x6f, 0x6e, 0x72, 0x65, 0x61, 0x64, 0x79, 0x73, 0x74, 0x61, 0x74, 0x65, 0x63, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x20, 0x3d, 0x20, 0x66, 0x75, 0x6e, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x28, 0x29, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x7b, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x69, 0x66, 0x20, 0x28, 0x78, 0x6d, 0x6c, 0x68, 0x74, 0x74, 0x70, 0x2e, 0x72, 0x65, 0x61, 0x64, 0x79, 0x53, 0x74, 0x61, 0x74, 0x65, 0x20, 0x3d, 0x3d, 0x20, 0x34, 0x20, 0x26, 0x26, 0x20, 0x78, 0x6d, 0x6c, 0x68, 0x74, 0x74, 0x70, 0x2e, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x20, 0x3d, 0x3d, 0x20, 0x32, 0x30, 0x30, 0x29, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x7b, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x64, 0x6f, 0x63, 0x75, 0x6d, 0x65, 0x6e, 0x74, 0x2e, 0x67, 0x65, 0x74, 0x45, 0x6c, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x42, 0x79, 0x49, 0x64, 0x28, 0x22, 0x6d, 0x61, 0x63, 0x22, 0x29, 0x2e, 0x69, 0x6e, 0x6e, 0x65, 0x72, 0x48, 0x54, 0x4d, 0x4c, 0x20, 0x3d, 0x20, 0x78, 0x6d, 0x6c, 0x68, 0x74, 0x74, 0x70, 0x2e, 0x72, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x54, 0x65, 0x78, 0x74, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x7d, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x7d, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x78, 0x6d, 0x6c, 0x68, 0x74, 0x74, 0x70, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x28, 0x22, 0x47, 0x45, 0x54, 0x22, 0x2c, 0x22, 0x6d, 0x61, 0x63, 0x22, 0x2c, 0x74, 0x72, 0x75, 0x65, 0x29, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x78, 0x6d, 0x6c, 0x68, 0x74, 0x74, 0x70, 0x2e, 0x73, 0x65, 0x6e, 0x64, 0x28, 0x29, 0x3b, 0x0d, 0x0a, 0x7d, 0x0d, 0x0a, 0x0d, 0x0a, }; static const int board_js_len = 1937; static const unsigned char cloud_png[] = { 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x46, 0x00, 0x00, 0x00, 0x34, 0x08, 0x06, 0x00, 0x00, 0x00, 0x37, 0xc4, 0x4e, 0x4e, 0x00, 0x00, 0x00, 0x06, 0x62, 0x4b, 0x47, 0x44, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0xa0, 0xbd, 0xa7, 0x93, 0x00, 0x00, 0x00, 0x09, 0x70, 0x48, 0x59, 0x73, 0x00, 0x00, 0x0b, 0x13, 0x00, 0x00, 0x0b, 0x13, 0x01, 0x00, 0x9a, 0x9c, 0x18, 0x00, 0x00, 0x00, 0x07, 0x74, 0x49, 0x4d, 0x45, 0x07, 0xe0, 0x0c, 0x14, 0x0e, 0x11, 0x09, 0xe0, 0x80, 0x2a, 0x55, 0x00, 0x00, 0x00, 0x19, 0x74, 0x45, 0x58, 0x74, 0x43, 0x6f, 0x6d, 0x6d, 0x65, 0x6e, 0x74, 0x00, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68, 0x20, 0x47, 0x49, 0x4d, 0x50, 0x57, 0x81, 0x0e, 0x17, 0x00, 0x00, 0x07, 0x12, 0x49, 0x44, 0x41, 0x54, 0x68, 0xde, 0xed, 0x9a, 0x6b, 0x50, 0x54, 0xf7, 0x19, 0xc6, 0x9f, 0xff, 0xd9, 0xb3, 0xcb, 0x22, 0xda, 0x70, 0x93, 0xcb, 0x5e, 0x40, 0x8b, 0x80, 0xb7, 0x01, 0x2f, 0x80, 0xa0, 0x40, 0x68, 0x5a, 0x63, 0xd2, 0x78, 0x89, 0x49, 0x75, 0x92, 0xc6, 0x49, 0x9a, 0x38, 0x49, 0xd4, 0xb1, 0x9a, 0xe4, 0x83, 0xa6, 0x29, 0x6d, 0x74, 0x26, 0x69, 0x9b, 0x26, 0x69, 0x74, 0x32, 0x41, 0x92, 0x4c, 0x99, 0x18, 0x52, 0x6b, 0x34, 0x49, 0xc7, 0xa8, 0x09, 0x46, 0x28, 0x49, 0xb4, 0xc5, 0x0b, 0xb0, 0x88, 0x28, 0x42, 0x04, 0xcc, 0xb2, 0x7b, 0x76, 0x97, 0x4b, 0x08, 0x8b, 0x2c, 0xec, 0x9e, 0xcb, 0xdb, 0x0f, 0xdc, 0x4a, 0xb4, 0x46, 0xda, 0xa5, 0xb2, 0x2c, 0xcf, 0xb7, 0x9d, 0x73, 0xce, 0x9e, 0xb3, 0xbf, 0x7d, 0x9f, 0xe7, 0xfd, 0x5f, 0x0e, 0x30, 0xa1, 0xeb, 0x8a, 0x79, 0xfb, 0x0b, 0x2d, 0xc7, 0xcf, 0xc1, 0xb0, 0x34, 0x79, 0xf0, 0xb3, 0x5d, 0xea, 0x9c, 0x89, 0x0f, 0xeb, 0xef, 0x95, 0xaa, 0xed, 0x22, 0xda, 0x7b, 0xc1, 0x08, 0xe0, 0x22, 0x83, 0x20, 0x45, 0x06, 0x32, 0x55, 0xaa, 0xde, 0xa4, 0x4b, 0x4b, 0x28, 0x19, 0x38, 0xb7, 0x79, 0x7f, 0x19, 0x33, 0x3e, 0x90, 0x41, 0xe3, 0x0e, 0x8c, 0x6d, 0x6f, 0x19, 0x8b, 0x7e, 0x24, 0x83, 0x2c, 0xad, 0xb6, 0xd5, 0xd8, 0x5b, 0xf3, 0x22, 0x0a, 0xce, 0x7b, 0x14, 0x6b, 0x57, 0x04, 0x0b, 0xd6, 0x46, 0x53, 0x8f, 0x08, 0x48, 0xd4, 0x77, 0x43, 0x9e, 0x03, 0xf1, 0x0c, 0x10, 0x15, 0x27, 0x88, 0xae, 0x70, 0xcb, 0x67, 0x80, 0x9e, 0x4c, 0x2a, 0x32, 0x66, 0xcc, 0xd9, 0x3e, 0xee, 0x2a, 0xa6, 0xb5, 0xc9, 0xaa, 0x99, 0x3a, 0x5d, 0xef, 0x11, 0x76, 0x95, 0x92, 0xb4, 0xf3, 0x04, 0xd0, 0xd1, 0x0d, 0x80, 0xbb, 0xc9, 0x5b, 0x10, 0xc0, 0x71, 0x60, 0x0f, 0xcd, 0x06, 0xcc, 0xce, 0x70, 0xf5, 0x33, 0x8b, 0x5c, 0x51, 0xab, 0x16, 0xf4, 0xdc, 0x4a, 0x30, 0xdc, 0xff, 0x6c, 0x9d, 0x25, 0x79, 0xb8, 0x4c, 0x2e, 0x5e, 0xdc, 0x7f, 0xe1, 0x8b, 0xe6, 0xa4, 0xd7, 0x48, 0x7a, 0xea, 0x28, 0xa1, 0xa3, 0x07, 0x80, 0x6a, 0x04, 0xdc, 0x19, 0xa0, 0x10, 0xa8, 0xf0, 0x1c, 0x51, 0x55, 0x4b, 0x9b, 0x72, 0xac, 0x51, 0x10, 0x1e, 0x3f, 0x30, 0x0d, 0x00, 0xec, 0x47, 0xaa, 0x98, 0x4f, 0x55, 0x8c, 0xc3, 0xd4, 0x80, 0xc8, 0xf9, 0x71, 0x7d, 0x70, 0x16, 0xbf, 0x51, 0xa7, 0x54, 0xb5, 0x24, 0xc0, 0xe5, 0xf1, 0x5e, 0x11, 0x86, 0x06, 0x5a, 0x34, 0x85, 0x2b, 0x2d, 0x51, 0xf7, 0x24, 0x67, 0x08, 0xbb, 0x4b, 0x99, 0x6e, 0xeb, 0x8f, 0xc8, 0x67, 0xac, 0xd4, 0xd2, 0xd6, 0xba, 0xa5, 0x37, 0xeb, 0xdd, 0xd7, 0x50, 0xdb, 0xc6, 0x8d, 0x42, 0x8e, 0x03, 0x50, 0xc0, 0xbf, 0x79, 0x8f, 0x55, 0xf7, 0x64, 0x96, 0xc1, 0x67, 0xac, 0x64, 0x3b, 0x6c, 0x8a, 0x77, 0x67, 0x17, 0xfe, 0x7a, 0xf4, 0xa0, 0xf4, 0x3d, 0x9e, 0xb4, 0xf9, 0x98, 0x5e, 0x78, 0xb9, 0xb8, 0xa4, 0x93, 0x88, 0xb3, 0x9d, 0xaa, 0x1b, 0xbb, 0x60, 0x9a, 0x73, 0x0f, 0x33, 0x00, 0x90, 0x76, 0x9e, 0xf8, 0x80, 0x6a, 0xdb, 0x22, 0x46, 0x0f, 0x4a, 0xbf, 0x44, 0x19, 0xf2, 0xab, 0xa7, 0xef, 0x70, 0x1d, 0xae, 0x3a, 0x11, 0x9d, 0x9e, 0x38, 0x36, 0xc1, 0xd8, 0xcf, 0xd4, 0xc3, 0xf8, 0xc2, 0x0a, 0x6a, 0xce, 0x3d, 0xec, 0xa6, 0x72, 0x6b, 0x12, 0xe8, 0xff, 0xe3, 0x76, 0xb2, 0x77, 0x41, 0xda, 0xf1, 0xe5, 0x62, 0x00, 0xb0, 0x3c, 0xfb, 0x31, 0x1b, 0x53, 0x19, 0x63, 0x2d, 0xaa, 0x82, 0xfe, 0xae, 0x79, 0xb0, 0x9f, 0xac, 0xad, 0xf3, 0x64, 0xee, 0x4d, 0xf0, 0x42, 0x43, 0x1b, 0x69, 0xe9, 0x10, 0xb7, 0x21, 0x95, 0x19, 0xf2, 0xd7, 0x0e, 0x3e, 0xb3, 0xad, 0xb0, 0x6c, 0x81, 0x94, 0x5f, 0x29, 0x53, 0x85, 0x1d, 0xe8, 0x95, 0x81, 0x49, 0x3c, 0x54, 0xa9, 0x3a, 0xe0, 0xe1, 0xb9, 0x8a, 0x7e, 0x7d, 0xe6, 0x79, 0x00, 0x10, 0x76, 0x7c, 0x0a, 0xdd, 0x8e, 0xbb, 0x47, 0x37, 0x7c, 0x05, 0x67, 0xeb, 0x22, 0xf9, 0xf6, 0x7d, 0x47, 0xc8, 0xe4, 0x08, 0xbf, 0x45, 0xa3, 0x2e, 0x59, 0xb3, 0xe7, 0xee, 0x55, 0x2c, 0xdb, 0x18, 0xe8, 0x5e, 0xfb, 0x51, 0x2a, 0x67, 0xf8, 0xc1, 0x36, 0xa5, 0xba, 0x05, 0x68, 0x71, 0x01, 0x92, 0x02, 0xf0, 0x1c, 0x58, 0x64, 0x10, 0x30, 0x33, 0x0c, 0x70, 0x89, 0x2f, 0xa9, 0x77, 0x2f, 0xcd, 0x8f, 0x4a, 0x4b, 0xb8, 0x62, 0x3e, 0x57, 0x8f, 0x98, 0xe4, 0x84, 0xd1, 0x03, 0x63, 0xdd, 0xf4, 0xc1, 0xd3, 0xf2, 0x81, 0x4b, 0x7f, 0x42, 0x9b, 0xeb, 0xd6, 0x8d, 0x48, 0x53, 0xa2, 0x7a, 0x21, 0x13, 0xa8, 0xa6, 0x55, 0x0b, 0x51, 0xfe, 0x0f, 0x3f, 0x81, 0x00, 0xb5, 0x0a, 0x5c, 0x7c, 0xa8, 0x5b, 0x29, 0xfa, 0xd9, 0xa3, 0x31, 0x31, 0x31, 0x7f, 0x6d, 0x36, 0xd5, 0x31, 0xe3, 0xfc, 0x44, 0xf2, 0x7a, 0xc6, 0x7c, 0x4b, 0xc4, 0xe4, 0x83, 0x97, 0x82, 0x6f, 0x25, 0x14, 0x00, 0xa0, 0x72, 0x9b, 0x96, 0x4c, 0x76, 0x2d, 0x44, 0xe5, 0x06, 0xff, 0x2b, 0x03, 0x44, 0x05, 0xca, 0xc5, 0x16, 0x0d, 0x4b, 0x79, 0x77, 0x5f, 0x73, 0x65, 0xdd, 0x2e, 0xe3, 0xfc, 0x44, 0xb2, 0x3c, 0xfd, 0x37, 0xef, 0x57, 0x8c, 0xe5, 0xb7, 0x47, 0x8d, 0x74, 0x4a, 0x30, 0xd3, 0x67, 0x8d, 0x18, 0xf5, 0x4e, 0xe4, 0x5d, 0x94, 0x60, 0xf1, 0xa1, 0xad, 0x5c, 0xee, 0x92, 0x1c, 0xfd, 0x23, 0x8b, 0x2f, 0xde, 0xec, 0x55, 0xfc, 0x4d, 0x65, 0x4b, 0xf5, 0x65, 0x88, 0xc9, 0x05, 0x6e, 0x16, 0x1a, 0xe8, 0x63, 0x50, 0xfa, 0xbb, 0xda, 0xd7, 0xce, 0xa9, 0xf2, 0xaf, 0x4a, 0xb3, 0x00, 0x5c, 0xf4, 0xaa, 0x95, 0x74, 0x49, 0x33, 0xc0, 0xe7, 0x2d, 0xbb, 0x17, 0xed, 0xdd, 0xbe, 0xb9, 0xb8, 0xe2, 0x91, 0xc0, 0xcd, 0x8d, 0xc8, 0x17, 0x9e, 0xff, 0xc4, 0xe0, 0xf5, 0x8c, 0x61, 0x3c, 0xf7, 0x26, 0x20, 0x91, 0x6f, 0x92, 0x61, 0x50, 0xce, 0xda, 0x20, 0xee, 0x7c, 0xeb, 0xaa, 0xe5, 0xec, 0x25, 0xe6, 0x55, 0x30, 0xb2, 0xad, 0x0b, 0x00, 0x63, 0xf0, 0x55, 0x75, 0x74, 0x81, 0x3b, 0x94, 0x5b, 0x6c, 0x48, 0x9d, 0x49, 0xde, 0xad, 0x98, 0x1e, 0xc9, 0x07, 0xf3, 0x65, 0x78, 0x08, 0xf3, 0x22, 0x16, 0x7a, 0xc5, 0x4a, 0xd6, 0xd7, 0x4b, 0x87, 0x4e, 0x54, 0x7c, 0x19, 0x4a, 0x9f, 0x9d, 0x98, 0x5a, 0x55, 0xe1, 0xb5, 0x76, 0x2d, 0x7c, 0x5e, 0x73, 0xbf, 0xbc, 0xa5, 0x78, 0x25, 0xbe, 0xe9, 0x79, 0x98, 0x2c, 0x4e, 0xdf, 0xad, 0x9a, 0x10, 0x2d, 0xa4, 0x8e, 0xf2, 0x90, 0xa0, 0xb3, 0xaf, 0x76, 0x46, 0xa6, 0xc6, 0xd3, 0x7f, 0x05, 0xc6, 0xfa, 0xe5, 0x05, 0xa6, 0xcf, 0x9e, 0x43, 0xe6, 0x5f, 0xec, 0x9b, 0x8d, 0x32, 0xe1, 0x02, 0xea, 0x3b, 0x00, 0x22, 0x9f, 0xb6, 0x11, 0xf7, 0xd3, 0x19, 0x60, 0x99, 0x46, 0xa3, 0xfe, 0xb9, 0x3b, 0x2d, 0x23, 0xb6, 0x92, 0xad, 0xbc, 0x1e, 0x00, 0x30, 0x25, 0x6b, 0xf6, 0x64, 0xeb, 0xfb, 0xa7, 0x89, 0x1d, 0xa8, 0xbb, 0x80, 0xba, 0x36, 0xf2, 0x6d, 0x28, 0x00, 0x02, 0x78, 0x28, 0x15, 0xb6, 0xf5, 0x03, 0x50, 0x84, 0xe2, 0xea, 0x91, 0x5b, 0xc9, 0xae, 0x74, 0x26, 0xd2, 0xae, 0xf2, 0x93, 0xe2, 0xb6, 0xd2, 0x70, 0x48, 0xb2, 0x8f, 0x07, 0x6e, 0xbf, 0x26, 0xa9, 0xc1, 0x8c, 0x53, 0x4a, 0x69, 0x51, 0x74, 0x85, 0xfa, 0x37, 0x99, 0xdf, 0x46, 0xc7, 0xc7, 0xbe, 0x38, 0x62, 0x30, 0xcd, 0x2b, 0xfe, 0xbc, 0x8c, 0x2a, 0x1c, 0x45, 0x10, 0xae, 0x62, 0x5c, 0x89, 0x01, 0x08, 0x54, 0x83, 0x85, 0x6a, 0x49, 0xb5, 0x2d, 0xbd, 0x93, 0x6d, 0x98, 0xb7, 0x90, 0x5e, 0x39, 0xd3, 0xa8, 0x7b, 0x6e, 0xd9, 0xf7, 0x5b, 0xa9, 0xf9, 0x50, 0x79, 0x1c, 0x5c, 0x52, 0x11, 0x04, 0x27, 0x61, 0xbc, 0x89, 0x00, 0xb8, 0x44, 0x90, 0xa5, 0x8b, 0x49, 0x5b, 0x8e, 0xde, 0xa6, 0x6c, 0x38, 0xd6, 0x40, 0x65, 0xc2, 0x54, 0x00, 0xb0, 0xdc, 0xf9, 0xf6, 0xf5, 0xc1, 0x0c, 0x6e, 0x51, 0xd4, 0xb6, 0x5f, 0xa6, 0x92, 0x7a, 0x02, 0x38, 0x86, 0x71, 0x2d, 0x0d, 0x93, 0x0b, 0x2a, 0x88, 0xcc, 0xce, 0x16, 0xcb, 0xcf, 0xdf, 0xcb, 0x36, 0x7c, 0xf6, 0x38, 0x2c, 0xab, 0xdf, 0xb9, 0xbe, 0x95, 0x1c, 0xa6, 0x86, 0x42, 0xf7, 0xa2, 0x77, 0xd6, 0xc1, 0x23, 0xc3, 0x7f, 0x44, 0x60, 0xf1, 0xa1, 0x0a, 0x4b, 0xd3, 0xa5, 0x19, 0xfe, 0xf2, 0xd0, 0xb0, 0x31, 0x0e, 0x67, 0x7b, 0xef, 0x54, 0xdf, 0x3c, 0xeb, 0xf7, 0xff, 0x98, 0x09, 0x8f, 0x04, 0xff, 0x12, 0x03, 0x7d, 0xd5, 0xc6, 0x31, 0xa2, 0x72, 0xe1, 0x50, 0x65, 0xd8, 0x30, 0x30, 0xd1, 0xeb, 0xd2, 0xd1, 0xe2, 0xee, 0x8c, 0xa5, 0xe3, 0x4d, 0x53, 0xc7, 0x45, 0x07, 0x1a, 0xb1, 0x54, 0x90, 0xf7, 0x99, 0x88, 0x84, 0xae, 0x36, 0x00, 0x70, 0x94, 0xd4, 0xb0, 0xc1, 0x8c, 0xf1, 0xe4, 0x57, 0xac, 0xc1, 0xe4, 0x80, 0x58, 0xf8, 0xad, 0x34, 0x4c, 0x7e, 0xa6, 0x04, 0x2d, 0x4d, 0x96, 0x5d, 0x91, 0x3f, 0x9e, 0x4b, 0x43, 0x5d, 0xe9, 0x93, 0x46, 0x09, 0x9d, 0x6e, 0xff, 0xe5, 0x02, 0x06, 0xf4, 0x88, 0x70, 0x3f, 0xfb, 0xf7, 0x25, 0xc3, 0xba, 0x12, 0xd5, 0xb7, 0x03, 0xbd, 0x12, 0xfc, 0x5b, 0x0c, 0x28, 0x6a, 0x0a, 0x76, 0x10, 0x85, 0x0d, 0x81, 0x71, 0x74, 0xf7, 0x6d, 0x3f, 0xf8, 0xbb, 0x42, 0xb4, 0x33, 0xe4, 0xbd, 0xff, 0x7c, 0x6c, 0xc8, 0x4a, 0x32, 0x01, 0x34, 0xc1, 0x85, 0xba, 0x45, 0x28, 0xa7, 0x05, 0x71, 0x10, 0x0c, 0x0b, 0x0b, 0x04, 0x78, 0x36, 0x41, 0xc6, 0x23, 0x83, 0xcc, 0xce, 0x7f, 0xcb, 0x98, 0x59, 0x61, 0x80, 0x96, 0x9f, 0x00, 0xa3, 0x10, 0x58, 0xb7, 0x38, 0x04, 0x86, 0xbf, 0x63, 0x1a, 0xd8, 0x14, 0xcd, 0x04, 0x18, 0x15, 0x03, 0x05, 0x07, 0x0c, 0x81, 0x91, 0x57, 0xfc, 0xd0, 0x49, 0x13, 0x60, 0x00, 0x2d, 0x0f, 0x9a, 0xd3, 0x37, 0x00, 0xe6, 0x9a, 0x8f, 0x54, 0xc0, 0x98, 0x14, 0x5f, 0xa0, 0x8a, 0x0b, 0xa9, 0xf2, 0xf7, 0x04, 0x66, 0x41, 0x1a, 0x68, 0x96, 0x27, 0x78, 0x00, 0x80, 0x33, 0x2e, 0xef, 0x5f, 0x38, 0x7f, 0x39, 0x27, 0xcf, 0xef, 0xe3, 0x57, 0xab, 0xaa, 0x89, 0x4c, 0x4f, 0x7c, 0x6b, 0xd0, 0x4a, 0x96, 0x73, 0x5f, 0x41, 0x3f, 0x27, 0xee, 0x6d, 0x65, 0xe3, 0x7c, 0x0f, 0x20, 0xfb, 0x29, 0x15, 0x82, 0x6a, 0x6b, 0xda, 0x37, 0x8c, 0x31, 0x69, 0x10, 0x8c, 0x21, 0x39, 0x1e, 0x5f, 0x6f, 0x3c, 0xc0, 0x62, 0xf7, 0xac, 0x0d, 0xe0, 0x32, 0x63, 0x01, 0xf8, 0xdb, 0x60, 0x4f, 0x22, 0x2c, 0x9d, 0x0e, 0xdd, 0x13, 0x99, 0xb7, 0x0b, 0x7f, 0x2c, 0x1e, 0x9a, 0x44, 0x02, 0x40, 0xec, 0x9e, 0xb5, 0xe4, 0xa8, 0x69, 0xe2, 0x54, 0x2b, 0x13, 0x5e, 0x61, 0xfa, 0xdb, 0xfc, 0xa9, 0x52, 0x88, 0x4d, 0x0f, 0x67, 0x6c, 0x55, 0xfc, 0x72, 0x00, 0xd0, 0x6d, 0xfb, 0x09, 0xf5, 0x4f, 0x10, 0xae, 0x95, 0xe5, 0x97, 0x1f, 0x7e, 0xa4, 0xe4, 0x55, 0xae, 0x86, 0xec, 0x07, 0x61, 0x3c, 0x89, 0x07, 0x22, 0x82, 0xee, 0x8b, 0xb9, 0xb2, 0x7d, 0xd8, 0xcb, 0x33, 0xd7, 0xec, 0x44, 0x5a, 0x1e, 0xdb, 0xcf, 0x0c, 0xaf, 0xdf, 0x7f, 0x9f, 0x6a, 0x73, 0xca, 0x11, 0x16, 0x35, 0x79, 0x1c, 0xdb, 0x8a, 0x00, 0x9e, 0x03, 0xbf, 0x71, 0x61, 0xaf, 0xc6, 0xb4, 0xde, 0xf6, 0xdd, 0xa3, 0xd7, 0x80, 0x31, 0x14, 0x3c, 0x40, 0xd6, 0xf5, 0xef, 0x33, 0xfd, 0xee, 0xd5, 0x2b, 0x54, 0x5b, 0x53, 0xfe, 0xc0, 0xe5, 0x4c, 0xc3, 0xf8, 0x0b, 0x64, 0x99, 0x58, 0x44, 0x10, 0x54, 0x2f, 0xe5, 0x38, 0xf8, 0xdf, 0xe5, 0xa4, 0x47, 0x85, 0x84, 0x9f, 0xb2, 0x9d, 0xac, 0xfd, 0xee, 0x5c, 0xfb, 0xfa, 0x12, 0x72, 0x8f, 0x82, 0xdf, 0xb8, 0x80, 0x8b, 0xd0, 0x47, 0x2b, 0xe6, 0x4d, 0x07, 0xdb, 0x59, 0x5e, 0x65, 0x28, 0xdd, 0xf8, 0x12, 0x5f, 0x19, 0xf7, 0x03, 0x4b, 0x8c, 0x60, 0x19, 0xfa, 0x1c, 0xd5, 0xe6, 0x94, 0x33, 0xba, 0x69, 0x86, 0x1e, 0xfb, 0x89, 0x5a, 0x44, 0x65, 0xcd, 0xba, 0x39, 0x30, 0x03, 0x32, 0x6f, 0x3a, 0xc8, 0x62, 0xf2, 0xd6, 0x90, 0xb9, 0xae, 0xf1, 0x0d, 0xb6, 0xfd, 0x8b, 0x6c, 0x9c, 0x6f, 0x4d, 0x84, 0x4b, 0x52, 0xd3, 0x55, 0x4f, 0xdf, 0x1a, 0x8e, 0x44, 0x63, 0x77, 0xfb, 0x96, 0x01, 0x50, 0xab, 0x00, 0x2d, 0x0f, 0x16, 0x1c, 0x00, 0x72, 0xba, 0x6b, 0xf9, 0xa7, 0xd2, 0x1c, 0xd1, 0xcf, 0xdf, 0xb5, 0x74, 0xa0, 0x2d, 0xdf, 0xe8, 0xd2, 0xef, 0x95, 0xd9, 0x54, 0xc7, 0x62, 0xfa, 0xdf, 0x78, 0xb4, 0xd5, 0x5f, 0x79, 0x10, 0x1f, 0x37, 0xe8, 0xc4, 0xe3, 0x0d, 0x60, 0x17, 0xdb, 0x41, 0xad, 0x3d, 0x63, 0x77, 0x91, 0x2b, 0x80, 0x03, 0x8b, 0x9a, 0x02, 0xcc, 0x8b, 0x80, 0x7a, 0xcd, 0xac, 0xc0, 0xa8, 0x75, 0xe9, 0x2f, 0x0c, 0x1c, 0xb2, 0x55, 0x37, 0x20, 0x3a, 0x29, 0xce, 0x3b, 0xf7, 0x11, 0x3e, 0xad, 0xf2, 0x9b, 0x26, 0xfe, 0x2f, 0xb6, 0x4c, 0xe3, 0xc3, 0xd6, 0x89, 0xb3, 0x90, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82, }; static const int cloud_png_len = 1962; static const unsigned char favicon_png[] = { 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x10, 0x08, 0x06, 0x00, 0x00, 0x00, 0x1f, 0xf3, 0xff, 0x61, 0x00, 0x00, 0x00, 0x06, 0x62, 0x4b, 0x47, 0x44, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0xa0, 0xbd, 0xa7, 0x93, 0x00, 0x00, 0x00, 0x09, 0x70, 0x48, 0x59, 0x73, 0x00, 0x00, 0x0b, 0x13, 0x00, 0x00, 0x0b, 0x13, 0x01, 0x00, 0x9a, 0x9c, 0x18, 0x00, 0x00, 0x00, 0x07, 0x74, 0x49, 0x4d, 0x45, 0x07, 0xde, 0x03, 0x0d, 0x0f, 0x0e, 0x04, 0xc3, 0x98, 0xdb, 0x58, 0x00, 0x00, 0x00, 0x19, 0x74, 0x45, 0x58, 0x74, 0x43, 0x6f, 0x6d, 0x6d, 0x65, 0x6e, 0x74, 0x00, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68, 0x20, 0x47, 0x49, 0x4d, 0x50, 0x57, 0x81, 0x0e, 0x17, 0x00, 0x00, 0x01, 0xef, 0x49, 0x44, 0x41, 0x54, 0x38, 0xcb, 0xb5, 0x93, 0xbd, 0x6b, 0x53, 0x61, 0x14, 0xc6, 0x7f, 0xe7, 0x4d, 0x6e, 0x5b, 0x0d, 0x92, 0x34, 0xd6, 0x41, 0xd3, 0x42, 0xc5, 0x48, 0x41, 0x0a, 0x7e, 0x20, 0x41, 0xbc, 0xb1, 0xe0, 0xe2, 0x9f, 0x20, 0x14, 0xba, 0x24, 0xb5, 0x76, 0xcb, 0xe8, 0xd2, 0x45, 0x5c, 0xa5, 0x8a, 0x08, 0x42, 0x4d, 0xc8, 0x85, 0x2e, 0x0e, 0xe2, 0xa0, 0x6e, 0x2a, 0x08, 0x7a, 0x2f, 0x16, 0xa1, 0xd0, 0x41, 0x41, 0x45, 0xea, 0xa0, 0x2d, 0x1d, 0x4c, 0x7b, 0x6b, 0x6d, 0x53, 0xf3, 0xf1, 0x1e, 0x07, 0x49, 0x07, 0x49, 0xb0, 0xa0, 0x3e, 0xdb, 0x7b, 0xe0, 0x79, 0x38, 0x0f, 0xe7, 0xf7, 0xc2, 0xbf, 0xd0, 0xd2, 0xb9, 0x3b, 0xfd, 0x95, 0x4c, 0x31, 0xd5, 0x7a, 0xaf, 0x8c, 0x14, 0x07, 0xbf, 0x9e, 0xf5, 0xce, 0xef, 0xc6, 0x1b, 0x5d, 0xcb, 0x96, 0xc6, 0x44, 0xcd, 0x2c, 0x5d, 0x2c, 0x86, 0xae, 0xd7, 0x6f, 0xa1, 0xa0, 0x0d, 0xfb, 0xc9, 0x18, 0x2e, 0x00, 0xcf, 0xff, 0x18, 0x00, 0x20, 0xca, 0x56, 0x3c, 0xc8, 0xa7, 0x43, 0xb7, 0xec, 0x19, 0x91, 0x09, 0xab, 0x72, 0xdd, 0xa8, 0x1e, 0xae, 0x64, 0x8a, 0xa9, 0x88, 0x13, 0x99, 0x11, 0x91, 0x61, 0x0b, 0xf7, 0xb7, 0xa4, 0x7a, 0x2b, 0x66, 0xf7, 0x94, 0x04, 0x1d, 0x52, 0x21, 0x48, 0xf8, 0xf9, 0x31, 0x03, 0xa0, 0xd0, 0xb3, 0xee, 0x7a, 0x4f, 0x45, 0xe4, 0xa2, 0xc2, 0x63, 0x20, 0x89, 0x48, 0x3a, 0xe2, 0x44, 0xa7, 0x80, 0x7d, 0x71, 0x3f, 0x37, 0xd8, 0x90, 0xda, 0x74, 0x4c, 0x7b, 0xa6, 0x00, 0x36, 0xb7, 0xeb, 0xc7, 0x44, 0x65, 0x64, 0xd5, 0xf5, 0x2e, 0x1b, 0x00, 0x84, 0x5a, 0x13, 0x7b, 0x75, 0x1b, 0x1d, 0xee, 0xf5, 0x73, 0xd7, 0x76, 0xf6, 0x13, 0x8d, 0x01, 0xab, 0x00, 0x07, 0x5e, 0x4e, 0xae, 0x00, 0x7b, 0x81, 0xd5, 0x43, 0xf3, 0x93, 0x55, 0x15, 0xdd, 0x34, 0x62, 0x63, 0xad, 0x0a, 0x36, 0x19, 0x8c, 0x07, 0xbf, 0xf7, 0xab, 0xd9, 0xc6, 0x8d, 0x6e, 0xe3, 0x3c, 0x0c, 0x5d, 0xef, 0xad, 0xa2, 0x73, 0xf5, 0xa6, 0xbd, 0xd9, 0x65, 0x22, 0x8f, 0x42, 0xb7, 0xfc, 0x5e, 0x90, 0xea, 0x16, 0xdf, 0x4b, 0xbb, 0xba, 0xd2, 0xe7, 0x33, 0x25, 0x87, 0xff, 0x25, 0xa9, 0x64, 0x8a, 0xa9, 0xed, 0xee, 0xba, 0xb4, 0x06, 0x46, 0x1b, 0xeb, 0x07, 0xfd, 0xc2, 0x06, 0x40, 0x25, 0x53, 0x4c, 0xa9, 0x63, 0x62, 0x7d, 0xc1, 0xf8, 0x87, 0x16, 0x2f, 0x3d, 0x3f, 0x1c, 0xdd, 0xff, 0x7a, 0x62, 0x69, 0x27, 0x20, 0xcc, 0x96, 0x3f, 0xa2, 0x12, 0x17, 0xa1, 0x4f, 0x61, 0x19, 0xd5, 0x17, 0x89, 0x20, 0x3f, 0x1a, 0x66, 0xcb, 0x4f, 0x80, 0x53, 0x82, 0x7c, 0x51, 0x58, 0x50, 0x9a, 0xcf, 0x04, 0x33, 0x0b, 0x2c, 0xa2, 0xd2, 0x6f, 0xa1, 0x90, 0x0c, 0x72, 0x77, 0x4d, 0xc2, 0xcf, 0xa7, 0x9b, 0x34, 0x46, 0x01, 0x12, 0x7e, 0x2e, 0xf5, 0xcb, 0xec, 0x5d, 0x01, 0x8e, 0x6f, 0x34, 0xec, 0xd1, 0xb8, 0x9f, 0x3b, 0x51, 0xa9, 0xd6, 0x0a, 0x2d, 0x5e, 0x12, 0x7e, 0x3e, 0x0d, 0x7a, 0xcf, 0x08, 0x13, 0x00, 0xa6, 0x5d, 0x2f, 0x55, 0x1d, 0x12, 0xe5, 0xcd, 0xc0, 0xdc, 0xa5, 0x35, 0x80, 0x23, 0xf3, 0x93, 0xdf, 0x3a, 0xf0, 0xd2, 0x3e, 0x00, 0x61, 0x01, 0x38, 0xd9, 0xfa, 0x1f, 0xcb, 0xee, 0xcc, 0x40, 0x27, 0x5e, 0xa2, 0xed, 0xfc, 0xbd, 0x7e, 0xfe, 0x76, 0x98, 0x2d, 0x9f, 0x8e, 0x3a, 0xd1, 0x77, 0x61, 0xd6, 0xdb, 0x44, 0xf5, 0x81, 0x62, 0x5f, 0x75, 0xe2, 0xe5, 0xaf, 0xf4, 0x13, 0x24, 0x76, 0xd9, 0x1b, 0x78, 0x6b, 0xa9, 0x70, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82, }; static const int favicon_png_len = 647; static const unsigned char index_html[] = { 0x3c, 0x21, 0x44, 0x4f, 0x43, 0x54, 0x59, 0x50, 0x45, 0x20, 0x68, 0x74, 0x6d, 0x6c, 0x20, 0x50, 0x55, 0x42, 0x4c, 0x49, 0x43, 0x20, 0x22, 0x2d, 0x2f, 0x2f, 0x57, 0x33, 0x43, 0x2f, 0x2f, 0x44, 0x54, 0x44, 0x20, 0x58, 0x48, 0x54, 0x4d, 0x4c, 0x20, 0x31, 0x2e, 0x30, 0x20, 0x53, 0x74, 0x72, 0x69, 0x63, 0x74, 0x2f, 0x2f, 0x45, 0x4e, 0x22, 0x20, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x77, 0x33, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x54, 0x52, 0x2f, 0x78, 0x68, 0x74, 0x6d, 0x6c, 0x31, 0x2f, 0x44, 0x54, 0x44, 0x2f, 0x78, 0x68, 0x74, 0x6d, 0x6c, 0x31, 0x2d, 0x73, 0x74, 0x72, 0x69, 0x63, 0x74, 0x2e, 0x64, 0x74, 0x64, 0x22, 0x3e, 0x0a, 0x3c, 0x68, 0x74, 0x6d, 0x6c, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x77, 0x33, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x31, 0x39, 0x39, 0x39, 0x2f, 0x78, 0x68, 0x74, 0x6d, 0x6c, 0x22, 0x3e, 0x0a, 0x3c, 0x68, 0x65, 0x61, 0x64, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x6d, 0x65, 0x74, 0x61, 0x20, 0x68, 0x74, 0x74, 0x70, 0x2d, 0x65, 0x71, 0x75, 0x69, 0x76, 0x3d, 0x22, 0x43, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2d, 0x54, 0x79, 0x70, 0x65, 0x22, 0x20, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x3d, 0x22, 0x74, 0x65, 0x78, 0x74, 0x2f, 0x68, 0x74, 0x6d, 0x6c, 0x3b, 0x20, 0x63, 0x68, 0x61, 0x72, 0x73, 0x65, 0x74, 0x3d, 0x55, 0x54, 0x46, 0x2d, 0x38, 0x22, 0x20, 0x2f, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x74, 0x69, 0x74, 0x6c, 0x65, 0x3e, 0x50, 0x49, 0x43, 0x33, 0x32, 0x4d, 0x5a, 0x20, 0x53, 0x74, 0x61, 0x72, 0x74, 0x65, 0x72, 0x20, 0x4b, 0x69, 0x74, 0x3c, 0x2f, 0x74, 0x69, 0x74, 0x6c, 0x65, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x6d, 0x65, 0x74, 0x61, 0x20, 0x6e, 0x61, 0x6d, 0x65, 0x3d, 0x22, 0x6b, 0x65, 0x79, 0x77, 0x6f, 0x72, 0x64, 0x73, 0x22, 0x20, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x3d, 0x22, 0x22, 0x20, 0x2f, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x6d, 0x65, 0x74, 0x61, 0x20, 0x6e, 0x61, 0x6d, 0x65, 0x3d, 0x22, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x22, 0x20, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x3d, 0x22, 0x22, 0x20, 0x2f, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x6c, 0x69, 0x6e, 0x6b, 0x20, 0x72, 0x65, 0x6c, 0x3d, 0x22, 0x69, 0x63, 0x6f, 0x6e, 0x22, 0x20, 0x74, 0x79, 0x70, 0x65, 0x3d, 0x22, 0x69, 0x6d, 0x61, 0x67, 0x65, 0x2f, 0x70, 0x6e, 0x67, 0x22, 0x20, 0x68, 0x72, 0x65, 0x66, 0x3d, 0x22, 0x66, 0x61, 0x76, 0x69, 0x63, 0x6f, 0x6e, 0x2e, 0x70, 0x6e, 0x67, 0x22, 0x20, 0x2f, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x6c, 0x69, 0x6e, 0x6b, 0x20, 0x68, 0x72, 0x65, 0x66, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x66, 0x6f, 0x6e, 0x74, 0x73, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x63, 0x73, 0x73, 0x3f, 0x66, 0x61, 0x6d, 0x69, 0x6c, 0x79, 0x3d, 0x4f, 0x70, 0x65, 0x6e, 0x2b, 0x53, 0x61, 0x6e, 0x73, 0x3a, 0x34, 0x30, 0x30, 0x2c, 0x33, 0x30, 0x30, 0x2c, 0x36, 0x30, 0x30, 0x2c, 0x37, 0x30, 0x30, 0x2c, 0x38, 0x30, 0x30, 0x7c, 0x4f, 0x70, 0x65, 0x6e, 0x2b, 0x53, 0x61, 0x6e, 0x73, 0x2b, 0x43, 0x6f, 0x6e, 0x64, 0x65, 0x6e, 0x73, 0x65, 0x64, 0x3a, 0x33, 0x30, 0x30, 0x2c, 0x37, 0x30, 0x30, 0x22, 0x20, 0x72, 0x65, 0x6c, 0x3d, 0x22, 0x73, 0x74, 0x79, 0x6c, 0x65, 0x73, 0x68, 0x65, 0x65, 0x74, 0x22, 0x20, 0x2f, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x6c, 0x69, 0x6e, 0x6b, 0x20, 0x68, 0x72, 0x65, 0x66, 0x3d, 0x22, 0x70, 0x69, 0x63, 0x6f, 0x74, 0x63, 0x70, 0x5f, 0x73, 0x74, 0x79, 0x6c, 0x65, 0x2e, 0x63, 0x73, 0x73, 0x22, 0x20, 0x72, 0x65, 0x6c, 0x3d, 0x22, 0x73, 0x74, 0x79, 0x6c, 0x65, 0x73, 0x68, 0x65, 0x65, 0x74, 0x22, 0x20, 0x74, 0x79, 0x70, 0x65, 0x3d, 0x22, 0x74, 0x65, 0x78, 0x74, 0x2f, 0x63, 0x73, 0x73, 0x22, 0x20, 0x2f, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x20, 0x74, 0x79, 0x70, 0x65, 0x3d, 0x22, 0x74, 0x65, 0x78, 0x74, 0x2f, 0x6a, 0x61, 0x76, 0x61, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x22, 0x20, 0x73, 0x72, 0x63, 0x3d, 0x22, 0x62, 0x6f, 0x61, 0x72, 0x64, 0x2e, 0x6a, 0x73, 0x22, 0x3e, 0x3c, 0x2f, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x3e, 0x0a, 0x3c, 0x2f, 0x68, 0x65, 0x61, 0x64, 0x3e, 0x0a, 0x0a, 0x3c, 0x62, 0x6f, 0x64, 0x79, 0x20, 0x6f, 0x6e, 0x6c, 0x6f, 0x61, 0x64, 0x3d, 0x22, 0x75, 0x70, 0x64, 0x61, 0x74, 0x65, 0x42, 0x6f, 0x61, 0x72, 0x64, 0x49, 0x6e, 0x66, 0x6f, 0x28, 0x29, 0x3b, 0x67, 0x65, 0x74, 0x49, 0x70, 0x28, 0x29, 0x3b, 0x67, 0x65, 0x74, 0x4d, 0x41, 0x43, 0x28, 0x29, 0x22, 0x3e, 0x0a, 0x0a, 0x3c, 0x64, 0x69, 0x76, 0x20, 0x69, 0x64, 0x3d, 0x22, 0x6c, 0x6f, 0x67, 0x6f, 0x22, 0x20, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x3d, 0x22, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x68, 0x31, 0x3e, 0x3c, 0x69, 0x6d, 0x67, 0x20, 0x61, 0x6c, 0x74, 0x3d, 0x22, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x22, 0x20, 0x73, 0x72, 0x63, 0x3d, 0x22, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2e, 0x70, 0x6e, 0x67, 0x22, 0x20, 0x2f, 0x3e, 0x3c, 0x61, 0x20, 0x68, 0x72, 0x65, 0x66, 0x3d, 0x22, 0x2f, 0x22, 0x3e, 0x50, 0x69, 0x63, 0x6f, 0x3c, 0x73, 0x70, 0x61, 0x6e, 0x3e, 0x54, 0x43, 0x50, 0x3c, 0x2f, 0x73, 0x70, 0x61, 0x6e, 0x3e, 0x3c, 0x2f, 0x61, 0x3e, 0x3c, 0x2f, 0x68, 0x31, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x70, 0x3e, 0x70, 0x72, 0x70, 0x6c, 0x48, 0x79, 0x70, 0x65, 0x72, 0x76, 0x69, 0x73, 0x6f, 0x72, 0x20, 0x57, 0x65, 0x62, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x20, 0x53, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x3c, 0x2f, 0x70, 0x3e, 0x0a, 0x3c, 0x2f, 0x64, 0x69, 0x76, 0x3e, 0x0a, 0x0a, 0x3c, 0x64, 0x69, 0x76, 0x20, 0x69, 0x64, 0x3d, 0x22, 0x77, 0x72, 0x61, 0x70, 0x70, 0x65, 0x72, 0x22, 0x20, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x3d, 0x22, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x64, 0x69, 0x76, 0x20, 0x69, 0x64, 0x3d, 0x22, 0x6d, 0x65, 0x6e, 0x75, 0x22, 0x20, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x3d, 0x22, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x75, 0x6c, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x6c, 0x69, 0x20, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x3d, 0x22, 0x63, 0x75, 0x72, 0x72, 0x65, 0x6e, 0x74, 0x5f, 0x70, 0x61, 0x67, 0x65, 0x5f, 0x69, 0x74, 0x65, 0x6d, 0x22, 0x3e, 0x3c, 0x61, 0x20, 0x68, 0x72, 0x65, 0x66, 0x3d, 0x22, 0x70, 0x69, 0x63, 0x33, 0x32, 0x6d, 0x7a, 0x2e, 0x68, 0x74, 0x6d, 0x6c, 0x22, 0x20, 0x74, 0x69, 0x74, 0x6c, 0x65, 0x3d, 0x22, 0x22, 0x3e, 0x50, 0x49, 0x43, 0x33, 0x32, 0x4d, 0x5a, 0x20, 0x53, 0x74, 0x61, 0x72, 0x74, 0x65, 0x72, 0x20, 0x4b, 0x69, 0x74, 0x3c, 0x2f, 0x61, 0x3e, 0x3c, 0x2f, 0x6c, 0x69, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x2f, 0x75, 0x6c, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x2f, 0x64, 0x69, 0x76, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x64, 0x69, 0x76, 0x20, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x3d, 0x22, 0x63, 0x65, 0x6e, 0x74, 0x65, 0x72, 0x2d, 0x63, 0x6f, 0x6c, 0x75, 0x6d, 0x6e, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x69, 0x6d, 0x67, 0x20, 0x73, 0x72, 0x63, 0x3d, 0x22, 0x70, 0x69, 0x63, 0x33, 0x32, 0x6d, 0x7a, 0x2e, 0x6a, 0x70, 0x67, 0x22, 0x20, 0x61, 0x6c, 0x74, 0x3d, 0x22, 0x50, 0x49, 0x43, 0x33, 0x32, 0x6d, 0x7a, 0x20, 0x53, 0x74, 0x61, 0x72, 0x74, 0x65, 0x72, 0x20, 0x4b, 0x69, 0x74, 0x22, 0x2f, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x2f, 0x64, 0x69, 0x76, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x64, 0x69, 0x76, 0x20, 0x69, 0x64, 0x3d, 0x22, 0x74, 0x68, 0x72, 0x65, 0x65, 0x2d, 0x63, 0x6f, 0x6c, 0x75, 0x6d, 0x6e, 0x22, 0x20, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x3d, 0x22, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x64, 0x69, 0x76, 0x20, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x3d, 0x22, 0x74, 0x77, 0x6f, 0x2d, 0x63, 0x6f, 0x6c, 0x75, 0x6d, 0x6e, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x70, 0x20, 0x69, 0x64, 0x3d, 0x22, 0x6d, 0x79, 0x5f, 0x69, 0x70, 0x22, 0x3e, 0x3c, 0x62, 0x3e, 0x49, 0x50, 0x3a, 0x3c, 0x2f, 0x62, 0x3e, 0x20, 0x3c, 0x73, 0x70, 0x61, 0x6e, 0x20, 0x69, 0x64, 0x3d, 0x22, 0x69, 0x70, 0x22, 0x3e, 0x3c, 0x2f, 0x73, 0x70, 0x61, 0x6e, 0x3e, 0x3c, 0x2f, 0x70, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x70, 0x20, 0x69, 0x64, 0x3d, 0x22, 0x6d, 0x79, 0x5f, 0x6d, 0x61, 0x63, 0x22, 0x3e, 0x3c, 0x62, 0x3e, 0x4d, 0x41, 0x43, 0x20, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x3a, 0x3c, 0x2f, 0x62, 0x3e, 0x20, 0x3c, 0x73, 0x70, 0x61, 0x6e, 0x20, 0x69, 0x64, 0x3d, 0x22, 0x6d, 0x61, 0x63, 0x22, 0x3e, 0x3c, 0x2f, 0x73, 0x70, 0x61, 0x6e, 0x3e, 0x3c, 0x2f, 0x70, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x70, 0x20, 0x69, 0x64, 0x3d, 0x22, 0x6d, 0x79, 0x5f, 0x75, 0x70, 0x74, 0x69, 0x6d, 0x65, 0x22, 0x3e, 0x3c, 0x62, 0x3e, 0x55, 0x70, 0x74, 0x69, 0x6d, 0x65, 0x3a, 0x3c, 0x2f, 0x62, 0x3e, 0x20, 0x3c, 0x73, 0x70, 0x61, 0x6e, 0x20, 0x69, 0x64, 0x3d, 0x22, 0x75, 0x70, 0x74, 0x69, 0x6d, 0x65, 0x22, 0x3e, 0x30, 0x20, 0x73, 0x65, 0x63, 0x6f, 0x6e, 0x64, 0x73, 0x3c, 0x2f, 0x73, 0x70, 0x61, 0x6e, 0x3e, 0x3c, 0x2f, 0x70, 0x3e, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x70, 0x3e, 0x3c, 0x73, 0x70, 0x61, 0x6e, 0x20, 0x69, 0x64, 0x3d, 0x22, 0x6c, 0x65, 0x64, 0x31, 0x5f, 0x73, 0x74, 0x61, 0x74, 0x65, 0x22, 0x3e, 0x4c, 0x45, 0x44, 0x20, 0x31, 0x3c, 0x2f, 0x73, 0x70, 0x61, 0x6e, 0x3e, 0x3c, 0x2f, 0x70, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x70, 0x3e, 0x3c, 0x73, 0x70, 0x61, 0x6e, 0x20, 0x69, 0x64, 0x3d, 0x22, 0x6c, 0x65, 0x64, 0x32, 0x5f, 0x73, 0x74, 0x61, 0x74, 0x65, 0x22, 0x3e, 0x4c, 0x45, 0x44, 0x20, 0x32, 0x3c, 0x2f, 0x73, 0x70, 0x61, 0x6e, 0x3e, 0x3c, 0x2f, 0x70, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x2f, 0x64, 0x69, 0x76, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x64, 0x69, 0x76, 0x20, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x3d, 0x22, 0x74, 0x77, 0x6f, 0x2d, 0x63, 0x6f, 0x6c, 0x75, 0x6d, 0x6e, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x64, 0x69, 0x76, 0x20, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x3d, 0x22, 0x62, 0x75, 0x74, 0x74, 0x6f, 0x6e, 0x22, 0x20, 0x6f, 0x6e, 0x63, 0x6c, 0x69, 0x63, 0x6b, 0x3d, 0x22, 0x74, 0x6f, 0x67, 0x67, 0x6c, 0x65, 0x5f, 0x6c, 0x65, 0x64, 0x31, 0x28, 0x29, 0x22, 0x3e, 0x54, 0x6f, 0x67, 0x67, 0x6c, 0x65, 0x20, 0x4c, 0x45, 0x44, 0x20, 0x31, 0x3c, 0x2f, 0x64, 0x69, 0x76, 0x3e, 0x20, 0x3c, 0x62, 0x72, 0x2f, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x64, 0x69, 0x76, 0x20, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x3d, 0x22, 0x62, 0x75, 0x74, 0x74, 0x6f, 0x6e, 0x22, 0x20, 0x6f, 0x6e, 0x63, 0x6c, 0x69, 0x63, 0x6b, 0x3d, 0x22, 0x74, 0x6f, 0x67, 0x67, 0x6c, 0x65, 0x5f, 0x6c, 0x65, 0x64, 0x32, 0x28, 0x29, 0x22, 0x3e, 0x54, 0x6f, 0x67, 0x67, 0x6c, 0x65, 0x20, 0x4c, 0x45, 0x44, 0x20, 0x32, 0x3c, 0x2f, 0x64, 0x69, 0x76, 0x3e, 0x20, 0x3c, 0x62, 0x72, 0x2f, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x2f, 0x64, 0x69, 0x76, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x2f, 0x64, 0x69, 0x76, 0x3e, 0x0a, 0x3c, 0x2f, 0x64, 0x69, 0x76, 0x3e, 0x0a, 0x3c, 0x64, 0x69, 0x76, 0x20, 0x69, 0x64, 0x3d, 0x22, 0x63, 0x6f, 0x70, 0x79, 0x72, 0x69, 0x67, 0x68, 0x74, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x70, 0x3e, 0x45, 0x6d, 0x62, 0x65, 0x64, 0x64, 0x65, 0x64, 0x20, 0x53, 0x79, 0x73, 0x74, 0x65, 0x6d, 0x73, 0x20, 0x47, 0x72, 0x6f, 0x75, 0x70, 0x20, 0x28, 0x47, 0x53, 0x45, 0x29, 0x20, 0x2d, 0x20, 0x50, 0x55, 0x43, 0x52, 0x53, 0x20, 0x2d, 0x20, 0x42, 0x72, 0x61, 0x7a, 0x69, 0x6c, 0x2e, 0x20, 0x7c, 0x20, 0x41, 0x64, 0x61, 0x70, 0x74, 0x61, 0x64, 0x65, 0x64, 0x20, 0x66, 0x72, 0x6f, 0x6d, 0x20, 0x68, 0x74, 0x74, 0x70, 0x73, 0x3a, 0x2f, 0x2f, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x74, 0x61, 0x73, 0x73, 0x2d, 0x62, 0x65, 0x6c, 0x67, 0x69, 0x75, 0x6d, 0x2f, 0x63, 0x79, 0x61, 0x73, 0x73, 0x6c, 0x2d, 0x70, 0x69, 0x63, 0x6f, 0x74, 0x63, 0x70, 0x2e, 0x67, 0x69, 0x74, 0x20, 0x3c, 0x2f, 0x70, 0x3e, 0x0a, 0x3c, 0x2f, 0x64, 0x69, 0x76, 0x3e, 0x0a, 0x3c, 0x2f, 0x62, 0x6f, 0x64, 0x79, 0x3e, 0x0a, 0x3c, 0x2f, 0x68, 0x74, 0x6d, 0x6c, 0x3e, 0x0a, }; static const int index_html_len = 2086; static const unsigned char picotcp_style_css[] = { 0x2f, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2f, 0x0d, 0x0a, 0x2f, 0x2a, 0x20, 0x47, 0x6c, 0x6f, 0x62, 0x61, 0x6c, 0x20, 0x76, 0x61, 0x72, 0x69, 0x61, 0x62, 0x6c, 0x65, 0x73, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x2a, 0x2f, 0x0d, 0x0a, 0x2f, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2f, 0x0d, 0x0a, 0x68, 0x74, 0x6d, 0x6c, 0x2c, 0x0d, 0x0a, 0x62, 0x6f, 0x64, 0x79, 0x20, 0x7b, 0x0d, 0x0a, 0x20, 0x20, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x3a, 0x20, 0x31, 0x30, 0x30, 0x25, 0x3b, 0x0d, 0x0a, 0x7d, 0x0d, 0x0a, 0x62, 0x6f, 0x64, 0x79, 0x20, 0x7b, 0x0d, 0x0a, 0x20, 0x20, 0x6d, 0x61, 0x72, 0x67, 0x69, 0x6e, 0x3a, 0x20, 0x30, 0x70, 0x78, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x70, 0x61, 0x64, 0x64, 0x69, 0x6e, 0x67, 0x3a, 0x20, 0x30, 0x70, 0x78, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x62, 0x61, 0x63, 0x6b, 0x67, 0x72, 0x6f, 0x75, 0x6e, 0x64, 0x3a, 0x20, 0x23, 0x65, 0x39, 0x65, 0x39, 0x65, 0x39, 0x20, 0x75, 0x72, 0x6c, 0x28, 0x62, 0x67, 0x5f, 0x73, 0x74, 0x72, 0x69, 0x70, 0x65, 0x2e, 0x70, 0x6e, 0x67, 0x29, 0x20, 0x72, 0x65, 0x70, 0x65, 0x61, 0x74, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x66, 0x6f, 0x6e, 0x74, 0x2d, 0x66, 0x61, 0x6d, 0x69, 0x6c, 0x79, 0x3a, 0x20, 0x27, 0x4f, 0x70, 0x65, 0x6e, 0x20, 0x53, 0x61, 0x6e, 0x73, 0x27, 0x2c, 0x20, 0x27, 0x44, 0x72, 0x6f, 0x69, 0x64, 0x20, 0x53, 0x61, 0x6e, 0x73, 0x27, 0x2c, 0x20, 0x73, 0x61, 0x6e, 0x73, 0x2d, 0x73, 0x65, 0x72, 0x69, 0x66, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x66, 0x6f, 0x6e, 0x74, 0x2d, 0x73, 0x69, 0x7a, 0x65, 0x3a, 0x20, 0x31, 0x31, 0x70, 0x74, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x66, 0x6f, 0x6e, 0x74, 0x2d, 0x77, 0x65, 0x69, 0x67, 0x68, 0x74, 0x3a, 0x20, 0x34, 0x30, 0x30, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x63, 0x6f, 0x6c, 0x6f, 0x72, 0x3a, 0x20, 0x23, 0x39, 0x36, 0x39, 0x36, 0x39, 0x36, 0x3b, 0x0d, 0x0a, 0x7d, 0x0d, 0x0a, 0x68, 0x31, 0x2c, 0x0d, 0x0a, 0x68, 0x32, 0x2c, 0x0d, 0x0a, 0x68, 0x33, 0x20, 0x7b, 0x0d, 0x0a, 0x20, 0x20, 0x6d, 0x61, 0x72, 0x67, 0x69, 0x6e, 0x3a, 0x20, 0x30, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x70, 0x61, 0x64, 0x64, 0x69, 0x6e, 0x67, 0x3a, 0x20, 0x30, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x66, 0x6f, 0x6e, 0x74, 0x2d, 0x77, 0x65, 0x69, 0x67, 0x68, 0x74, 0x3a, 0x20, 0x39, 0x30, 0x30, 0x3b, 0x0d, 0x0a, 0x7d, 0x0d, 0x0a, 0x70, 0x2c, 0x0d, 0x0a, 0x6f, 0x6c, 0x2c, 0x0d, 0x0a, 0x75, 0x6c, 0x20, 0x7b, 0x0d, 0x0a, 0x20, 0x20, 0x6d, 0x61, 0x72, 0x67, 0x69, 0x6e, 0x2d, 0x74, 0x6f, 0x70, 0x3a, 0x20, 0x30, 0x3b, 0x0d, 0x0a, 0x7d, 0x0d, 0x0a, 0x6f, 0x6c, 0x2c, 0x0d, 0x0a, 0x75, 0x6c, 0x20, 0x7b, 0x0d, 0x0a, 0x20, 0x20, 0x70, 0x61, 0x64, 0x64, 0x69, 0x6e, 0x67, 0x3a, 0x20, 0x30, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x6c, 0x69, 0x73, 0x74, 0x2d, 0x73, 0x74, 0x79, 0x6c, 0x65, 0x3a, 0x20, 0x6e, 0x6f, 0x6e, 0x65, 0x3b, 0x0d, 0x0a, 0x7d, 0x0d, 0x0a, 0x70, 0x20, 0x7b, 0x0d, 0x0a, 0x20, 0x20, 0x6c, 0x69, 0x6e, 0x65, 0x2d, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x3a, 0x20, 0x31, 0x38, 0x30, 0x25, 0x3b, 0x0d, 0x0a, 0x7d, 0x0d, 0x0a, 0x61, 0x20, 0x7b, 0x0d, 0x0a, 0x20, 0x20, 0x63, 0x6f, 0x6c, 0x6f, 0x72, 0x3a, 0x20, 0x23, 0x30, 0x30, 0x30, 0x30, 0x46, 0x46, 0x3b, 0x0d, 0x0a, 0x7d, 0x0d, 0x0a, 0x61, 0x3a, 0x68, 0x6f, 0x76, 0x65, 0x72, 0x20, 0x7b, 0x0d, 0x0a, 0x20, 0x20, 0x74, 0x65, 0x78, 0x74, 0x2d, 0x64, 0x65, 0x63, 0x6f, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x3a, 0x20, 0x6e, 0x6f, 0x6e, 0x65, 0x3b, 0x0d, 0x0a, 0x7d, 0x0d, 0x0a, 0x2e, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, 0x20, 0x7b, 0x0d, 0x0a, 0x20, 0x20, 0x6d, 0x61, 0x72, 0x67, 0x69, 0x6e, 0x3a, 0x20, 0x30, 0x70, 0x78, 0x20, 0x61, 0x75, 0x74, 0x6f, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3a, 0x20, 0x31, 0x32, 0x30, 0x30, 0x70, 0x78, 0x3b, 0x0d, 0x0a, 0x7d, 0x0d, 0x0a, 0x2f, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2f, 0x0d, 0x0a, 0x2f, 0x2a, 0x20, 0x42, 0x75, 0x74, 0x74, 0x6f, 0x6e, 0x20, 0x53, 0x74, 0x79, 0x6c, 0x65, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x2a, 0x2f, 0x0d, 0x0a, 0x2f, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2f, 0x0d, 0x0a, 0x2e, 0x62, 0x75, 0x74, 0x74, 0x6f, 0x6e, 0x20, 0x7b, 0x0d, 0x0a, 0x20, 0x20, 0x64, 0x69, 0x73, 0x70, 0x6c, 0x61, 0x79, 0x3a, 0x20, 0x69, 0x6e, 0x6c, 0x69, 0x6e, 0x65, 0x2d, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x62, 0x61, 0x63, 0x6b, 0x67, 0x72, 0x6f, 0x75, 0x6e, 0x64, 0x3a, 0x20, 0x23, 0x46, 0x31, 0x33, 0x43, 0x39, 0x46, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x62, 0x6f, 0x72, 0x64, 0x65, 0x72, 0x2d, 0x72, 0x61, 0x64, 0x69, 0x75, 0x73, 0x3a, 0x20, 0x35, 0x70, 0x78, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x6c, 0x69, 0x6e, 0x65, 0x2d, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x3a, 0x20, 0x34, 0x65, 0x6d, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x70, 0x61, 0x64, 0x64, 0x69, 0x6e, 0x67, 0x3a, 0x20, 0x30, 0x20, 0x33, 0x65, 0x6d, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x2d, 0x77, 0x65, 0x62, 0x6b, 0x69, 0x74, 0x2d, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x3a, 0x20, 0x61, 0x6c, 0x6c, 0x20, 0x30, 0x2e, 0x32, 0x35, 0x73, 0x20, 0x65, 0x61, 0x73, 0x65, 0x2d, 0x69, 0x6e, 0x2d, 0x6f, 0x75, 0x74, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x2d, 0x6d, 0x6f, 0x7a, 0x2d, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x3a, 0x20, 0x61, 0x6c, 0x6c, 0x20, 0x30, 0x2e, 0x32, 0x35, 0x73, 0x20, 0x65, 0x61, 0x73, 0x65, 0x2d, 0x69, 0x6e, 0x2d, 0x6f, 0x75, 0x74, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x2d, 0x6d, 0x73, 0x2d, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x3a, 0x20, 0x61, 0x6c, 0x6c, 0x20, 0x30, 0x2e, 0x32, 0x35, 0x73, 0x20, 0x65, 0x61, 0x73, 0x65, 0x2d, 0x69, 0x6e, 0x2d, 0x6f, 0x75, 0x74, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x2d, 0x6f, 0x2d, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x3a, 0x20, 0x61, 0x6c, 0x6c, 0x20, 0x30, 0x2e, 0x32, 0x35, 0x73, 0x20, 0x65, 0x61, 0x73, 0x65, 0x2d, 0x69, 0x6e, 0x2d, 0x6f, 0x75, 0x74, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x3a, 0x20, 0x61, 0x6c, 0x6c, 0x20, 0x30, 0x2e, 0x32, 0x35, 0x73, 0x20, 0x65, 0x61, 0x73, 0x65, 0x2d, 0x69, 0x6e, 0x2d, 0x6f, 0x75, 0x74, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x6c, 0x65, 0x74, 0x74, 0x65, 0x72, 0x2d, 0x73, 0x70, 0x61, 0x63, 0x69, 0x6e, 0x67, 0x3a, 0x20, 0x30, 0x2e, 0x32, 0x35, 0x65, 0x6d, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x74, 0x65, 0x78, 0x74, 0x2d, 0x64, 0x65, 0x63, 0x6f, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x3a, 0x20, 0x6e, 0x6f, 0x6e, 0x65, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x74, 0x65, 0x78, 0x74, 0x2d, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x66, 0x6f, 0x72, 0x6d, 0x3a, 0x20, 0x75, 0x70, 0x70, 0x65, 0x72, 0x63, 0x61, 0x73, 0x65, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x6f, 0x75, 0x74, 0x6c, 0x69, 0x6e, 0x65, 0x3a, 0x20, 0x30, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x77, 0x68, 0x69, 0x74, 0x65, 0x2d, 0x73, 0x70, 0x61, 0x63, 0x65, 0x3a, 0x20, 0x6e, 0x6f, 0x77, 0x72, 0x61, 0x70, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x66, 0x6f, 0x6e, 0x74, 0x2d, 0x77, 0x65, 0x69, 0x67, 0x68, 0x74, 0x3a, 0x20, 0x39, 0x30, 0x30, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x66, 0x6f, 0x6e, 0x74, 0x2d, 0x73, 0x69, 0x7a, 0x65, 0x3a, 0x20, 0x31, 0x65, 0x6d, 0x20, 0x21, 0x69, 0x6d, 0x70, 0x6f, 0x72, 0x74, 0x61, 0x6e, 0x74, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x63, 0x6f, 0x6c, 0x6f, 0x72, 0x3a, 0x20, 0x23, 0x66, 0x66, 0x66, 0x20, 0x21, 0x69, 0x6d, 0x70, 0x6f, 0x72, 0x74, 0x61, 0x6e, 0x74, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x63, 0x75, 0x72, 0x73, 0x6f, 0x72, 0x3a, 0x20, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x3b, 0x0d, 0x0a, 0x7d, 0x0d, 0x0a, 0x2e, 0x62, 0x75, 0x74, 0x74, 0x6f, 0x6e, 0x3a, 0x68, 0x6f, 0x76, 0x65, 0x72, 0x20, 0x7b, 0x0d, 0x0a, 0x20, 0x20, 0x62, 0x61, 0x63, 0x6b, 0x67, 0x72, 0x6f, 0x75, 0x6e, 0x64, 0x3a, 0x20, 0x23, 0x31, 0x38, 0x41, 0x43, 0x44, 0x39, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x2d, 0x77, 0x65, 0x62, 0x6b, 0x69, 0x74, 0x2d, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x3a, 0x20, 0x61, 0x6c, 0x6c, 0x20, 0x30, 0x2e, 0x32, 0x35, 0x73, 0x20, 0x65, 0x61, 0x73, 0x65, 0x2d, 0x69, 0x6e, 0x2d, 0x6f, 0x75, 0x74, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x2d, 0x6d, 0x6f, 0x7a, 0x2d, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x3a, 0x20, 0x61, 0x6c, 0x6c, 0x20, 0x30, 0x2e, 0x32, 0x35, 0x73, 0x20, 0x65, 0x61, 0x73, 0x65, 0x2d, 0x69, 0x6e, 0x2d, 0x6f, 0x75, 0x74, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x2d, 0x6d, 0x73, 0x2d, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x3a, 0x20, 0x61, 0x6c, 0x6c, 0x20, 0x30, 0x2e, 0x32, 0x35, 0x73, 0x20, 0x65, 0x61, 0x73, 0x65, 0x2d, 0x69, 0x6e, 0x2d, 0x6f, 0x75, 0x74, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x2d, 0x6f, 0x2d, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x3a, 0x20, 0x61, 0x6c, 0x6c, 0x20, 0x30, 0x2e, 0x32, 0x35, 0x73, 0x20, 0x65, 0x61, 0x73, 0x65, 0x2d, 0x69, 0x6e, 0x2d, 0x6f, 0x75, 0x74, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x3a, 0x20, 0x61, 0x6c, 0x6c, 0x20, 0x30, 0x2e, 0x32, 0x35, 0x73, 0x20, 0x65, 0x61, 0x73, 0x65, 0x2d, 0x69, 0x6e, 0x2d, 0x6f, 0x75, 0x74, 0x3b, 0x0d, 0x0a, 0x7d, 0x0d, 0x0a, 0x2e, 0x62, 0x75, 0x74, 0x74, 0x6f, 0x6e, 0x3a, 0x61, 0x63, 0x74, 0x69, 0x76, 0x65, 0x20, 0x7b, 0x0d, 0x0a, 0x20, 0x20, 0x62, 0x61, 0x63, 0x6b, 0x67, 0x72, 0x6f, 0x75, 0x6e, 0x64, 0x3a, 0x20, 0x23, 0x30, 0x30, 0x39, 0x31, 0x42, 0x44, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x2d, 0x77, 0x65, 0x62, 0x6b, 0x69, 0x74, 0x2d, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x3a, 0x20, 0x61, 0x6c, 0x6c, 0x20, 0x30, 0x2e, 0x32, 0x35, 0x73, 0x20, 0x65, 0x61, 0x73, 0x65, 0x2d, 0x69, 0x6e, 0x2d, 0x6f, 0x75, 0x74, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x2d, 0x6d, 0x6f, 0x7a, 0x2d, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x3a, 0x20, 0x61, 0x6c, 0x6c, 0x20, 0x30, 0x2e, 0x32, 0x35, 0x73, 0x20, 0x65, 0x61, 0x73, 0x65, 0x2d, 0x69, 0x6e, 0x2d, 0x6f, 0x75, 0x74, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x2d, 0x6d, 0x73, 0x2d, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x3a, 0x20, 0x61, 0x6c, 0x6c, 0x20, 0x30, 0x2e, 0x32, 0x35, 0x73, 0x20, 0x65, 0x61, 0x73, 0x65, 0x2d, 0x69, 0x6e, 0x2d, 0x6f, 0x75, 0x74, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x2d, 0x6f, 0x2d, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x3a, 0x20, 0x61, 0x6c, 0x6c, 0x20, 0x30, 0x2e, 0x32, 0x35, 0x73, 0x20, 0x65, 0x61, 0x73, 0x65, 0x2d, 0x69, 0x6e, 0x2d, 0x6f, 0x75, 0x74, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x3a, 0x20, 0x61, 0x6c, 0x6c, 0x20, 0x30, 0x2e, 0x32, 0x35, 0x73, 0x20, 0x65, 0x61, 0x73, 0x65, 0x2d, 0x69, 0x6e, 0x2d, 0x6f, 0x75, 0x74, 0x3b, 0x0d, 0x0a, 0x7d, 0x0d, 0x0a, 0x2f, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2f, 0x0d, 0x0a, 0x2f, 0x2a, 0x20, 0x57, 0x72, 0x61, 0x70, 0x70, 0x65, 0x72, 0x73, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x2a, 0x2f, 0x0d, 0x0a, 0x2f, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2f, 0x0d, 0x0a, 0x23, 0x77, 0x72, 0x61, 0x70, 0x70, 0x65, 0x72, 0x20, 0x7b, 0x0d, 0x0a, 0x20, 0x20, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x3a, 0x20, 0x72, 0x65, 0x6c, 0x61, 0x74, 0x69, 0x76, 0x65, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x70, 0x61, 0x64, 0x64, 0x69, 0x6e, 0x67, 0x3a, 0x20, 0x30, 0x65, 0x6d, 0x20, 0x30, 0x65, 0x6d, 0x20, 0x32, 0x65, 0x6d, 0x20, 0x30, 0x65, 0x6d, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x62, 0x61, 0x63, 0x6b, 0x67, 0x72, 0x6f, 0x75, 0x6e, 0x64, 0x3a, 0x20, 0x23, 0x46, 0x46, 0x46, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x62, 0x6f, 0x78, 0x2d, 0x73, 0x68, 0x61, 0x64, 0x6f, 0x77, 0x3a, 0x20, 0x30, 0x70, 0x78, 0x20, 0x30, 0x70, 0x78, 0x20, 0x31, 0x30, 0x70, 0x78, 0x20, 0x35, 0x70, 0x78, 0x20, 0x72, 0x67, 0x62, 0x61, 0x28, 0x30, 0x2c, 0x20, 0x30, 0x2c, 0x20, 0x30, 0x2c, 0x20, 0x30, 0x2e, 0x31, 0x29, 0x3b, 0x0d, 0x0a, 0x7d, 0x0d, 0x0a, 0x2f, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2f, 0x0d, 0x0a, 0x2f, 0x2a, 0x20, 0x4c, 0x6f, 0x67, 0x6f, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x2a, 0x2f, 0x0d, 0x0a, 0x2f, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2f, 0x0d, 0x0a, 0x23, 0x6c, 0x6f, 0x67, 0x6f, 0x20, 0x7b, 0x0d, 0x0a, 0x20, 0x20, 0x6d, 0x61, 0x72, 0x67, 0x69, 0x6e, 0x3a, 0x20, 0x30, 0x2e, 0x35, 0x65, 0x6d, 0x20, 0x61, 0x75, 0x74, 0x6f, 0x20, 0x30, 0x2e, 0x35, 0x65, 0x6d, 0x20, 0x61, 0x75, 0x74, 0x6f, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x74, 0x65, 0x78, 0x74, 0x2d, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x66, 0x6f, 0x72, 0x6d, 0x3a, 0x20, 0x75, 0x70, 0x70, 0x65, 0x72, 0x63, 0x61, 0x73, 0x65, 0x3b, 0x0d, 0x0a, 0x7d, 0x0d, 0x0a, 0x23, 0x6c, 0x6f, 0x67, 0x6f, 0x20, 0x68, 0x31, 0x20, 0x7b, 0x0d, 0x0a, 0x20, 0x20, 0x66, 0x6f, 0x6e, 0x74, 0x2d, 0x73, 0x69, 0x7a, 0x65, 0x3a, 0x20, 0x32, 0x2e, 0x32, 0x65, 0x6d, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x63, 0x6f, 0x6c, 0x6f, 0x72, 0x3a, 0x20, 0x23, 0x32, 0x39, 0x32, 0x39, 0x32, 0x39, 0x3b, 0x0d, 0x0a, 0x7d, 0x0d, 0x0a, 0x23, 0x6c, 0x6f, 0x67, 0x6f, 0x20, 0x68, 0x31, 0x20, 0x61, 0x20, 0x7b, 0x0d, 0x0a, 0x20, 0x20, 0x6d, 0x61, 0x72, 0x67, 0x69, 0x6e, 0x2d, 0x6c, 0x65, 0x66, 0x74, 0x3a, 0x20, 0x30, 0x2e, 0x35, 0x30, 0x65, 0x6d, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x74, 0x65, 0x78, 0x74, 0x2d, 0x64, 0x65, 0x63, 0x6f, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x3a, 0x20, 0x6e, 0x6f, 0x6e, 0x65, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x66, 0x6f, 0x6e, 0x74, 0x2d, 0x73, 0x69, 0x7a, 0x65, 0x3a, 0x20, 0x31, 0x2e, 0x35, 0x65, 0x6d, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x63, 0x6f, 0x6c, 0x6f, 0x72, 0x3a, 0x20, 0x23, 0x32, 0x39, 0x32, 0x39, 0x32, 0x39, 0x3b, 0x0d, 0x0a, 0x7d, 0x0d, 0x0a, 0x23, 0x6c, 0x6f, 0x67, 0x6f, 0x20, 0x73, 0x70, 0x61, 0x6e, 0x20, 0x7b, 0x0d, 0x0a, 0x20, 0x20, 0x63, 0x6f, 0x6c, 0x6f, 0x72, 0x3a, 0x20, 0x23, 0x45, 0x32, 0x30, 0x30, 0x37, 0x41, 0x3b, 0x0d, 0x0a, 0x7d, 0x0d, 0x0a, 0x23, 0x6c, 0x6f, 0x67, 0x6f, 0x20, 0x2e, 0x69, 0x63, 0x6f, 0x6e, 0x2d, 0x73, 0x69, 0x7a, 0x65, 0x20, 0x7b, 0x0d, 0x0a, 0x20, 0x20, 0x70, 0x61, 0x64, 0x64, 0x69, 0x6e, 0x67, 0x2d, 0x74, 0x6f, 0x70, 0x3a, 0x20, 0x30, 0x2e, 0x32, 0x30, 0x65, 0x6d, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x66, 0x6f, 0x6e, 0x74, 0x2d, 0x73, 0x69, 0x7a, 0x65, 0x3a, 0x20, 0x32, 0x65, 0x6d, 0x20, 0x21, 0x69, 0x6d, 0x70, 0x6f, 0x72, 0x74, 0x61, 0x6e, 0x74, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x63, 0x6f, 0x6c, 0x6f, 0x72, 0x3a, 0x20, 0x23, 0x45, 0x32, 0x30, 0x30, 0x37, 0x41, 0x3b, 0x0d, 0x0a, 0x7d, 0x0d, 0x0a, 0x23, 0x6c, 0x6f, 0x67, 0x6f, 0x20, 0x70, 0x20, 0x7b, 0x0d, 0x0a, 0x20, 0x20, 0x6d, 0x61, 0x72, 0x67, 0x69, 0x6e, 0x3a, 0x20, 0x30, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x70, 0x61, 0x64, 0x64, 0x69, 0x6e, 0x67, 0x3a, 0x20, 0x30, 0x20, 0x30, 0x20, 0x30, 0x20, 0x35, 0x65, 0x6d, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x6c, 0x65, 0x74, 0x74, 0x65, 0x72, 0x2d, 0x73, 0x70, 0x61, 0x63, 0x69, 0x6e, 0x67, 0x3a, 0x20, 0x30, 0x2e, 0x31, 0x30, 0x65, 0x6d, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x66, 0x6f, 0x6e, 0x74, 0x2d, 0x73, 0x69, 0x7a, 0x65, 0x3a, 0x20, 0x30, 0x2e, 0x39, 0x30, 0x65, 0x6d, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x63, 0x6f, 0x6c, 0x6f, 0x72, 0x3a, 0x20, 0x23, 0x38, 0x32, 0x38, 0x32, 0x38, 0x32, 0x3b, 0x0d, 0x0a, 0x7d, 0x0d, 0x0a, 0x23, 0x6c, 0x6f, 0x67, 0x6f, 0x20, 0x70, 0x20, 0x61, 0x20, 0x7b, 0x0d, 0x0a, 0x20, 0x20, 0x74, 0x65, 0x78, 0x74, 0x2d, 0x64, 0x65, 0x63, 0x6f, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x3a, 0x20, 0x6e, 0x6f, 0x6e, 0x65, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x63, 0x6f, 0x6c, 0x6f, 0x72, 0x3a, 0x20, 0x23, 0x38, 0x32, 0x38, 0x32, 0x38, 0x32, 0x3b, 0x0d, 0x0a, 0x7d, 0x0d, 0x0a, 0x2f, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2f, 0x0d, 0x0a, 0x2f, 0x2a, 0x20, 0x4d, 0x65, 0x6e, 0x75, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x2a, 0x2f, 0x0d, 0x0a, 0x2f, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2f, 0x0d, 0x0a, 0x23, 0x6d, 0x65, 0x6e, 0x75, 0x20, 0x7b, 0x0d, 0x0a, 0x20, 0x20, 0x62, 0x61, 0x63, 0x6b, 0x67, 0x72, 0x6f, 0x75, 0x6e, 0x64, 0x3a, 0x20, 0x23, 0x32, 0x39, 0x32, 0x39, 0x32, 0x39, 0x3b, 0x0d, 0x0a, 0x7d, 0x0d, 0x0a, 0x23, 0x6d, 0x65, 0x6e, 0x75, 0x20, 0x75, 0x6c, 0x20, 0x7b, 0x0d, 0x0a, 0x20, 0x20, 0x6d, 0x61, 0x72, 0x67, 0x69, 0x6e, 0x3a, 0x20, 0x30, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x70, 0x61, 0x64, 0x64, 0x69, 0x6e, 0x67, 0x3a, 0x20, 0x30, 0x70, 0x78, 0x20, 0x30, 0x70, 0x78, 0x20, 0x30, 0x70, 0x78, 0x20, 0x30, 0x70, 0x78, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x6c, 0x69, 0x73, 0x74, 0x2d, 0x73, 0x74, 0x79, 0x6c, 0x65, 0x3a, 0x20, 0x6e, 0x6f, 0x6e, 0x65, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x6c, 0x69, 0x6e, 0x65, 0x2d, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x3a, 0x20, 0x6e, 0x6f, 0x72, 0x6d, 0x61, 0x6c, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x74, 0x65, 0x78, 0x74, 0x2d, 0x61, 0x6c, 0x69, 0x67, 0x6e, 0x3a, 0x20, 0x63, 0x65, 0x6e, 0x74, 0x65, 0x72, 0x3b, 0x0d, 0x0a, 0x7d, 0x0d, 0x0a, 0x23, 0x6d, 0x65, 0x6e, 0x75, 0x20, 0x6c, 0x69, 0x20, 0x7b, 0x0d, 0x0a, 0x20, 0x20, 0x64, 0x69, 0x73, 0x70, 0x6c, 0x61, 0x79, 0x3a, 0x20, 0x69, 0x6e, 0x6c, 0x69, 0x6e, 0x65, 0x2d, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x3b, 0x0d, 0x0a, 0x7d, 0x0d, 0x0a, 0x23, 0x6d, 0x65, 0x6e, 0x75, 0x20, 0x61, 0x20, 0x7b, 0x0d, 0x0a, 0x20, 0x20, 0x64, 0x69, 0x73, 0x70, 0x6c, 0x61, 0x79, 0x3a, 0x20, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x70, 0x61, 0x64, 0x64, 0x69, 0x6e, 0x67, 0x3a, 0x20, 0x30, 0x65, 0x6d, 0x20, 0x32, 0x65, 0x6d, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x6c, 0x69, 0x6e, 0x65, 0x2d, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x3a, 0x20, 0x36, 0x30, 0x70, 0x78, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x6c, 0x65, 0x74, 0x74, 0x65, 0x72, 0x2d, 0x73, 0x70, 0x61, 0x63, 0x69, 0x6e, 0x67, 0x3a, 0x20, 0x31, 0x70, 0x78, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x74, 0x65, 0x78, 0x74, 0x2d, 0x64, 0x65, 0x63, 0x6f, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x3a, 0x20, 0x6e, 0x6f, 0x6e, 0x65, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x74, 0x65, 0x78, 0x74, 0x2d, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x66, 0x6f, 0x72, 0x6d, 0x3a, 0x20, 0x75, 0x70, 0x70, 0x65, 0x72, 0x63, 0x61, 0x73, 0x65, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x66, 0x6f, 0x6e, 0x74, 0x2d, 0x73, 0x69, 0x7a, 0x65, 0x3a, 0x20, 0x31, 0x65, 0x6d, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x66, 0x6f, 0x6e, 0x74, 0x2d, 0x77, 0x65, 0x69, 0x67, 0x68, 0x74, 0x3a, 0x20, 0x37, 0x30, 0x30, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x63, 0x6f, 0x6c, 0x6f, 0x72, 0x3a, 0x20, 0x23, 0x38, 0x33, 0x38, 0x33, 0x38, 0x33, 0x3b, 0x0d, 0x0a, 0x7d, 0x0d, 0x0a, 0x23, 0x6d, 0x65, 0x6e, 0x75, 0x20, 0x2e, 0x63, 0x75, 0x72, 0x72, 0x65, 0x6e, 0x74, 0x5f, 0x70, 0x61, 0x67, 0x65, 0x5f, 0x69, 0x74, 0x65, 0x6d, 0x20, 0x61, 0x20, 0x7b, 0x0d, 0x0a, 0x20, 0x20, 0x62, 0x61, 0x63, 0x6b, 0x67, 0x72, 0x6f, 0x75, 0x6e, 0x64, 0x3a, 0x20, 0x23, 0x45, 0x32, 0x30, 0x30, 0x37, 0x41, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x63, 0x6f, 0x6c, 0x6f, 0x72, 0x3a, 0x20, 0x23, 0x46, 0x46, 0x46, 0x3b, 0x0d, 0x0a, 0x7d, 0x0d, 0x0a, 0x23, 0x6d, 0x65, 0x6e, 0x75, 0x20, 0x61, 0x3a, 0x68, 0x6f, 0x76, 0x65, 0x72, 0x20, 0x7b, 0x0d, 0x0a, 0x20, 0x20, 0x74, 0x65, 0x78, 0x74, 0x2d, 0x64, 0x65, 0x63, 0x6f, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x3a, 0x20, 0x6e, 0x6f, 0x6e, 0x65, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x63, 0x6f, 0x6c, 0x6f, 0x72, 0x3a, 0x20, 0x23, 0x46, 0x46, 0x46, 0x3b, 0x0d, 0x0a, 0x7d, 0x0d, 0x0a, 0x2e, 0x61, 0x72, 0x72, 0x6f, 0x77, 0x2d, 0x64, 0x6f, 0x77, 0x6e, 0x20, 0x7b, 0x0d, 0x0a, 0x20, 0x20, 0x6d, 0x61, 0x72, 0x67, 0x69, 0x6e, 0x3a, 0x20, 0x30, 0x20, 0x61, 0x75, 0x74, 0x6f, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3a, 0x20, 0x30, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x3a, 0x20, 0x30, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x62, 0x6f, 0x72, 0x64, 0x65, 0x72, 0x2d, 0x74, 0x6f, 0x70, 0x3a, 0x20, 0x34, 0x30, 0x70, 0x78, 0x20, 0x73, 0x6f, 0x6c, 0x69, 0x64, 0x20, 0x23, 0x46, 0x46, 0x46, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x62, 0x6f, 0x72, 0x64, 0x65, 0x72, 0x2d, 0x6c, 0x65, 0x66, 0x74, 0x3a, 0x20, 0x35, 0x30, 0x70, 0x78, 0x20, 0x73, 0x6f, 0x6c, 0x69, 0x64, 0x20, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x62, 0x6f, 0x72, 0x64, 0x65, 0x72, 0x2d, 0x72, 0x69, 0x67, 0x68, 0x74, 0x3a, 0x20, 0x35, 0x30, 0x70, 0x78, 0x20, 0x73, 0x6f, 0x6c, 0x69, 0x64, 0x20, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x64, 0x69, 0x73, 0x70, 0x6c, 0x61, 0x79, 0x3a, 0x20, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x74, 0x65, 0x78, 0x74, 0x2d, 0x61, 0x6c, 0x69, 0x67, 0x6e, 0x3a, 0x20, 0x63, 0x65, 0x6e, 0x74, 0x65, 0x72, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x62, 0x6f, 0x72, 0x64, 0x65, 0x72, 0x2d, 0x74, 0x6f, 0x70, 0x2d, 0x63, 0x6f, 0x6c, 0x6f, 0x72, 0x3a, 0x20, 0x23, 0x32, 0x39, 0x32, 0x39, 0x32, 0x39, 0x3b, 0x0d, 0x0a, 0x7d, 0x0d, 0x0a, 0x2f, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2f, 0x0d, 0x0a, 0x2f, 0x2a, 0x20, 0x43, 0x6f, 0x70, 0x79, 0x72, 0x69, 0x67, 0x68, 0x74, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x2a, 0x2f, 0x0d, 0x0a, 0x2f, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2f, 0x0d, 0x0a, 0x23, 0x6c, 0x65, 0x64, 0x31, 0x5f, 0x73, 0x74, 0x61, 0x74, 0x65, 0x20, 0x7b, 0x0d, 0x0a, 0x20, 0x20, 0x63, 0x6f, 0x6c, 0x6f, 0x72, 0x3a, 0x77, 0x68, 0x69, 0x74, 0x65, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x62, 0x61, 0x63, 0x6b, 0x67, 0x72, 0x6f, 0x75, 0x6e, 0x64, 0x2d, 0x63, 0x6f, 0x6c, 0x6f, 0x72, 0x3a, 0x23, 0x30, 0x30, 0x32, 0x32, 0x30, 0x30, 0x3b, 0x0d, 0x0a, 0x7d, 0x0d, 0x0a, 0x23, 0x6c, 0x65, 0x64, 0x32, 0x5f, 0x73, 0x74, 0x61, 0x74, 0x65, 0x20, 0x7b, 0x0d, 0x0a, 0x20, 0x20, 0x63, 0x6f, 0x6c, 0x6f, 0x72, 0x3a, 0x77, 0x68, 0x69, 0x74, 0x65, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x62, 0x61, 0x63, 0x6b, 0x67, 0x72, 0x6f, 0x75, 0x6e, 0x64, 0x2d, 0x63, 0x6f, 0x6c, 0x6f, 0x72, 0x3a, 0x23, 0x30, 0x30, 0x30, 0x30, 0x32, 0x32, 0x3b, 0x0d, 0x0a, 0x7d, 0x0d, 0x0a, 0x23, 0x6c, 0x65, 0x64, 0x33, 0x5f, 0x73, 0x74, 0x61, 0x74, 0x65, 0x20, 0x7b, 0x0d, 0x0a, 0x20, 0x20, 0x63, 0x6f, 0x6c, 0x6f, 0x72, 0x3a, 0x77, 0x68, 0x69, 0x74, 0x65, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x62, 0x61, 0x63, 0x6b, 0x67, 0x72, 0x6f, 0x75, 0x6e, 0x64, 0x2d, 0x63, 0x6f, 0x6c, 0x6f, 0x72, 0x3a, 0x23, 0x32, 0x32, 0x31, 0x31, 0x30, 0x30, 0x3b, 0x0d, 0x0a, 0x7d, 0x0d, 0x0a, 0x23, 0x6c, 0x65, 0x64, 0x34, 0x5f, 0x73, 0x74, 0x61, 0x74, 0x65, 0x20, 0x7b, 0x0d, 0x0a, 0x20, 0x20, 0x63, 0x6f, 0x6c, 0x6f, 0x72, 0x3a, 0x77, 0x68, 0x69, 0x74, 0x65, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x62, 0x61, 0x63, 0x6b, 0x67, 0x72, 0x6f, 0x75, 0x6e, 0x64, 0x2d, 0x63, 0x6f, 0x6c, 0x6f, 0x72, 0x3a, 0x23, 0x32, 0x32, 0x30, 0x30, 0x30, 0x30, 0x3b, 0x0d, 0x0a, 0x7d, 0x0d, 0x0a, 0x2f, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2f, 0x0d, 0x0a, 0x2f, 0x2a, 0x20, 0x43, 0x6f, 0x70, 0x79, 0x72, 0x69, 0x67, 0x68, 0x74, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x2a, 0x2f, 0x0d, 0x0a, 0x2f, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2f, 0x0d, 0x0a, 0x23, 0x63, 0x6f, 0x70, 0x79, 0x72, 0x69, 0x67, 0x68, 0x74, 0x20, 0x7b, 0x0d, 0x0a, 0x20, 0x20, 0x70, 0x61, 0x64, 0x64, 0x69, 0x6e, 0x67, 0x3a, 0x20, 0x36, 0x65, 0x6d, 0x20, 0x30, 0x65, 0x6d, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x66, 0x6f, 0x6e, 0x74, 0x2d, 0x73, 0x69, 0x7a, 0x65, 0x3a, 0x20, 0x30, 0x2e, 0x37, 0x30, 0x65, 0x6d, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x6c, 0x65, 0x74, 0x74, 0x65, 0x72, 0x2d, 0x73, 0x70, 0x61, 0x63, 0x69, 0x6e, 0x67, 0x3a, 0x20, 0x30, 0x2e, 0x32, 0x30, 0x65, 0x6d, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x74, 0x65, 0x78, 0x74, 0x2d, 0x61, 0x6c, 0x69, 0x67, 0x6e, 0x3a, 0x20, 0x63, 0x65, 0x6e, 0x74, 0x65, 0x72, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x74, 0x65, 0x78, 0x74, 0x2d, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x66, 0x6f, 0x72, 0x6d, 0x3a, 0x20, 0x75, 0x70, 0x70, 0x65, 0x72, 0x63, 0x61, 0x73, 0x65, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x74, 0x65, 0x78, 0x74, 0x2d, 0x73, 0x68, 0x61, 0x64, 0x6f, 0x77, 0x3a, 0x20, 0x31, 0x70, 0x78, 0x20, 0x31, 0x70, 0x78, 0x20, 0x31, 0x70, 0x78, 0x20, 0x23, 0x46, 0x46, 0x46, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x63, 0x6f, 0x6c, 0x6f, 0x72, 0x3a, 0x20, 0x23, 0x36, 0x41, 0x36, 0x41, 0x36, 0x41, 0x3b, 0x0d, 0x0a, 0x7d, 0x0d, 0x0a, 0x23, 0x63, 0x6f, 0x70, 0x79, 0x72, 0x69, 0x67, 0x68, 0x74, 0x20, 0x61, 0x20, 0x7b, 0x0d, 0x0a, 0x20, 0x20, 0x63, 0x6f, 0x6c, 0x6f, 0x72, 0x3a, 0x20, 0x23, 0x37, 0x34, 0x37, 0x34, 0x37, 0x34, 0x3b, 0x0d, 0x0a, 0x7d, 0x0d, 0x0a, 0x2f, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2f, 0x0d, 0x0a, 0x2f, 0x2a, 0x20, 0x43, 0x6f, 0x6c, 0x75, 0x6d, 0x6e, 0x73, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x2a, 0x2f, 0x0d, 0x0a, 0x2f, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2f, 0x0d, 0x0a, 0x23, 0x74, 0x68, 0x72, 0x65, 0x65, 0x2d, 0x63, 0x6f, 0x6c, 0x75, 0x6d, 0x6e, 0x20, 0x7b, 0x0d, 0x0a, 0x20, 0x20, 0x6f, 0x76, 0x65, 0x72, 0x66, 0x6c, 0x6f, 0x77, 0x3a, 0x20, 0x68, 0x69, 0x64, 0x64, 0x65, 0x6e, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x74, 0x65, 0x78, 0x74, 0x2d, 0x61, 0x6c, 0x69, 0x67, 0x6e, 0x3a, 0x20, 0x63, 0x65, 0x6e, 0x74, 0x65, 0x72, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x63, 0x6f, 0x6c, 0x6f, 0x72, 0x3a, 0x20, 0x23, 0x35, 0x32, 0x35, 0x32, 0x35, 0x32, 0x3b, 0x0d, 0x0a, 0x7d, 0x0d, 0x0a, 0x23, 0x74, 0x68, 0x72, 0x65, 0x65, 0x2d, 0x63, 0x6f, 0x6c, 0x75, 0x6d, 0x6e, 0x20, 0x68, 0x32, 0x20, 0x7b, 0x0d, 0x0a, 0x20, 0x20, 0x6d, 0x61, 0x72, 0x67, 0x69, 0x6e, 0x3a, 0x20, 0x31, 0x65, 0x6d, 0x20, 0x30, 0x65, 0x6d, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x74, 0x65, 0x78, 0x74, 0x2d, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x66, 0x6f, 0x72, 0x6d, 0x3a, 0x20, 0x75, 0x70, 0x70, 0x65, 0x72, 0x63, 0x61, 0x73, 0x65, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x66, 0x6f, 0x6e, 0x74, 0x2d, 0x73, 0x69, 0x7a, 0x65, 0x3a, 0x20, 0x31, 0x2e, 0x35, 0x65, 0x6d, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x66, 0x6f, 0x6e, 0x74, 0x2d, 0x77, 0x65, 0x69, 0x67, 0x68, 0x74, 0x3a, 0x20, 0x37, 0x30, 0x30, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x63, 0x6f, 0x6c, 0x6f, 0x72, 0x3a, 0x20, 0x23, 0x34, 0x35, 0x34, 0x34, 0x34, 0x35, 0x3b, 0x0d, 0x0a, 0x7d, 0x0d, 0x0a, 0x23, 0x74, 0x68, 0x72, 0x65, 0x65, 0x2d, 0x63, 0x6f, 0x6c, 0x75, 0x6d, 0x6e, 0x20, 0x2e, 0x69, 0x63, 0x6f, 0x6e, 0x20, 0x7b, 0x0d, 0x0a, 0x20, 0x20, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x3a, 0x20, 0x72, 0x65, 0x6c, 0x61, 0x74, 0x69, 0x76, 0x65, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x64, 0x69, 0x73, 0x70, 0x6c, 0x61, 0x79, 0x3a, 0x20, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x6d, 0x61, 0x72, 0x67, 0x69, 0x6e, 0x3a, 0x20, 0x30, 0x70, 0x78, 0x20, 0x61, 0x75, 0x74, 0x6f, 0x20, 0x30, 0x2e, 0x35, 0x65, 0x6d, 0x20, 0x61, 0x75, 0x74, 0x6f, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x6c, 0x69, 0x6e, 0x65, 0x2d, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x3a, 0x20, 0x31, 0x35, 0x30, 0x70, 0x78, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x66, 0x6f, 0x6e, 0x74, 0x2d, 0x73, 0x69, 0x7a, 0x65, 0x3a, 0x20, 0x34, 0x65, 0x6d, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x62, 0x61, 0x63, 0x6b, 0x67, 0x72, 0x6f, 0x75, 0x6e, 0x64, 0x3a, 0x20, 0x23, 0x46, 0x46, 0x46, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x62, 0x6f, 0x72, 0x64, 0x65, 0x72, 0x2d, 0x72, 0x61, 0x64, 0x69, 0x75, 0x73, 0x3a, 0x20, 0x31, 0x30, 0x30, 0x70, 0x78, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x62, 0x6f, 0x72, 0x64, 0x65, 0x72, 0x3a, 0x20, 0x36, 0x70, 0x78, 0x20, 0x73, 0x6f, 0x6c, 0x69, 0x64, 0x20, 0x23, 0x46, 0x31, 0x33, 0x43, 0x39, 0x46, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x74, 0x65, 0x78, 0x74, 0x2d, 0x61, 0x6c, 0x69, 0x67, 0x6e, 0x3a, 0x20, 0x63, 0x65, 0x6e, 0x74, 0x65, 0x72, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x63, 0x6f, 0x6c, 0x6f, 0x72, 0x3a, 0x20, 0x23, 0x46, 0x31, 0x33, 0x43, 0x39, 0x46, 0x3b, 0x0d, 0x0a, 0x7d, 0x0d, 0x0a, 0x23, 0x74, 0x68, 0x72, 0x65, 0x65, 0x2d, 0x63, 0x6f, 0x6c, 0x75, 0x6d, 0x6e, 0x20, 0x23, 0x74, 0x62, 0x6f, 0x78, 0x31, 0x2c, 0x0d, 0x0a, 0x23, 0x74, 0x68, 0x72, 0x65, 0x65, 0x2d, 0x63, 0x6f, 0x6c, 0x75, 0x6d, 0x6e, 0x20, 0x23, 0x74, 0x62, 0x6f, 0x78, 0x32, 0x2c, 0x0d, 0x0a, 0x23, 0x74, 0x68, 0x72, 0x65, 0x65, 0x2d, 0x63, 0x6f, 0x6c, 0x75, 0x6d, 0x6e, 0x20, 0x23, 0x74, 0x62, 0x6f, 0x78, 0x33, 0x20, 0x7b, 0x0d, 0x0a, 0x20, 0x20, 0x66, 0x6c, 0x6f, 0x61, 0x74, 0x3a, 0x20, 0x6c, 0x65, 0x66, 0x74, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3a, 0x20, 0x33, 0x32, 0x30, 0x70, 0x78, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x70, 0x61, 0x64, 0x64, 0x69, 0x6e, 0x67, 0x3a, 0x20, 0x33, 0x30, 0x70, 0x78, 0x20, 0x34, 0x30, 0x70, 0x78, 0x20, 0x32, 0x30, 0x70, 0x78, 0x20, 0x34, 0x30, 0x70, 0x78, 0x3b, 0x0d, 0x0a, 0x7d, 0x0d, 0x0a, 0x23, 0x74, 0x68, 0x72, 0x65, 0x65, 0x2d, 0x63, 0x6f, 0x6c, 0x75, 0x6d, 0x6e, 0x20, 0x2e, 0x74, 0x77, 0x6f, 0x2d, 0x63, 0x6f, 0x6c, 0x75, 0x6d, 0x6e, 0x20, 0x7b, 0x0d, 0x0a, 0x20, 0x20, 0x66, 0x6c, 0x6f, 0x61, 0x74, 0x3a, 0x20, 0x6c, 0x65, 0x66, 0x74, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3a, 0x20, 0x35, 0x32, 0x30, 0x70, 0x78, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x70, 0x61, 0x64, 0x64, 0x69, 0x6e, 0x67, 0x3a, 0x20, 0x33, 0x30, 0x70, 0x78, 0x20, 0x34, 0x30, 0x70, 0x78, 0x20, 0x32, 0x30, 0x70, 0x78, 0x20, 0x34, 0x30, 0x70, 0x78, 0x3b, 0x0d, 0x0a, 0x7d, 0x0d, 0x0a, 0x23, 0x74, 0x68, 0x72, 0x65, 0x65, 0x2d, 0x63, 0x6f, 0x6c, 0x75, 0x6d, 0x6e, 0x20, 0x2e, 0x74, 0x69, 0x74, 0x6c, 0x65, 0x20, 0x7b, 0x0d, 0x0a, 0x20, 0x20, 0x6c, 0x65, 0x74, 0x74, 0x65, 0x72, 0x2d, 0x73, 0x70, 0x61, 0x63, 0x69, 0x6e, 0x67, 0x3a, 0x20, 0x30, 0x2e, 0x31, 0x30, 0x65, 0x6d, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x74, 0x65, 0x78, 0x74, 0x2d, 0x61, 0x6c, 0x69, 0x67, 0x6e, 0x3a, 0x20, 0x63, 0x65, 0x6e, 0x74, 0x65, 0x72, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x74, 0x65, 0x78, 0x74, 0x2d, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x66, 0x6f, 0x72, 0x6d, 0x3a, 0x20, 0x75, 0x70, 0x70, 0x65, 0x72, 0x63, 0x61, 0x73, 0x65, 0x3b, 0x0d, 0x0a, 0x7d, 0x0d, 0x0a, 0x23, 0x74, 0x68, 0x72, 0x65, 0x65, 0x2d, 0x63, 0x6f, 0x6c, 0x75, 0x6d, 0x6e, 0x20, 0x2e, 0x74, 0x69, 0x74, 0x6c, 0x65, 0x20, 0x68, 0x32, 0x20, 0x7b, 0x0d, 0x0a, 0x20, 0x20, 0x66, 0x6f, 0x6e, 0x74, 0x2d, 0x73, 0x69, 0x7a, 0x65, 0x3a, 0x20, 0x31, 0x2e, 0x36, 0x30, 0x65, 0x6d, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x66, 0x6f, 0x6e, 0x74, 0x2d, 0x77, 0x65, 0x69, 0x67, 0x68, 0x74, 0x3a, 0x20, 0x39, 0x30, 0x30, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x66, 0x6f, 0x6e, 0x74, 0x2d, 0x66, 0x61, 0x6d, 0x69, 0x6c, 0x79, 0x3a, 0x20, 0x27, 0x4f, 0x70, 0x65, 0x6e, 0x20, 0x53, 0x61, 0x6e, 0x73, 0x27, 0x2c, 0x20, 0x73, 0x61, 0x6e, 0x73, 0x2d, 0x73, 0x65, 0x72, 0x69, 0x66, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x63, 0x6f, 0x6c, 0x6f, 0x72, 0x3a, 0x20, 0x23, 0x46, 0x31, 0x33, 0x43, 0x39, 0x46, 0x3b, 0x0d, 0x0a, 0x7d, 0x0d, 0x0a, 0x23, 0x74, 0x68, 0x72, 0x65, 0x65, 0x2d, 0x63, 0x6f, 0x6c, 0x75, 0x6d, 0x6e, 0x20, 0x2e, 0x74, 0x69, 0x74, 0x6c, 0x65, 0x20, 0x2e, 0x62, 0x79, 0x6c, 0x69, 0x6e, 0x65, 0x20, 0x7b, 0x0d, 0x0a, 0x20, 0x20, 0x70, 0x61, 0x64, 0x64, 0x69, 0x6e, 0x67, 0x2d, 0x74, 0x6f, 0x70, 0x3a, 0x20, 0x30, 0x2e, 0x35, 0x30, 0x65, 0x6d, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x66, 0x6f, 0x6e, 0x74, 0x2d, 0x73, 0x69, 0x7a, 0x65, 0x3a, 0x20, 0x30, 0x2e, 0x39, 0x30, 0x65, 0x6d, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x63, 0x6f, 0x6c, 0x6f, 0x72, 0x3a, 0x20, 0x23, 0x38, 0x35, 0x38, 0x35, 0x38, 0x35, 0x3b, 0x0d, 0x0a, 0x7d, 0x0d, 0x0a, 0x23, 0x74, 0x68, 0x72, 0x65, 0x65, 0x2d, 0x63, 0x6f, 0x6c, 0x75, 0x6d, 0x6e, 0x20, 0x69, 0x6e, 0x70, 0x75, 0x74, 0x20, 0x7b, 0x0d, 0x0a, 0x20, 0x20, 0x66, 0x6f, 0x6e, 0x74, 0x2d, 0x66, 0x61, 0x6d, 0x69, 0x6c, 0x79, 0x3a, 0x20, 0x27, 0x4f, 0x70, 0x65, 0x6e, 0x20, 0x53, 0x61, 0x6e, 0x73, 0x27, 0x2c, 0x20, 0x27, 0x44, 0x72, 0x6f, 0x69, 0x64, 0x20, 0x53, 0x61, 0x6e, 0x73, 0x27, 0x2c, 0x20, 0x73, 0x61, 0x6e, 0x73, 0x2d, 0x73, 0x65, 0x72, 0x69, 0x66, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x66, 0x6f, 0x6e, 0x74, 0x2d, 0x73, 0x69, 0x7a, 0x65, 0x3a, 0x20, 0x31, 0x65, 0x6d, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x74, 0x65, 0x78, 0x74, 0x2d, 0x61, 0x6c, 0x69, 0x67, 0x6e, 0x3a, 0x20, 0x63, 0x65, 0x6e, 0x74, 0x65, 0x72, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x62, 0x6f, 0x72, 0x64, 0x65, 0x72, 0x2d, 0x72, 0x61, 0x64, 0x69, 0x75, 0x73, 0x3a, 0x20, 0x35, 0x70, 0x78, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x70, 0x61, 0x64, 0x64, 0x69, 0x6e, 0x67, 0x3a, 0x20, 0x31, 0x65, 0x6d, 0x20, 0x30, 0x3b, 0x0d, 0x0a, 0x7d, 0x0d, 0x0a, 0x23, 0x74, 0x68, 0x72, 0x65, 0x65, 0x2d, 0x63, 0x6f, 0x6c, 0x75, 0x6d, 0x6e, 0x20, 0x70, 0x72, 0x6f, 0x67, 0x72, 0x65, 0x73, 0x73, 0x20, 0x7b, 0x0d, 0x0a, 0x20, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3a, 0x20, 0x33, 0x30, 0x30, 0x70, 0x78, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x3a, 0x20, 0x32, 0x30, 0x70, 0x78, 0x3b, 0x0d, 0x0a, 0x7d, 0x0d, 0x0a, 0x2e, 0x63, 0x65, 0x6e, 0x74, 0x65, 0x72, 0x2d, 0x63, 0x6f, 0x6c, 0x75, 0x6d, 0x6e, 0x20, 0x7b, 0x0d, 0x0a, 0x20, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3a, 0x20, 0x31, 0x30, 0x30, 0x25, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x70, 0x61, 0x64, 0x64, 0x69, 0x6e, 0x67, 0x3a, 0x20, 0x33, 0x30, 0x70, 0x78, 0x20, 0x30, 0x20, 0x30, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x74, 0x65, 0x78, 0x74, 0x2d, 0x61, 0x6c, 0x69, 0x67, 0x6e, 0x3a, 0x20, 0x63, 0x65, 0x6e, 0x74, 0x65, 0x72, 0x3b, 0x0d, 0x0a, 0x7d, 0x0d, 0x0a, 0x2f, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2f, 0x0d, 0x0a, 0x2f, 0x2a, 0x20, 0x54, 0x65, 0x72, 0x6d, 0x69, 0x6e, 0x61, 0x6c, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x2a, 0x2f, 0x0d, 0x0a, 0x2f, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2f, 0x0d, 0x0a, 0x2e, 0x74, 0x65, 0x72, 0x6d, 0x69, 0x6e, 0x61, 0x6c, 0x20, 0x7b, 0x0d, 0x0a, 0x20, 0x20, 0x63, 0x6f, 0x6c, 0x6f, 0x72, 0x3a, 0x20, 0x23, 0x61, 0x61, 0x61, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x66, 0x6f, 0x6e, 0x74, 0x2d, 0x66, 0x61, 0x6d, 0x69, 0x6c, 0x79, 0x3a, 0x20, 0x22, 0x44, 0x72, 0x6f, 0x69, 0x64, 0x20, 0x53, 0x61, 0x6e, 0x73, 0x20, 0x4d, 0x6f, 0x6e, 0x6f, 0x22, 0x2c, 0x20, 0x22, 0x43, 0x6f, 0x75, 0x72, 0x69, 0x65, 0x72, 0x20, 0x4e, 0x65, 0x77, 0x22, 0x2c, 0x20, 0x6d, 0x6f, 0x6e, 0x6f, 0x73, 0x70, 0x61, 0x63, 0x65, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x62, 0x61, 0x63, 0x6b, 0x67, 0x72, 0x6f, 0x75, 0x6e, 0x64, 0x2d, 0x63, 0x6f, 0x6c, 0x6f, 0x72, 0x3a, 0x20, 0x23, 0x30, 0x30, 0x30, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x62, 0x6f, 0x72, 0x64, 0x65, 0x72, 0x2d, 0x72, 0x61, 0x64, 0x69, 0x75, 0x73, 0x3a, 0x20, 0x31, 0x30, 0x70, 0x78, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x70, 0x61, 0x64, 0x64, 0x69, 0x6e, 0x67, 0x3a, 0x20, 0x31, 0x30, 0x70, 0x78, 0x20, 0x32, 0x25, 0x3b, 0x0d, 0x0a, 0x7d, 0x0d, 0x0a, 0x2e, 0x6f, 0x75, 0x74, 0x70, 0x75, 0x74, 0x20, 0x7b, 0x0d, 0x0a, 0x20, 0x20, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x3a, 0x20, 0x32, 0x30, 0x65, 0x6d, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x6f, 0x76, 0x65, 0x72, 0x66, 0x6c, 0x6f, 0x77, 0x3a, 0x20, 0x61, 0x75, 0x74, 0x6f, 0x3b, 0x0d, 0x0a, 0x7d, 0x0d, 0x0a, 0x2e, 0x69, 0x6e, 0x70, 0x75, 0x74, 0x20, 0x7b, 0x0d, 0x0a, 0x20, 0x20, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x3a, 0x20, 0x31, 0x65, 0x6d, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x62, 0x6f, 0x72, 0x64, 0x65, 0x72, 0x3a, 0x20, 0x30, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x6f, 0x75, 0x74, 0x6c, 0x69, 0x6e, 0x65, 0x3a, 0x20, 0x6e, 0x6f, 0x6e, 0x65, 0x3b, 0x0d, 0x0a, 0x20, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3a, 0x20, 0x39, 0x36, 0x25, 0x3b, 0x0d, 0x0a, 0x7d, 0x0d, 0x0a, 0x23, 0x74, 0x65, 0x72, 0x6d, 0x69, 0x6e, 0x61, 0x6c, 0x5f, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, 0x20, 0x7b, 0x0d, 0x0a, 0x20, 0x20, 0x6d, 0x61, 0x72, 0x67, 0x69, 0x6e, 0x3a, 0x20, 0x32, 0x30, 0x70, 0x78, 0x20, 0x38, 0x30, 0x70, 0x78, 0x20, 0x30, 0x70, 0x78, 0x3b, 0x0d, 0x0a, 0x7d, 0x0d, 0x0a, }; static const int picotcp_style_css_len = 7595; const struct web_file web_files[7] = { { "bg_stripe.png", &bg_stripe_png_len, bg_stripe_png, 1 }, { "pic32mz.jpg", &pic32mz_jpg_len, pic32mz_jpg, 1 }, { "board.js", &board_js_len, board_js, 1 }, { "cloud.png", &cloud_png_len, cloud_png, 1 }, { "favicon.png", &favicon_png_len, favicon_png, 1 }, { "index.html", &index_html_len, index_html, 1 }, { "picotcp_style.css", &picotcp_style_css_len, picotcp_style_css, 1 }, }; const int num_web_files = 7; <file_sep>#!/bin/bash # #Copyright (c) 2016, prpl Foundation # #Permission to use, copy, modify, and/or distribute this software for any purpose with or without #fee is hereby granted, provided that the above copyright notice and this permission notice appear #in all copies. # #THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE #INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE #FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM #LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, #ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # #This code was written by <NAME> at Embedded System Group (GSE) at PUCRS/Brazil. URL_BAIKAL=http://www.baikalelectronics.com/upload/iblock/35f/bsp_baikal_mips_4_00_08.run FILE=bsp_baikal_mips_4_00_08.run DOWNLOAD_DIR=~/baikal-bsp download_baikal(){ echo "************************************************************************************" echo "Downloading the Baikal BSP. After download follow the instructions on the screen." echo "************************************************************************************" echo wget -O $FILE $URL_BAIKAL chmod +x $FILE ./$FILE } # Make sure only root can run our script if [[ $EUID -ne 0 ]]; then echo "This script must be run as root." 1>&2 exit 1 fi apt-get update apt-get --yes --force-yes install srecord apt-get --yes --force-yes install libconfig-dev mkdir -p $DOWNLOAD_DIR pushd $DOWNLOAD_DIR if [ ! -f "$URL_BAIKAL" ]; then download_baikal; fi; popd echo >> ~/.profile echo "export PATH=\"\$PATH:\"$HOME/baikal-bsp/baikal/usr/x-tools/mipsel-unknown-linux-gnu/bin/\"\"" >> ~/.profile echo >> ~/.profile echo "***********************************************************" echo "You need to logout to the changes on you PATH make effect. " echo "***********************************************************" <file_sep>/* * Copyright (c) 2016, prpl Foundation * * Permission to use, copy, modify, and/or distribute this software for any purpose with or without * fee is hereby granted, provided that the above copyright notice and this permission notice appear * in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE * FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * * This code was written by <NAME> at Embedded System Group (GSE) at PUCRS/Brazil. * */ /** * This program decodes the csv file output from OLS LogicSniffer * to determine the interrupt average latency. * * */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <search.h> struct element { struct element *forward; struct element *backward; int *array; }; #define ARRAYSIZE 3 #define STRSZ 512 unsigned int rate = 0; static struct element * insert_element(struct element **header, int* array, int size){ struct element *e; static struct element *last = NULL; e = malloc(sizeof(struct element)); e->array = malloc(ARRAYSIZE*sizeof(int)); memcpy(e->array, array, ARRAYSIZE*sizeof(int)); insque(e, last); if (*header == NULL){ *header = e; } last = e; return *header; } int getlinearray3(FILE* arq, int* array, int size){ int i; char str[STRSZ]; char *pt; if (fgets(str, sizeof(str), arq) == NULL){ return 0; } pt = strtok (str,","); for(i=0; i<10 && pt!=NULL; i++){ if(i==0){ array[0] = atoi(pt); }else if(i==1){ rate = atoi(pt); }else if(i==7){ array[1] = atoi(pt); }else if(i==9){ array[2] = atoi(pt); } pt = strtok (NULL, ","); } return size; } int main(int argc, char**argv){ FILE* arq; int run=1; int linearray[ARRAYSIZE]; int oldarray[ARRAYSIZE] = {0, 0, 0}; char str[STRSZ]; int flag = 1; int flag2=0; unsigned int num_interrupts = 0; unsigned int total_delay = 0; struct element *header = NULL; struct element *p = NULL; struct element *aux = NULL; unsigned int work_case = 0, best_case = 999999999; if (argc < 2){ fprintf(stderr, "Usage: %s <input file>", argv[0]); return 0; } if ( (arq = fopen(argv[1], "r")) == NULL){ perror("fopen"); return 1; } /* drop off the first line of the file */ if (fgets(str, sizeof(str), arq) == NULL){ fprintf(stderr, "Wrong file format."); return 0; } while(!feof(arq)){ if (getlinearray3(arq, linearray, ARRAYSIZE) == 0){ break; } if( linearray[1] != oldarray[1] & flag){ insert_element(&header, linearray, ARRAYSIZE); while(!feof(arq) && linearray[1] != linearray[2]){ memcpy((char*)oldarray, (char*)linearray, ARRAYSIZE*sizeof(int)); if (getlinearray3(arq, linearray, ARRAYSIZE) == 0){ break; } flag2=1; } if(flag2){ insert_element(&header, linearray, ARRAYSIZE); flag2=0; } flag = 0; continue; }else{ flag=1; } memcpy((char*)oldarray, (char*)linearray, ARRAYSIZE*sizeof(int)); } p = header; while(p){ if(p->array[1] == p->array[2]){ num_interrupts++; }else{ num_interrupts++; aux = p; p = p->forward; if(!p) break; total_delay += p->array[0] - aux->array[0]; if(work_case < p->array[0] - aux->array[0]){ work_case = p->array[0] - aux->array[0]; } if(best_case > p->array[0] - aux->array[0]){ best_case = p->array[0] - aux->array[0]; } } p = p->forward; } printf("Total of Interrupts %d\n \ Total delay %d\n \ Worst Case %0.2fus\n \ Best Case %0.2fus\n \ Average %0.2fus\n \ Sample Rate %d\n \ Measurement Error %0.2fus\n", num_interrupts, total_delay, work_case*(1000000.0/rate), best_case*(1000000.0/rate), ((total_delay*(1000000.0/rate))/num_interrupts), rate, 1000000.0/rate); }<file_sep>#ifndef _PLATFORM_H #define _PLATFORM_H #include <pic32mz.h> #define UARTSTAT U2STA #define UARTTXREG U2TXREG #define UART_IRQ_RX IRQ_U2RX #define UART_IRQ_TX IRQ_U2TX #endif <file_sep>/* Copyright (c) 2016, prpl Foundation Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. This code was written by <NAME> at Embedded System Group (GSE) at PUCRS/Brazil. */ /** * @file pic32mz-timer-test.c * * @section DESCRIPTION * * Interrupt subsystem stress test. * * Uses the PIC32mz's timers 2 and 3 as a single 32 bits timer count to generate timer interrupts. * * The propose of this driver is generate stress tests of the interrupt subsystem. * */ #include <hypercall.h> #include <globals.h> #include <driver.h> #include <hypercall_defines.h> #include <mips_cp0.h> #include <hal.h> #include <scheduler.h> #include <libc.h> #include <uart.h> #include <interrupts.h> /* Time interval in microseconds. */ #define QUANTUM_US 10 /* Timer tick count */ uint32_t tick_count = 0; void timer_interrupt_hander(){ if (IFS(0) & 0x00004000){ IFSCLR(0) = 0x00004000; } tick_count++; if(tick_count%50000==0){ putchar('!'); } } /** * @brief Driver init call. * Register the interrupt handler and enable the timer. */ void timer_test_init(){ uint32_t offset; uint32_t interval = QUANTUM_US * 1000; offset = register_interrupt(timer_interrupt_hander); OFF(14) = offset; /* Using PIC32's timers 2/3 for 32bit counter */ T2CON = 0; TMR2 = 0x0; TMR3 = 0; PR2 = (interval & 0xFFFF); PR3 = (interval >> 16); IPCSET(2) = 0x00001f00; IFSCLR(0) = 0x00000200; IECSET(0) = 0x00000200; IPCSET(3) = 0x001f0000; IFSCLR(0) = 0x00004000; IECSET(0) = 0x00004000; T2CON |= 0x8008; INFO("PIC32mz driver for 32 bits timer test enabled with %dus interval .", QUANTUM_US); } driver_init(timer_test_init); <file_sep>/* Copyright (c) 2016, prpl Foundation Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. This code was written by <NAME> at Embedded System Group (GSE) at PUCRS/Brazil. */ #include <tlb.h> #include <types.h> #include <hypercall_defines.h> #include <vcpu.h> #include <globals.h> #include <proc.h> #include <hal.h> #define PAGESIZE 4096 #define VIRTUALBASE 0x80000000 extern uint64_t __pages_start; static const uint8_t *page_Buffer = (uint8_t *)&__pages_start; uint32_t next_page = 0; static uint32_64_t* get_next_page(){ uint32_64_t *page_addr = page_Buffer + next_page * PAGESIZE; memset(page_addr, 0, PAGESIZE); next_page++; return page_addr; } /** Get a random tlb index */ uint32_t tblGetRandomIndex(){ return 0; } void dumpPageTables(){ uint32_t i, j; for (i=0; i<next_page; i++){ printf("Table %d at 0x%x\n", i, (page_Buffer + (i*PAGESIZE))); for (j=0; j<512; j++){ uint32_64_t v = ((uint32_64_t*)(page_Buffer + (i*PAGESIZE)))[j]; if (v != 0){ printf("%d, %x\n", j, v); } } } } /** Write an entry to the tbl. @param index tlb index. The current entry on index will be lost. @param entry the entry to be written. */ void tlbEntryWrite(vm_t* vm, struct tlbentry *entry){ uint32_64_t *page_table, *inner_page_table; uint32_64_t addr, i, first_va, last_va, first_va_jump, last_va_jump; /* Get level 1 and 2 page tables. */ page_table = get_next_page(); inner_page_table = get_next_page(); /* Keep the root page table address for context switches*/ vm->root_page_table = page_table; addr = (vm->base_addr>>12); first_va = VIRTUALBASE; last_va = (uint32_64_t)(((entry->entrylo1 - entry->entrylo0)*2)<<12) + VIRTUALBASE - 1; #if defined(RISCV64) first_va_jump = first_va>>30; last_va_jump = last_va>>30; #else first_va_jump = first_va>>22; last_va_jump = last_va>>22; #endif for(i=first_va_jump;i<=(last_va_jump);i++){ page_table[i] |= 1; page_table[i] |= (((uint32_64_t)inner_page_table + (uint32_64_t)(i-first_va_jump)) >> 12) << 10; } /* Get level 3 page table */ page_table = inner_page_table; #if defined(RISCV64) inner_page_table = get_next_page(); first_va_jump = (first_va&0x3FE00000)>>21; last_va_jump = (last_va&0x3FE00000)>21; #else first_va_jump = (first_va&0x3FF000)>>12; last_va_jump = (last_va&0x3FF000)>12; #endif #if defined(RISCV64) for(i=first_va_jump;i<=(last_va_jump);i++){ page_table[i] |= 1; page_table[i] |= (((uint32_64_t)inner_page_table + (uint32_64_t)(i-first_va_jump)) >> 12) << 10; } page_table = inner_page_table; first_va_jump = (first_va&0x1FF000)>>12; last_va_jump = (last_va&0x1FF000)>>12; for(i=first_va_jump;i<=(last_va_jump);i++){ page_table[i] |= 0xf; page_table[i] |= (addr + (uint32_64_t)(i-first_va_jump))<< 10; } #else for(i=first_va_jump;i<=(last_va_jump);i++){ page_table[i] |= 0xf; page_table[i] |= (addr + (uint32_64_t)(i-first_va_jump))<< 10; } #endif } /** Create a temporary tlb entry mapped to non cachable area. * Uses the VM base address as virtual address to map the page. * @param address hypercall address event * @param baseaddr virtual machine base address * @param size guest data size * @param use_cache Determines if the page will be mapped to KSEG1 or KSEG2 * @return Mapped address. */ uint32_t tlbCreateEntry(uint32_t address, uint32_t baseaddr, uint32_t size, uint32_t tlbindex, uint32_t use_cache){ address = address-0x80000000+baseaddr; return address; } <file_sep>/* Copyright (c) 2016, prpl Foundation Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. This code was written by <NAME> at Embedded System Group (GSE) at PUCRS/Brazil. */ /** * @file driver.c * * @section DESCRIPTION * * Driver support implementation. Implements the driver_init() call. * */ #include <types.h> #include <driver.h> /* Symbols defined in the linker script indicating the start and the end of the driver's function table. */ extern uint32_t __drivers_table_init_start; extern uint32_t __drivers_table_init_end; /** * @brief Walk in the driver's function table calling all initialization functions. */ void drivers_initialization(){ uint32_t i; for(i=(uint32_t)(&__drivers_table_init_start); i<(int)(&__drivers_table_init_end); i+=sizeof(uint32_t*)){ ((initcall_t*)*(uint32_t*)i)(); } } <file_sep>/* * Copyright (c) 2016, prpl Foundation * * Permission to use, copy, modify, and/or distribute this software for any purpose with or without * fee is hereby granted, provided that the above copyright notice and this permission notice appear * in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE * FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * * This code was written by <NAME> at Embedded System Group (GSE) at PUCRS/Brazil. * */ /** * @file gpr_context.c * * @section DESCRIPTION * * */ #include <gpr_context.h> #include <libc.h> #include <vcpu.h> #include <proc.h> /** * @brief Stack pointer defined at baikal.ld linker script. */ extern long _stack; void print_stack(){ uint64_t i, j; printf("\n=========================="); for(i=((uint64_t)(&_stack))-GPR_SIZE; i<((uint64_t)(&_stack)); i+=sizeof(uint64_t)){ printf("\n0x%x", *(uint64_t*)i); } printf("\n=========================="); } /** * @brief Copy the GPR from vcpu to the stack. * @param grp_p Pointer to the address where the gpr is saved. */ void gpr_context_restore(long* gpr_p){ uint64_t i, j; for(i=((uint64_t)(&_stack))-GPR_SIZE, j=0; i<((uint64_t)(&_stack)); i+=sizeof(uint64_t), j++){ *(uint64_t*)i = gpr_p[j]; } } /** * @brief Copy the GPR from stack to the vcpu. * @param grp_p Pointer to the address where gpr will be saved. */ void gpr_context_save(long* gpr_p){ uint64_t i, j; for(i=((uint64_t)(&_stack))-GPR_SIZE, j=0; i<((uint64_t)(&_stack)); i+=sizeof(uint64_t), j++){ gpr_p[j] = ((uint64_t)*(uint64_t*)i); } } /** * @brief Move data to the previous guest GPR on stack. * @param reg GPR number. * @param value Value to write on the stack. */ void MoveToPreviousGuestGPR(long reg, uint64_t value){ uint64_t* sp = (((uint64_t)(&_stack)) - GPR_SIZE); sp[reg] = value; } /** * @brief Copy data from the previous guest GPR on stack. * @param reg GPR number. * @return GPR data. */ uint64_t MoveFromPreviousGuestGPR(long reg){ uint64_t* sp = (((uint64_t)(&_stack)) - GPR_SIZE); return sp[reg]; } <file_sep>/* C o*pyright (c) 2016, prpl Foundation Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. This code was written by <NAME> at Embedded System Group (GSE) at PUCRS/Brazil. */ #ifndef _IO_H #define _IO_H #include <arch.h> #define ENABLE_LED1 writeio(TRISHCLR, 1) #define ENABLE_LED2 writeio(TRISHCLR, 2); #define ENABLE_LED3 writeio(TRISHCLR, 4) #define TOGGLE_LED1 writeio(LATHINV, 1) #define TOGGLE_LED2 writeio(LATHINV, 2) #define TOGGLE_LED3 writeio(LATHINV, 4) #endif <file_sep>/* Copyright (c) 2016, prpl Foundation Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. This code was written by <NAME> at Embedded System Group (GSE) at PUCRS/Brazil. */ /** * @file t1-baikal-UART-test.c * * @section DESCRIPTION * * Simple test to the interrupt subsystem using UART interrupts. * * */ #include <hypercall.h> #include <globals.h> #include <driver.h> #include <hypercall_defines.h> #include <mips_cp0.h> #include <hal.h> #include <scheduler.h> #include <libc.h> #include <uart.h> #include <interrupts.h> void interrupt_handler(){ char a; while( (UART0_LSR & 0x1) ){ a = UART0_RBR; UART0_RBR = a; } } /** * @brief Driver init call. * Register the interrupt handler and enable UART interrupts. */ void uart_init(){ uint32_t temp; if( register_interrupt(interrupt_handler, 3) == 0){ INFO("UART Baikal-T1 driver registration ERROR."); return 0; } /*Clean input FIFO */ while( (UART0_LSR & 0x1) ){ UART0_RBR; } UART0_IER = 0x1; temp = mfc0(CP0_STATUS, 0); temp |= (STATUS_IM3 << STATUS_IM_SHIFT); mtc0(CP0_STATUS, 0, temp); GIC_SH_MAP_CORE(48) = 1; GIC_SH_MAP_PIN(48) = 0x80000001; GIC_SH_POL_HIGH(48); GIC_SH_SMASK(48); INFO("UART Baikal-T1 driver test."); } driver_init(uart_init); <file_sep>/* Copyright (c) 2016, prpl Foundation Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. This code was written by <NAME> at Embedded System Group (GSE) at PUCRS/Brazil. */ /** * @file eth.c * * @section DESCRIPTION * * Ethernet virtualized driver for picoTCP stack implementing the polling method. * */ #ifdef PICOTCP #include <eth.h> #include <libc.h> #include <hypercalls.h> #include <platform.h> #define ETH_FRAME_SZ 1518 /** * @brief Temporary buffer. */ uint8_t frame_buf[ETH_FRAME_SZ]; /** * @brief Ethernet link state. */ static uint32_t link_state = 0; /** * @brief PicoTCP link state checker function. * @param dev picoTCP device. * @return 0 for down or 1 for link up. */ int eth_link_state(struct pico_device *dev){ return link_state; } /** * @brief Ethernet watchdog. Must be pulled around 500ms to check the link state. * If the link is up, it enables the packet reception. * @param time Old time. * @param ms_delay Time interval. */ void eth_watchdog(uint32_t *time, uint32_t ms_delay){ if (wait_time(*time, ms_delay)){ link_state = eth_watch(); *time = mfc0(CP0_COUNT, 0); } } /** * @brief PicoTCP send packet function. * @param dev picoTCP device. * @param buf Frame buffer. * @param len frame size. * @return number of bytes sent. */ int eth_send(struct pico_device *dev, void *buf, int len){ return eth_send_frame(buf, len); } /** * @brief PicoTCP poll function. Perform polling for packet reception. * @param dev picoTCP device. * @param loop_score Polling control. * @return Updated value of loop_score. */ int eth_poll(struct pico_device *dev, int loop_score){ int32_t size; while(loop_score > 0){ size = eth_recv_frame(frame_buf); if (size<=0){ break; } pico_stack_recv(dev, frame_buf, size); loop_score--; } return loop_score; } #endif <file_sep>/* Copyright (c) 2016, prpl Foundation Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. This code was written by <NAME> at Embedded System Group (GSE) at PUCRS/Brazil. */ /** * @file pic32mz-interrupt-latency-test.c * * @section DESCRIPTION * * Test the interrupt latency on internal hypervisor drivers. * * Test procedure for PIC32mz Starter Kit: * * * Connect a signal generator to pin RD10 (pin 37 on J12 connector). * You can use another board for that. The application output_signal * works with PIC32mz Curiosity boards for this purpose. * * * Connect a logical analizer to pins RD10 and RF4 (pin 21 on J12 connector). * * * The test consists of measure the time difference between the interrupt on RD10 * and the response on pin RF4. * */ #include <hypercall.h> #include <globals.h> #include <driver.h> #include <hypercall_defines.h> #include <mips_cp0.h> #include <hal.h> #include <scheduler.h> #include <libc.h> #include <uart.h> #include <interrupts.h> void interrupt_handler(){ IFSCLR(3) = 1<<25; if(PORTD & (1<<10)){ LATFSET = 1 << 4; }else{ LATFCLR = 1 << 4; } } /** * @brief Driver init call. * Register the interrupt handler and enable the timer. */ void start_latency_init(){ uint32_t offset; TRISDSET = 1 << 10; /* RD10 (Input pin) */ CNPUDSET = 1 << 10; /* enable pull-up */ TRISFCLR = 1 << 4; /* RD0 as output*/ LATFCLR = 1 << 4; CNPUFCLR = 1 << 4; CNPDFCLR = 1 << 4; ANSELFCLR = 1 << 4; /* Configure interrupt for pin RD10 */ offset = register_interrupt(interrupt_handler); OFF(121) = offset; CNCONDSET = 0x8000; CNENDSET = 1<<10; IPC(30) = 0x1f<<8; IFSCLR(3) = 1<<25; IECSET(3) = 1<<25; INFO("PIC32mz driver for interrupt latency test."); } driver_init(start_latency_init); <file_sep>/* Copyright (c) 2016, prpl Foundation Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. This code was written by <NAME> at Embedded System Group (GSE) at PUCRS/Brazil. */ #include <arch.h> #include <types.h> #include <guest_interrupts.h> #include <malloc.h> #include <libc.h> #include <platform.h> #include <hypercalls.h> #define NUM_GUEST_INTERRUPTS 10 typedef void interrupt_handler_t(); static interrupt_handler_t * interrupt_handlers[NUM_GUEST_INTERRUPTS] = {[0 ... NUM_GUEST_INTERRUPTS-1] = NULL}; /** * @brief Interrupt registration. * Register interruts rotines. The valid interrupt numbers are * in the guest_interrupts.h file. */ uint32_t interrupt_register(interrupt_handler_t *handler, uint32_t interrupt){ uint32_t i; for(i=0; i<NUM_GUEST_INTERRUPTS; i++){ if(interrupt & (1<<i)){ if (interrupt_handlers[i] == NULL){ interrupt_handlers[i] = handler; return (uint32_t)handler; } } } return 0; } /** * @brief General exception routine. * All interrupts or exceptions invoke this routine. Call the * function handler corresponding to the RIPL field. */ void _irq_handler(uint32_t sstatus, uint32_t sepc){ if(read_csr(sip)&0x2ULL){ if (interrupt_handlers[1]){ ((interrupt_handler_t*)interrupt_handlers[1])(); } write_csr(sip,read_csr(sip)^0x2); } } /** * @brief Processor configuration. Called early during the initilization. * */ void init_proc(){ /* Enable float-point instructions */ write_csr(sstatus, read_csr(sstatus) | (1 << 13)); } /** * @brief Determines if a time period was consumed. * @param old_time Initial time. * @param ms_delay Time period. * @return 0 if the period was not consumed, 1 otherwise. */ uint32_t wait_time(uint64_t old_time, uint64_t ms_delay){ uint64_t diff_time; uint64_t now = get_mtimer_value(); if (now >= old_time) diff_time = now - old_time; else diff_time = 0xffffffffffffffff - (old_time - now); if(diff_time > (ms_delay * MILISECOND)){ return 1; } return 0; } void mdelay(uint32_t msec){ uint64_t now = get_mtimer_value(); while(!wait_time(now, msec)); } void di(){ write_csr(sie, read_csr(sie) ^ 2); } void ei(){ write_csr(sie, read_csr(sie) | 2); } void enable_interrupts(){ ei(); } <file_sep>/* Copyright (c) 2016, prpl Foundation Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. This code was written by <NAME> at Embedded System Group (GSE) at PUCRS/Brazil. */ /** * @file pic32mz-puf-functions.h * * @section DESCRIPTION * * Specific functions for PUF access to flash and PUF generation. Required by Intrinsic-ID PUF implementation. */ #ifndef __PUF_FUNCTIONS_H #define __PUF_FUNCTIONS_H #include <types.h> #include <pic32mz.h> #include <hal.h> #include <globals.h> #include <scheduler.h> #include <hypercall_defines.h> #include <hypercall.h> #include <libc.h> #include <driver.h> #include <mips_cp0.h> #include <globals.h> #include <interrupts.h> uint32_t NVMUnlock(uint32_t nvmop); uint32_t NVMErasePage(void *address); uint32_t NVMWriteQuad(void *address, void *data); uint32_t flash_read1Kbuffer(uint8_t *buffer); uint32_t flash_write1Kbuffer(uint8_t *buffer); #endif<file_sep>/* * Copyright (c) 2016, prpl Foundation * * Permission to use, copy, modify, and/or distribute this software for any purpose with or without * fee is hereby granted, provided that the above copyright notice and this permission notice appear * in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE * FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * * This code was written by <NAME> at Embedded System Group (GSE) at PUCRS/Brazil. * */ /* * Network driver for the PIC32MZ internal Ethernet controller. The following * PHY variants are supported: * SMSC LAN8720A * SMSC LAN8740A * * Based on sources of Digilent deIPcK library by <NAME>, LiteBSD by * <NAME> and the PIC32 Ethernet interface reference manual. * * * * This version of the PIC32mz Ethernet driver allows to share the * ethernet device among several VMs. Each VM will have its own MAC * address and IP address. To use/test it, you need to have the picoTCP * stack running in multiple VMs. To this, follow the steps: * * 1 - Duplicate the directory bare-metal-apps/apps/tcp-listener to tcp-listener2. * 2 - Inside the tcp-listener2 directory rename the file tcp-listener.c to tcp-listener2.c. * 3 - In the file tcp-listener2.c modify the IP address 192.168.0.2 to 192.168.0.3. * 4 - Use the shared-ethernet.cfg file to generete the firmware. * 5 - Enable the flag CONFIG_PIC32MZ_ETHERNET_SHARED_DRV in the main Makefile. * * If you desire more VMs sharing the Ethernet device repeate the steps above and * increase the NUMBER_OF_VM defined bellow. */ #include <pic32mz.h> #include <pic32mz-ethernet.h> #include <mips_cp0.h> #include <driver.h> #include <hypercall_defines.h> #include <guest_interrupts.h> #include <tlb.h> #include <libc.h> #include <hal.h> #include <scheduler.h> #include <malloc.h> #include <board.h> #include <hypercall.h> #include <interrupts.h> #include <vcpu.h> /* Number of VMs sharing the ethernet driver */ #define NUMBER_OF_VM 2 #define NUMBER_OF_FRAMES 10 #define MAC_ADDRESS_SIZE 6 /* List of buffers for temporary frame storage. Frames will * be copied here until the destination VM request it. */ struct bounded_buffer{ uint32_t used; uint32_t frame_size; uint8_t frame[MTU]; }b_buf[NUMBER_OF_FRAMES]; /* Define a control structure for buffer management for * each VM sharing the ethernet driver. */ struct vm_ctrl_buffer{ uint32_t vm_id; uint8_t mac[6]; uint32_t input; uint32_t output; struct bounded_buffer *frame_list[NUMBER_OF_FRAMES]; }VMCTRLbuf[NUMBER_OF_VM]; static uint32_t receive_index = 0; static uint32_t read_index = 0; static uint32_t desc_offset = 0; static uint32_t frame_size = 0; static uint32_t read_nbytes = 0; static uint32_t number_used_buffers = 0; /* Each VM will receive the device address MAC plus vm_counter */ static uint32_t vm_counter = 0; static vcpu_t* vcpu = NULL; void ethernet_interrupt_handler(){ fast_interrupt_delivery(vcpu); IFSCLR(IRQ_ETH >> 5) = (1<<25); ETHIRQCLR = ETHIRQ; } /* Each VM must call this hypercall just once to receive its MAC address. */ void en_get_mac(){ uint8_t * mac = (uint8_t *) tlbCreateEntry((uint32_t) MoveFromPreviousGuestGPR(REG_A0), vm_in_execution->base_addr, sizeof(uint8_t) * 6, 0xf, CACHEABLE); memcpy(mac, eth_port.macaddr, sizeof(uint8_t) * 6); mac[5] += vm_counter; /* The buffer of each VM is identified by the last mac address octet. * The frames will be copied to the buffer based on this value. */ if(vm_counter < NUMBER_OF_VM){ memcpy(VMCTRLbuf[vm_counter].mac, mac, MAC_ADDRESS_SIZE); VMCTRLbuf[vm_counter].vm_id = vcpu_in_execution->vm->id; vm_counter++; } } /* Return the VM buffer index from its VM ID.*/ int32_t get_vm_buffer_pos(uint32_t id){ uint32_t i; for(i=0; i<vm_counter; i++){ if(VMCTRLbuf[i].vm_id == id){ return i; } } return -1; } /* Choose the first free buffer fom the struct bounded_buffer*/ int32_t get_free_buffer(){ uint32_t i; for(i=0; i<NUMBER_OF_FRAMES; i++){ if(b_buf[i].used == 0){ return i; } } return -1; } /* Verify if two MAC addresses are the same */ int32_t maccmp(uint8_t* mac1, uint8_t* mac2){ uint32_t i; for(i=0; i<MAC_ADDRESS_SIZE; i++){ if(mac1[i] != mac2[i]){ return 0; } } return 1; } /* Check if an ethernet frame is broadcast */ uint32_t is_broadcast(uint8_t* f){ uint8_t mac[] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff}; if(maccmp(f, mac)){ return 1; } return 0; } /* Verify who is the VM destination searching by the MAC. */ int32_t get_vm_destination(uint8_t* f){ uint32_t i; for(i=0; i<vm_counter; i++){ if(maccmp(VMCTRLbuf[i].mac, f)){ return i; } } return -1; } void receive_frame(){ int32_t framesz = 0; uint32_t j; uint32_t freebuf; uint32_t i; /* Get the guest buffer pointer */ char* frame_ptr = (char*)MoveFromPreviousGuestGPR(REG_A0); /* Map the guest buffer */ char* frame_ptr_mapped = (char*)tlbCreateEntry((uint32_t)frame_ptr, vm_in_execution->base_addr, MTU, 0xf, CACHEABLE); j = get_vm_buffer_pos(vcpu_in_execution->vm->id); if(j<0){ /* VM not registered. Maybe forgot to call en_get_mac()?*/ MoveToPreviousGuestGPR(REG_V0, framesz); return; } /*Check if there is a frame available on buffer*/ if(VMCTRLbuf[j].input != VMCTRLbuf[j].output){ /* get frame from temporary buffer */ framesz = VMCTRLbuf[j].frame_list[VMCTRLbuf[j].output]->frame_size; memcpy(frame_ptr_mapped, VMCTRLbuf[j].frame_list[VMCTRLbuf[j].output]->frame, framesz); VMCTRLbuf[j].frame_list[VMCTRLbuf[j].output]->used--; if(VMCTRLbuf[j].frame_list[VMCTRLbuf[j].output]->used == 0) number_used_buffers--; VMCTRLbuf[j].output = (VMCTRLbuf[j].output + 1) % NUMBER_OF_FRAMES; MoveToPreviousGuestGPR(REG_V0, framesz); return; }else{ /* Read the next frame from DMA ring. */ while(1){ freebuf = get_free_buffer(); if(freebuf < 0){ /* No more free buffers, just return.*/ MoveToPreviousGuestGPR(REG_V0, 0); return; } framesz = en_ll_input(b_buf[freebuf].frame); if(framesz == 0){ /* No frames available now */ MoveToPreviousGuestGPR(REG_V0, 0); return; } /* Check if the destination MAC is the current VM or is a broadcast frame */ if( maccmp(b_buf[freebuf].frame, VMCTRLbuf[j].mac) || is_broadcast(b_buf[freebuf].frame)){ memcpy(frame_ptr_mapped, b_buf[freebuf].frame, framesz); MoveToPreviousGuestGPR(REG_V0, framesz); if(is_broadcast(b_buf[freebuf].frame)){ /* broadcast frame, must be sent for all VMs */ b_buf[freebuf].frame_size = framesz; for(i=0; i<vm_counter; i++){ if(i==j) continue; VMCTRLbuf[i].frame_list[VMCTRLbuf[i].input] = &b_buf[freebuf]; b_buf[freebuf].used++; VMCTRLbuf[i].input = (VMCTRLbuf[i].input + 1) % NUMBER_OF_FRAMES; } number_used_buffers++; } return; }else { /* This frame is not to the current VM, put it on the destinatin VM buffer */ i = get_vm_destination(b_buf[freebuf].frame); if(i<0){ /* frame destination not on this device, just discard it */ continue; } VMCTRLbuf[i].frame_list[VMCTRLbuf[i].input] = &b_buf[freebuf]; VMCTRLbuf[i].input = (VMCTRLbuf[i].input + 1) % NUMBER_OF_FRAMES; b_buf[freebuf].used++; b_buf[freebuf].frame_size = framesz; number_used_buffers++; } } } } void send_frame(){ /* Getting parameters from guest*/ uint8_t *frame = (uint8_t *)MoveFromPreviousGuestGPR(REG_A0); uint32_t size = MoveFromPreviousGuestGPR(REG_A1); char* frame_ptr_mapped = (char*)tlbCreateEntry((uint32_t)frame, vm_in_execution->base_addr, size, 0xf, CACHEABLE); uint8_t* buf = MACH_PHYS_TO_VIRT(MACH_VIRT_TO_PHYS(tx_buf)); memcpy(buf,frame_ptr_mapped,size); MoveToPreviousGuestGPR(REG_V0, size); en_ll_output(buf, size); } /* * Read PHY register. * Return -1 when failed. */ static int32_t phy_read(int32_t phy_addr, int32_t reg_num, uint32_t msec) { uint32_t time_start = mfc0(CP0_COUNT, 0); uint32_t timeout = msec * (CPU_SPEED / 2000); /* Clear any commands. */ EMAC1MCMD = 0; while (EMAC1MIND & PIC32_EMAC1MIND_MIIMBUSY) { if (mfc0(CP0_COUNT, 0) - time_start > timeout) { return -1; } } EMAC1MADR = PIC32_EMAC1MADR(phy_addr, reg_num); EMAC1MCMDSET = PIC32_EMAC1MCMD_READ; delay_ms(1); /* Wait to finish. */ time_start = mfc0(CP0_COUNT, 0); while (EMAC1MIND & PIC32_EMAC1MIND_MIIMBUSY) { if (mfc0(CP0_COUNT, 0) - time_start > timeout) { EMAC1MCMD = 0; return -1; } } EMAC1MCMD = 0; return EMAC1MRDD & 0xffff; } /* * Scan PHY register for expected value. * Return -1 when failed. */ static int32_t phy_scan(int32_t phy_addr, int32_t reg_num, int32_t scan_mask, int32_t expected_value, uint32_t msec) { uint32_t time_start = mfc0(CP0_COUNT, 0); uint32_t timeout = msec * (CPU_SPEED / 2000); /* Clear any commands. */ EMAC1MCMD = 0; while (EMAC1MIND & PIC32_EMAC1MIND_MIIMBUSY) { if (mfc0(CP0_COUNT, 0) - time_start > timeout) { return -1; } } /* Scan the PHY until it is ready. */ EMAC1MADR = PIC32_EMAC1MADR(phy_addr, reg_num); EMAC1MCMDSET = PIC32_EMAC1MCMD_SCAN; delay_ms(1); /* Wait for it to become valid. */ time_start = mfc0(CP0_COUNT, 0); while (EMAC1MIND & PIC32_EMAC1MIND_NOTVALID) { if (mfc0(CP0_COUNT, 0) - time_start > timeout) { return -1; } } /* Wait until we hit our mask. */ time_start = mfc0(CP0_COUNT, 0); while (((EMAC1MRDD & scan_mask) == scan_mask) != expected_value) { if (mfc0(CP0_COUNT, 0) - time_start > timeout) { return -1; } } /* Kill the scan. */ EMAC1MCMD = 0; delay_ms(1); time_start = mfc0(CP0_COUNT, 0); while (EMAC1MIND & PIC32_EMAC1MIND_MIIMBUSY) { if (mfc0(CP0_COUNT, 0) - time_start > timeout) { return -1; } } return 0; } /* * Write PHY register. * Return -1 when failed. */ static int32_t phy_write(int32_t phy_addr, int32_t reg_num, int32_t value, uint32_t msec) { uint32_t time_start = mfc0(CP0_COUNT, 0); uint32_t timeout = msec * (CPU_SPEED / 2000); /* Clear any commands. */ EMAC1MCMD = 0; while (EMAC1MIND & PIC32_EMAC1MIND_MIIMBUSY) { if (mfc0(CP0_COUNT, 0) - time_start > timeout) { return -1; } } EMAC1MADR = PIC32_EMAC1MADR(phy_addr, reg_num); EMAC1MWTD = value; delay_ms(1); /* Wait to finish. */ time_start = mfc0(CP0_COUNT, 0); while (EMAC1MIND & PIC32_EMAC1MIND_MIIMBUSY) { if (mfc0(CP0_COUNT, 0) - time_start > timeout) { return -1; } } return 0; } /* * Reset the PHY via MIIM interface. * Return -1 on failure. */ static int32_t phy_reset(int32_t phy_addr) { int32_t advrt; int32_t advertise_all = PHY_ADVRT_10_HDX | PHY_ADVRT_10_FDX | PHY_ADVRT_100_HDX | PHY_ADVRT_100_FDX; /* Check ADVRT register is writable. */ phy_write(phy_addr, PHY_ADVRT, 0, 100); advrt = phy_read(phy_addr, PHY_ADVRT, 1); if (advrt & advertise_all) return -1; phy_write(phy_addr, PHY_ADVRT, PHY_ADVRT_CSMA | advertise_all, 100); advrt = phy_read(phy_addr, PHY_ADVRT, 1); if ((advrt & advertise_all) != advertise_all) return -1; /* Send a reset to the PHY. */ if (phy_write(phy_addr, PHY_CONTROL, PHY_CONTROL_RESET, 100) < 0) return -1; /* Wait for the reset pin to autoclear. */ if (phy_scan(phy_addr, PHY_CONTROL, PHY_CONTROL_RESET, 0, 500) < 0) return -1; /* Advertise both 100Mbps and 10Mbps modes, full or half duplex. */ phy_write(phy_addr, PHY_ADVRT, PHY_ADVRT_CSMA | advertise_all, 100); /* Restart autonegotiation. */ phy_write(phy_addr, PHY_CONTROL, PHY_CONTROL_ANEG_EN | PHY_CONTROL_ANEG_RESTART, 100); return 0; } /* * Get the speed and duplex mode of LAN87x0A chip. */ static void phy_lan87x0a_poll(int32_t phy_addr, int32_t *speed_100, int32_t *full_duplex) { /* Read 87x0A-specific register #31. */ int32_t special = phy_read(phy_addr, 31, 1); if (special & PHY_LAN87x0A_AUTODONE) { /* Auto-negotiation is done - get the speed. */ *speed_100 = (special & PHY_LAN87x0A_100) != 0; *full_duplex = (special & PHY_LAN87x0A_FDX) != 0; } } /* * Determine whether the link is up. * When up, get the speed and duplex mode. */ static int32_t is_phy_linked(int32_t phy_addr, int32_t *speed_100, int32_t *full_duplex) { int32_t status = phy_read(phy_addr, PHY_STATUS, 1); if (status < 0) return 0; if (! (status & PHY_STATUS_LINK)) /* Is link up? */ return 0; if (! (status & PHY_STATUS_ANEG_ACK)) /* Is auto-negotiation done? */ return 0; phy_lan87x0a_poll(phy_addr, speed_100, full_duplex); return 1; } /* * Initialize the Ethernet Controller. */ static void en_setup() { int32_t empty_watermark, full_watermark; /* Disable the ethernet interrupt. */ IECCLR(IRQ_ETH >> 5) = 1 << (IRQ_ETH & 31); /* Turn the Ethernet cotroller off. */ ETHCON1CLR = PIC32_ETHCON1_ON | PIC32_ETHCON1_RXEN | PIC32_ETHCON1_TXRTS; /* Wait for abort to finish. */ while (ETHSTAT & PIC32_ETHSTAT_ETHBUSY); /* Clear the interrupt flag bit. */ IFSCLR(IRQ_ETH >> 5) = 1 << (IRQ_ETH & 31); /* Clear interrupts. */ ETHIEN = 0; ETHIRQ = 0; /* Clear discriptor pointers; for now. */ ETHTXST = 0; ETHRXST = 0; /* High and low watermarks. */ empty_watermark = MTU / RX_BYTES_PER_DESC; full_watermark = RX_DESCRIPTORS - (MTU * 2) / RX_BYTES_PER_DESC; ETHRXWM = PIC32_ETHRXWM_FWM(full_watermark) | PIC32_ETHRXWM_EWM(empty_watermark); /* Set RX descriptor buffer size in bytes (aligned to 16 bytes). */ ETHCON2 = RX_BYTES_PER_DESC; /* Set our Rx filters. */ ETHRXFC = PIC32_ETHRXFC_CRCOKEN | /* enable checksum filter */ PIC32_ETHRXFC_RUNTEN | /* enable short packets */ PIC32_ETHRXFC_UCEN | /* enable unicast filter */ PIC32_ETHRXFC_BCEN | /* enable broadcast filter */ PIC32_ETHRXFC_NOTMEEN; /* enable not me unicast filter*/ /* Hash table, not used. */ ETHHT0 = 0; ETHHT1 = 0; /* Pattern match, not used. */ ETHPMM0 = 0; ETHPMM1 = 0; /* Byte in TCP like checksum pattern calculation. */ ETHPMCS = 0; /* Turn on the ethernet controller. */ ETHCON1 = PIC32_ETHCON1_ON; } /* * Initialize the MAC. */ static void en_setup_mac() { /* Reset the MAC. */ EMAC1CFG1 = PIC32_EMAC1CFG1_SOFTRESET; delay_ms(1); /* Pull it out of reset. */ EMAC1CFG1 = 0; delay_ms(1); EMAC1CFG1 = PIC32_EMAC1CFG1_RXENABLE | /* Receive enable */ PIC32_EMAC1CFG1_TXPAUSE | /* MAC TX flow control */ PIC32_EMAC1CFG1_RXPAUSE; /* MAC RX flow control */ EMAC1CFG2 = PIC32_EMAC1CFG2_PADENABLE | /* Pad/CRC enable */ PIC32_EMAC1CFG2_CRCENABLE | /* CRC enable */ PIC32_EMAC1CFG2_EXCESSDFR | PIC32_EMAC1CFG2_AUTOPAD | PIC32_EMAC1CFG2_LENGTHCK; EMAC1MAXF = 1518; /* max frame size in bytes */ EMAC1IPGR = PIC32_EMAC1IPGR(12, 18); /* non-back-to-back interpacket gap */ EMAC1CLRT = PIC32_EMAC1CLRT(55, 15); /* collision window/retry limit */ } /* * Initialize RMII and MIIM. */ static void en_setup_rmii() { EMAC1SUPP = PIC32_EMAC1SUPP_RESETRMII; /* reset RMII */ delay_ms(1); EMAC1SUPP = 0; EMAC1MCFG = PIC32_EMAC1MCFG_RESETMGMT; /* reset the management fuctions */ delay_ms(1); EMAC1MCFG = 0; /* The IEEE 802.3 spec says no faster than 2.5MHz. * 80 / 40 = 2MHz */ EMAC1MCFG = PIC32_EMAC1MCFG_CLKSEL_40; } void en_enable_interrupts() { uint32_t offset; /* Enable interrupts. */ #if 0 ETHIENSET = PIC32_ETHIRQ_TXBUSE | /* Transmit Bus Error */ PIC32_ETHIRQ_TXDONE | /* Transmit Done */ PIC32_ETHIRQ_TXABORT | /* Transmit Abort */ PIC32_ETHIRQ_RXBUSE | /* Receive Bus Error */ PIC32_ETHIRQ_RXDONE | /* Receive Done */ PIC32_ETHIRQ_RXBUFNA | /* Receive Buffer Not Available */ PIC32_ETHIRQ_RXOVFLW; /* Receive FIFO Overflow */ #endif offset = register_interrupt(ethernet_interrupt_handler); OFF(IRQ_ETH) = offset; INFO("Ethernet interrupt %d registered at 0x%x", IRQ_ETH, offset); ETHIENSET = PIC32_ETHIRQ_RXDONE; /* Set IPL , sub-priority 0 */ IPCSET(38) = 0x1f00; /* Clear interrupt */ IFSCLR(IRQ_ETH >> 5) = (1<<25); ETHIRQCLR = ETHIRQ; IECSET(IRQ_ETH >> 5) = 1 << 25; } /* * Set DMA descriptors. */ void en_setup_dma() { struct eth_port *e = &eth_port; int32_t i; /* Set Rx discriptor list. * All owned by the ethernet controller. */ memset(e->rx_desc, 0, (RX_DESCRIPTORS+1) * sizeof(eth_desc_t)); for (i=0; i<RX_DESCRIPTORS; i++) { DESC_SET_EOWN(&e->rx_desc[i]); DESC_CLEAR_NPV(&e->rx_desc[i]); e->rx_desc[i].paddr = MACH_VIRT_TO_PHYS(&e->rx_buf[0] + (i * RX_BYTES_PER_DESC)); } /* Loop the list back to the begining. * This is a circular array descriptor list. */ e->rx_desc[RX_DESCRIPTORS].hdr = MACH_VIRT_TO_PHYS(&e->rx_desc[0]); DESC_SET_NPV(&e->rx_desc[RX_DESCRIPTORS-1]); /* Set RX at the start of the list. */ receive_index = 0; ETHRXST = MACH_VIRT_TO_PHYS(&e->rx_desc[0]); /* Set up the transmit descriptors all owned by * the software; clear it completely out. */ memset(e->tx_desc, 0, (TX_DESCRIPTORS+1) * sizeof(eth_desc_t)); ETHTXST = MACH_VIRT_TO_PHYS(&e->tx_desc[0]); } /* * ethernet low level input (receive) * * a raw ethernet frame is fetched from the reception buffer (controlled by * the RX DMA) and copied to the application buffer. Warning: the application * buffer should be cache-coherent. */ int32_t en_ll_input(uint8_t *frame) { struct eth_port *e = &eth_port; uint8_t *buf = frame; uint16_t size; read_index = receive_index; desc_offset = 0; read_nbytes = 0; if (!e->is_up) return 0; if (DESC_EOWN(&e->rx_desc[receive_index])) { /* There are no receive descriptors to process. */ return 0; } frame_size = DESC_FRAMESZ(&e->rx_desc[receive_index]); size = frame_size; if (frame_size == 0) return 0; /* make sure we own the descriptor, bad if we don't! */ while (frame_size > 0) { if (DESC_EOWN(&e->rx_desc[read_index])) break; int32_t end_of_packet = DESC_EOP(&e->rx_desc[read_index]); uint32_t nbytes = DESC_BYTECNT(&e->rx_desc[read_index]); uint32_t cb = min(nbytes - desc_offset, frame_size); memcpy(buf, MACH_PHYS_TO_VIRT(e->rx_desc[read_index].paddr + desc_offset), cb); buf += cb; desc_offset += cb; read_nbytes += cb; frame_size -= cb; /* if we read the whole descriptor page */ if (desc_offset == nbytes) { /* set up for the next page */ desc_offset = 0; read_index = INCR_RX_INDEX(read_index); /* if we are done, get out */ if (end_of_packet || read_nbytes == frame_size) break; } } /* Free the receive descriptors. */ while (!DESC_EOWN(&e->rx_desc[receive_index])){ int32_t end_of_packet = DESC_EOP(&e->rx_desc[receive_index]); DESC_SET_EOWN(&e->rx_desc[receive_index]); /* give up ownership */ ETHCON1SET = PIC32_ETHCON1_BUFCDEC; /* decrement the BUFCNT */ receive_index = INCR_RX_INDEX(receive_index); /* check the next one */ /* hit the end of packet */ if (end_of_packet) break; } read_index = 0; desc_offset = 0; frame_size = 0; read_nbytes = 0; return size; } /* * ethernet low level output (send) * * a raw ethernet frame is copied from the application buffer to the transmission * buffer by the TX DMA engine. Warning: the application buffer should be * cache-coherent. */ void en_ll_output(uint8_t *frame, uint16_t size) { struct eth_port *e = &eth_port; volatile eth_desc_t *desc = &e->tx_desc[0]; if (size > 0 && size <= MTU) { while(ETHCON1 & PIC32_ETHCON1_TXRTS); desc->hdr = 0; desc->paddr = MACH_VIRT_TO_PHYS(frame); DESC_SET_BYTECNT(desc, size); DESC_SET_SOP(desc); /* Start of packet */ DESC_SET_EOWN(desc); /* Set owner */ DESC_SET_EOP(desc); /* End of packet */ /* Set the descriptor table to be transmitted. */ ETHTXST = MACH_VIRT_TO_PHYS(e->tx_desc); /* Start transmitter. */ ETHCON1SET = PIC32_ETHCON1_TXRTS; } } /* * ethernet watchdog * * this routine should be called periodically (~500ms) from the application. * the link will be stablished and monitored by this routine (link up/down). * no transmission / reception will work if the link is down. */ void en_watchdog(void) { struct eth_port *e = &eth_port; int32_t receiver_enabled = (ETHCON1 & PIC32_ETHCON1_RXEN); int32_t speed_100 = 1, full_duplex = 1; /* Poll whether the link is active. * Get speed and duplex status from the PHY. */ e->is_up = is_phy_linked(e->phy_addr, &speed_100, &full_duplex); MoveToPreviousGuestGPR(REG_V0, e->is_up); /* Check whether RX is enabled. */ if (e->is_up && ! receiver_enabled) { /* Link activated. */ INFO("en0: link up, %s, %s duplex", speed_100 ? "100Mbps" : "10Mbps", full_duplex ? "full" : "half"); /* Set speed. */ if (speed_100) { EMAC1SUPPSET = PIC32_EMAC1SUPP_SPEEDRMII; } else { EMAC1SUPPCLR = PIC32_EMAC1SUPP_SPEEDRMII; } /* Set duplex. */ if (full_duplex) { EMAC1CFG2SET = PIC32_EMAC1CFG2_FULLDPLX; } else { EMAC1CFG2CLR = PIC32_EMAC1CFG2_FULLDPLX; } /* Set gap size. */ EMAC1IPGT = full_duplex ? 21 : 18; en_setup_dma(); ETHCON1SET = PIC32_ETHCON1_RXEN; } else if (! e->is_up && receiver_enabled) { /* Link down. */ INFO("en0: link down"); ETHCON1CLR = PIC32_ETHCON1_RXEN; while (ETHSTAT & PIC32_ETHSTAT_RXBUSY); } } /* * Different devices can have different pin assignments, * depending on pin count and DEVCFG.FETHIO configuration setting. */ static void setup_signals() { switch (DEVID & 0x0fffffff) { case 0x05104053: /* MZ2048ECG064 */ case 0x05109053: /* MZ2048ECH064 */ case 0x05131053: /* MZ2048ECM064 */ case 0x07203053: /* MZ1024EFG064 */ case 0x07204053: /* MZ2048EFG064 */ case 0x07208053: /* MZ1024EFH064 */ case 0x07209053: /* MZ2048EFH064 */ case 0x07230053: /* MZ1024EFM064 */ case 0x07231053: /* MZ2048EFM064 */ if (*(uint32_t*)_DEVCFG3 & _DEVCFG3_FETHIO) { /* * Default setup for 64-pin device. */ ANSELECLR = 1 << 4; /* Disable analog pad on RE4 for ERXERR */ ANSELECLR = 1 << 6; /* Disable analog pad on RE6 for ETXD0 */ ANSELECLR = 1 << 7; /* Disable analog pad on RE7 for ETXD1 */ ANSELECLR = 1 << 5; /* Disable analog pad on RE5 for ETXEN */ ANSELBCLR = 1 << 15; /* Disable analog pad on RB15 for EMDC */ LATECLR = 1 << 6; TRISECLR = 1 << 6; /* set RE6 as output for ETXD0 */ LATECLR = 1 << 7; TRISECLR = 1 << 7; /* set RE7 as output for ETXD1 */ LATECLR = 1 << 5; TRISECLR = 1 << 5; /* set RE5 as output for ETXEN */ } else { /* * Alternative setup for 64-pin device. */ ANSELBCLR = 1 << 15; /* Disable analog pad on RB15 for AEMDC */ LATFCLR = 1 << 1; TRISFCLR = 1 << 1; /* set RF1 as output for AETXD0 */ LATFCLR = 1 << 0; TRISFCLR = 1 << 0; /* set RF0 as output for AETXD1 */ LATDCLR = 1 << 2; TRISDCLR = 1 << 2; /* set RD2 as output for AETXEN */ } break; case 0x0510E053: /* MZ2048ECG100 */ case 0x05113053: /* MZ2048ECH100 */ case 0x0513B053: /* MZ2048ECM100 */ case 0x0720D053: /* MZ1024EFG100 */ case 0x0720E053: /* MZ2048EFG100 */ case 0x07212053: /* MZ1024EFH100 */ case 0x07213053: /* MZ2048EFH100 */ case 0x0723A053: /* MZ1024EFM100 */ case 0x0723B053: /* MZ2048EFM100 */ if (*(uint32_t*)_DEVCFG3 & _DEVCFG3_FETHIO) { /* * Default setup for 100-pin devices. */ ANSELGCLR = 1 << 9; /* Disable analog pad on RG9 for EREFCLK */ ANSELBCLR = 1 << 12; /* Disable analog pad on RB12 for ERXD0 */ ANSELBCLR = 1 << 13; /* Disable analog pad on RB13 for ERXD1 */ ANSELGCLR = 1 << 8; /* Disable analog pad on RG8 for ECRSDV */ ANSELBCLR = 1 << 11; /* Disable analog pad on RB11 for ERXERR */ LATFCLR = 1 << 1; TRISFCLR = 1 << 1; /* set RF1 as output for ETXD0 */ LATFCLR = 1 << 0; TRISFCLR = 1 << 0; /* set RF0 as output for ETXD1 */ LATDCLR = 1 << 2; TRISDCLR = 1 << 2; /* set RD2 as output for ETXEN */ } else { /* * Alternative setup for 100-pin devices. */ ANSELGCLR = 1 << 9; /* Disable analog pad on RG9 for AEREFCLK */ ANSELECLR = 1 << 8; /* Disable analog pad on RE8 for AERXD0 */ ANSELECLR = 1 << 9; /* Disable analog pad on RE9 for AERXD1 */ ANSELGCLR = 1 << 8; /* Disable analog pad on RG8 for AECRSDV */ ANSELGCLR = 1 << 15; /* Disable analog pad on RG15 for AERXERR */ ANSELDCLR = 1 << 14; /* Disable analog pad on RD14 for AETXD0 */ ANSELDCLR = 1 << 15; /* Disable analog pad on RD15 for AETXD1 */ LATDCLR = 1 << 14; TRISDCLR = 1 << 14; /* set RD14 as output for AETXD0 */ LATDCLR = 1 << 15; TRISDCLR = 1 << 15; /* set RD15 as output for AETXD1 */ LATACLR = 1 << 15; TRISACLR = 1 << 15; /* set RA15 as output for AETXEN */ } break; case 0x05118053: /* MZ2048ECG124 */ case 0x0511D053: /* MZ2048ECH124 */ case 0x05145053: /* MZ2048ECM124 */ case 0x07217053: /* MZ1024EFG124 */ case 0x07218053: /* MZ2048EFG124 */ case 0x0721C053: /* MZ1024EFH124 */ case 0x0721D053: /* MZ2048EFH124 */ case 0x07244053: /* MZ1024EFM124 */ case 0x07245053: /* MZ2048EFM124 */ WARNING("124-pin devices not supported yet"); break; case 0x05122053: /* MZ2048ECG144 */ case 0x05127053: /* MZ2048ECH144 */ case 0x0514F053: /* MZ2048ECM144 */ case 0x07221053: /* MZ1024EFG144 */ case 0x07222053: /* MZ2048EFG144 */ case 0x07226053: /* MZ1024EFH144 */ case 0x07227053: /* MZ2048EFH144 */ case 0x0724E053: /* MZ1024EFM144 */ case 0x0724F053: /* MZ2048EFM144 */ /* * Setup for 144-pin devices. */ ANSELJCLR = 1 << 11; /* Disable analog pad on RJ11 for EREFCLK */ ANSELHCLR = 1 << 5; /* Disable analog pad on RH5 for ERXD1 */ ANSELHCLR = 1 << 4; /* Disable analog pad on RH4 for ERXERR */ ANSELJCLR = 1 << 8; /* Disable analog pad on RJ8 for ETXD0 */ ANSELJCLR = 1 << 9; /* Disable analog pad on RJ9 for ETXD1 */ LATJCLR = 1 << 8; TRISJCLR = 1 << 8; /* set RJ8 as output for ETXD0 */ LATJCLR = 1 << 9; TRISJCLR = 1 << 9; /* set RJ9 as output for ETXD1 */ LATDCLR = 1 << 6; TRISDCLR = 1 << 6; /* set RD6 as output for ETXEN */ break; default: WARNING("DEVID not recognized\n"); } } static void en_init(){ struct eth_port *e = &eth_port; memset(b_buf, 0, sizeof(b_buf)); memset(VMCTRLbuf, 0, sizeof(VMCTRLbuf)); /* Board-dependent initialization. */ setup_signals(); /* Link is down. */ e->is_up = 0; /* As per section 35.4.10 of the Pic32 Family Ref Manual. */ en_setup(); en_setup_mac(); en_setup_rmii(); /* Auto-detect the PHY address, 0-31. */ for (e->phy_addr=0; e->phy_addr<32; e->phy_addr++) { if (phy_reset(e->phy_addr) >= 0) break; } if (e->phy_addr >= 32) { ETHCON1 = 0; WARNING("Ethernet PHY not detected\n"); return; }else{ INFO("Ethernet PHY at %d", e->phy_addr); } /* Extract our MAC address */ e->macaddr[0] = EMAC1SA2; e->macaddr[1] = EMAC1SA2 >> 8; e->macaddr[2] = EMAC1SA1; e->macaddr[3] = EMAC1SA1 >> 8; e->macaddr[4] = EMAC1SA0; e->macaddr[5] = EMAC1SA0 >> 8; /* * Interface exists: make available by filling in network interface * record. System will initialize the interface when it is ready * to accept packets. We get the ethernet address here. */ INFO("Ethernet interface en0: interrupt %d, MAC address %x:%x:%x:%x:%x:%x", IRQ_ETH, e->macaddr[0], e->macaddr[1], e->macaddr[2], e->macaddr[3], e->macaddr[4], e->macaddr[5]); e->phy_id = (phy_read(e->phy_addr, PHY_ID1, 1) << 16 | phy_read(e->phy_addr, PHY_ID2, 1)) & 0xfffffff0; switch (e->phy_id) { case PHY_ID_LAN8720A: INFO("Ethernet device is a SMSC LAN8720A"); break; case PHY_ID_LAN8740A: INFO("Ethernet device is a SMSC LAN8740A"); break; default: INFO("PHY id=%x", e->phy_id); break; } /* allocate buffers and change pointers from kseg0 to kseg1 (non-cachable) * this will make DMA buffers coherent because we avoid acessing the L1 cache. */ e->rx_buf = MACH_PHYS_TO_VIRT(MACH_VIRT_TO_PHYS((int8_t *)malloc(RX_BYTES * sizeof(int8_t)))); e->rx_desc = MACH_PHYS_TO_VIRT(MACH_VIRT_TO_PHYS((eth_desc_t *)malloc((RX_DESCRIPTORS+1) * sizeof(eth_desc_t)))); e->tx_desc = MACH_PHYS_TO_VIRT(MACH_VIRT_TO_PHYS((eth_desc_t *)malloc((TX_DESCRIPTORS+1) * sizeof(eth_desc_t)))); if (!e->rx_buf || !e->rx_desc || !e->tx_desc){ CRITICAL("\nEthernet Driver: Out of Memory - Hypervisor Halted."); } if (register_hypercall(en_watchdog, HCALL_ETHERNET_WATCHDOG) < 0){ ERROR("Error registering the HCALL_GET_VM_ID hypercall"); return; } if (register_hypercall(en_get_mac, HCALL_ETHERNET_GET_MAC) < 0){ ERROR("Error registering the HCALL_GET_VM_ID hypercall"); return; } if (register_hypercall(send_frame, HCALL_ETHERNET_SEND) < 0){ ERROR("Error registering the HCALL_GET_VM_ID hypercall"); return; } if (register_hypercall(receive_frame, HCALL_ETHERNET_RECV) < 0){ ERROR("Error registering the HCALL_GET_VM_ID hypercall"); return; } /* check if there is a VCPU associated to ethernet interrutps. */ vcpu = get_fast_int_vcpu_node(IRQ_ETH); if (vcpu){ en_enable_interrupts(); } return; } driver_init(en_init); <file_sep>/* Copyright (c) 2016, prpl Foundation Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. This code was written by <NAME> at Embedded System Group (GSE) at PUCRS/Brazil. */ /* Simple UART Bare-metal application sample */ #include <arch.h> #include <libc.h> volatile int32_t t2 = 0; void irq_timer(){ t2++; } uint8_t buffer[32]; void printf_buffer(uint8_t *buffer, uint32_t size){ uint32_t i; for(i=0;i<size;i++){ putchar(buffer[i]); } } int main() { uint32_t ret, source; uint32_t a; uint32_t guestid = hyp_get_guest_id(); /* Select output serial 2 = UART2, 6 = UART6 */ serial_select(UART6); printf("\n\routputUART Guest ID %d. Waiting message."); while (1){ ret = ReceiveMessage(&source, buffer, sizeof(buffer), 0); if (ret>0){ printf("\n\routputUART Guest ID %d - size %d ", guestid, ret); printf_buffer(buffer, ret); } } return 0; } <file_sep>/* Copyright (c) 2016, prpl Foundation Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. This code was written by <NAME> at Embedded System Group (GSE) at PUCRS/Brazil. */ #ifndef NETWORK_H #define NETWORK_H #include <arch.h> #include <libc.h> #define MESSAGELIST_SZ 5 #define MESSAGE_SZ 255 /** Return values for inter-vm communication hypercalls */ #define MESSAGE_VCPU_NOT_FOUND -1 #define MESSAGE_FULL -2 #define MESSAGE_TOO_BIG -3 #define MESSAGE_EMPTY -4 #define MESSAGE_VCPU_NOT_INIT -5 /** Struct for message exchange It is a circular buffer. Message_list is a char matrix statically allocated. */ struct message_t{ uint32_t source_id; uint32_t size; /* size of each message in message_list */ uint8_t message[MESSAGE_SZ]; }; struct message_list_t{ uint32_t in; uint32_t out; volatile uint32_t num_messages; struct message_t messages[MESSAGELIST_SZ]; }; void init_network(); int32_t ReceiveMessage(uint32_t *source, void* message, uint32_t bufsz, uint32_t block); int32_t SendMessage(uint32_t target_id, void* message, uint32_t size); void network_int_handler(); void print_net_error(int32_t error); #endif <file_sep>#Copyright (c) 2016, prpl Foundation # #Permission to use, copy, modify, and/or distribute this software for any purpose with or without #fee is hereby granted, provided that the above copyright notice and this permission notice appear #in all copies. # #THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE #INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE #FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM #LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, #ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # #This code was written by <NAME> at Embedded System Group (GSE) at PUCRS/Brazil. PREFIX?=$(PWD)/../../../../wolfssl/build PICOTCP=$(PWD)/../../../../picotcp/build/include CC=gcc CROSS_COMPILE?=mips-mti-elf- CFLAGS+=-I. -Iwolfssl -I$(PICOTCP) #prpl flags CFLAGS+= -EL -O2 -mtune=m14k -mips32r2 CFLAGS+= -Wa,-mvirt CFLAGS+= -mno-check-zero-division -msoft-float -fshort-double CFLAGS+= -c -ffreestanding -nostdlib -fomit-frame-pointer -G 0 CXX_FILES = \ src/ssl.c \ src/tls.c \ src/internal.c \ src/keys.c \ src/io.c \ wolfcrypt/src/camellia.c \ wolfcrypt/src/dh.c \ wolfcrypt/src/ripemd.c \ wolfcrypt/src/aes.c \ wolfcrypt/src/md4.c \ wolfcrypt/src/coding.c \ wolfcrypt/src/curve25519.c \ wolfcrypt/src/ecc_fp.c \ wolfcrypt/src/dsa.c \ wolfcrypt/src/sha256.c \ wolfcrypt/src/rsa.c \ wolfcrypt/src/srp.c \ wolfcrypt/src/hash.c \ wolfcrypt/src/asm.c \ wolfcrypt/src/blake2b.c \ wolfcrypt/src/logging.c \ wolfcrypt/src/ed25519.c \ wolfcrypt/src/wolfmath.c \ wolfcrypt/src/ecc.c \ wolfcrypt/src/pkcs7.c \ wolfcrypt/src/arc4.c \ wolfcrypt/src/compress.c \ wolfcrypt/src/md5.c \ wolfcrypt/src/misc.c \ wolfcrypt/src/rabbit.c \ wolfcrypt/src/wc_encrypt.c \ wolfcrypt/src/idea.c \ wolfcrypt/src/cmac.c \ wolfcrypt/src/integer.c \ wolfcrypt/src/chacha20_poly1305.c \ wolfcrypt/src/poly1305.c \ wolfcrypt/src/pkcs12.c \ wolfcrypt/src/des3.c \ wolfcrypt/src/error.c \ wolfcrypt/src/md2.c \ wolfcrypt/src/fe_low_mem.c \ wolfcrypt/src/fe_operations.c \ wolfcrypt/src/ge_low_mem.c \ wolfcrypt/src/async.c \ wolfcrypt/src/pwdbased.c \ wolfcrypt/src/hmac.c \ wolfcrypt/src/sha512.c \ wolfcrypt/src/signature.c \ wolfcrypt/src/wolfevent.c \ wolfcrypt/src/asn.c \ wolfcrypt/src/hc128.c \ wolfcrypt/src/ge_operations.c \ wolfcrypt/src/tfm.c \ wolfcrypt/src/wc_port.c \ wolfcrypt/src/sha.c \ wolfcrypt/src/memory.c \ wolfcrypt/src/random.c \ wolfcrypt/src/chacha.c # Translate to .o object files OBJS:= $(patsubst %.c,%.o,$(CXX_FILES)) #OBJS:= $(patsubst wolfcrypt/src/%.c,$(PREFIX)/ssl/wolfcrypt/%.o,$(OBJ_FILES)) all: $(PREFIX)/libwolfssl.a %.o: %.c $(CROSS_COMPILE)$(CC) -c $(CFLAGS) -o $@ $< $(PREFIX)/libwolfssl.a: $(OBJS) @mkdir -p $(PREFIX) #@cp wolfssl/*.h $(PREFIX)/include/wolfssl #@cp wolfssl/wolfcrypt/*.h $(PREFIX)/include/wolfssl/wolfcrypt #@cp -r wolfssl/openssl/ $(PREFIX)/include/ @$(CROSS_COMPILE)ar cru $@ $(OBJS) @$(CROSS_COMPILE)ranlib $@ clean: rm -f $(OBJS) <file_sep>/* Copyright (c) 2016, prpl Foundation Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. This code was written by <NAME> at Embedded System Group (GSE) at PUCRS/Brazil. */ /** * @file pic32mz-puf-flash.c * * @section DESCRIPTION * * This is a Driver that search denied hypercalls in each VM. When a denied hypercall is founded, the driver blocks the VM. */ #include <hypercall.h> #include <globals.h> #include <driver.h> #include <hypercall_defines.h> #include <libc.h> #include <vm.h> #include <malloc.h> #include <config.h> #include <tlb.h> #include <scheduler.h> #include <vcpu.h> #include <queue.h> #define HYP_ORIGIN 0x80000000 #define VM_ORIGIN 0x9d000000 #define FUNCT_BITS 0x3F #define OPCODE_BITS 0xFC000000 #define HYPCALL_CODE 0x28 #define R_TYPE_OPCODE 0x10 #define CODE_BITS 0x1FF800 /** * @brief Block the VM with denied hypercalls. */ void invalid_hypercall(int32_t vm){ vcpu_t * vcpu = NULL; vcpu = queue_get(scheduler_info.vcpu_ready_list,vm); vcpu->state = VCPU_BLOCKED; INFO("Virtual Machine %s is blocked, denied hypercall founded.",vcpu->vm->vm_name); } /** * @brief Initialize driver scanning the VM's memory. */ void denied_hypercalls_init(){ int32_t i,j,k,blocked; int32_t* adress; int32_t mem_size,hcall_funct,code,opcode,adraux; vcpu_t * vcpu = NULL; for(i=0;i<NVMACHINES;i++){ blocked = 0; adress = 0; vcpu = queue_get(scheduler_info.vcpu_ready_list,i); for(j=1;j<VMCONF[i].num_tlb_entries;j++){ if(adress < VMCONF[i].tlb[j].entrylo0){ adraux = VMCONF[i].tlb[j].entrylo0; } } adress = ((adraux<<12)+HYP_ORIGIN); mem_size = *adress - VM_ORIGIN; for(j=0;j<mem_size;j=j+4){ hcall_funct=(*adress)&FUNCT_BITS; opcode=((*adress)&OPCODE_BITS)>>26; if(hcall_funct==HYPCALL_CODE&&opcode==R_TYPE_OPCODE){ code=((*adress)&CODE_BITS)>>11; for(k=0;k<VMCONF[i].denied_hypercalls_sz;k++){ if((code==VMCONF[i].denied_hypercalls[k])&&(blocked==0)){ invalid_hypercall(i); blocked++; } } } adress++; } if(blocked==0) INFO("Virtual Machine %s is clean of denied hypercalls.",vcpu->vm->vm_name); } } driver_init(denied_hypercalls_init); <file_sep>/* Copyright (c) 2016, prpl Foundation Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. This code was written by <NAME> at Embedded System Group (GSE) at PUCRS/Brazil. */ /** * @file pic32mz-puf-sram.c * * @section DESCRIPTION * * Specific driver to generate a SRAM PUF. */ #include <types.h> #include <pic32mz.h> #include <hal.h> #include <globals.h> #include <scheduler.h> #include <hypercall_defines.h> #include <hypercall.h> #include <libc.h> #include <driver.h> #include <mips_cp0.h> #include <globals.h> #include <interrupts.h> #include <pic32mz-puf-functions.h> #define XRORED_VALUE1 0xFFFFFFFF #define XRORED_VALUE0 0x00000000 extern int32_t* _puf; /** * @brief Generate Correction Bits for ECC Repetition Code. */ static int32_t sram_puf_not_initialized(uint8_t *buffer){ int32_t i,sram,correction_data,nominal_value; int32_t *sram_address; int32_t id = 0; sram_address = (int32_t *)(&_puf); for(i=0;i<32;i++){ sram = *(sram_address); nominal_value = sram&0x1; sram = sram>>1; if(nominal_value==0) correction_data = sram^XRORED_VALUE0; else correction_data = sram^XRORED_VALUE1; ((uint32_t *)buffer)[i] = correction_data; if(nominal_value==1) id = id|(1<<i); sram_address++; } flash_write1Kbuffer(buffer); return id; } /** * @brief Generate PUF when ECC Repetition Code was initialized. */ static int32_t sram_puf_initialized(uint8_t *buffer){ int32_t i,sram,correction_data,bits31; int32_t bit_id = 0; int32_t id = 0; int32_t *sram_address; sram_address = (int32_t *)(&_puf); for(i=0;i<32;i++){ sram = *(sram_address)>>1; correction_data = ((uint32_t *)buffer)[i]; bits31 = sram^correction_data; while (bits31) { bits31 &= (bits31-1) ; bit_id++; } if(bit_id>15) bit_id=1; else bit_id=0; if(bit_id==1) id = id|(1<<i); sram_address++; } return id; } static void puf_id(){ uint8_t *buffer; int32_t i; int32_t flash_status = 0; int32_t id = 0; buffer = malloc(sizeof(uint8_t)*1024); if(flash_read1Kbuffer(buffer)!=1024) ERROR("Error reading PUF Flash."); for(i=0;i<256;i++){ if(((uint32_t *)buffer)[i]!=XRORED_VALUE1) flash_status = 1; } if(flash_status==0){ id = sram_puf_not_initialized(buffer); }else{ id = sram_puf_initialized(buffer); } MoveToPreviousGuestGPR(REG_V0, id); } /** * @brief Initialize driver registering the hypercall. */ static void sram_puf_init(){ puf_id(); if (register_hypercall(puf_id, HCALL_GET_PUF_ID) < 0){ ERROR("Error registering the HCALL_GET_PUF_ID hypercall."); return; } INFO("PUF ID enabled."); } driver_init(sram_puf_init);<file_sep>/* Copyright (c) 2016, prpl Foundation Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. This code was written by <NAME> at Embedded System Group (GSE) at PUCRS/Brazil. */ /* Simple SPI write application sample */ #include <arch.h> #include <libc.h> volatile int32_t t2 = 0; void irq_timer(){ t2++; } uint8_t tx_buffer[] = "abcdefghijklmnopqstuvxz"; /* SP1 configuration */ void setupSPI1(){ uint32_t rData; SPI1CON = 0; rData=SPI1BUF; SPI1BRG = 4; SPI1STATCLR=0x40; SPI1CON = 0x8120; /* enable SPI / master mode / data transition from high to low clk */ } void SPI_write_byte(uint8_t c){ while(SPI1STAT & SPISTAT_SPITBF); SPI1BUF=c; } void SPI_write_buffer(uint8_t *buffer, uint32_t size){ uint32_t i; LATBCLR= 8; /* enable CS */ for(i=0;i<sizeof(tx_buffer);i++){ SPI_write_byte(tx_buffer[i]); } /* Make sure that SPI is not busy before disable CS */ while(SPI1STAT & SPISTAT_SPIBUSY); LATBSET= 8; /* disable CS */ } int main() { uint32_t i; /* Select output serial 2 = UART2, 6 = UART6 */ serial_select(UART2); printf("\nConfiguring SPI."); setupSPI1(); while (1){ SPI_write_buffer(tx_buffer, sizeof(tx_buffer)); } return 0; } <file_sep>/* Copyright (c) 2016, prpl Foundation Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. This code was written by <NAME> at Embedded System Group (GSE) at PUCRS/Brazil. */ /** * This is the dhrystone benchmark. * * The benchmark sources will be automatically cloned from : * - https://github.com/crmoratelli/prplHypervisor-benckmarks.git * * A benchmark folder will be created in the same level of the hypervisor's folder. You should see: * ~/ * prpl-hypervisor/ * benchmark/ * * For generante a system configuration with different number of VMs: * - Go to the prpl-hypervisor/bare-metal-apps/apps folder and copy the original dhyrstone app. Example: * cp -R dhrystone/ dhrystone2 * cp -R dhrystone/ dhrystone3 * cp -R dhrystone/ dhrystone4 * * See the dhrystone.cfg file for more details. * */ #include <arch.h> #include <libc.h> #include <hypercalls.h> #include <guest_interrupts.h> #include <platform.h> #include <io.h> #define RUNS 5000000 #define CPU_TICK_TO_MS(ticks) ((ticks)/((CPU_SPEED/2)/1000)) volatile uint64_t tick_passed = 0; void irq_timer(){ static uint32_t tick_old = 0; uint32_t tick_now = mfc0 (CP0_COUNT, 0); uint32_t diff_time; if (tick_old == 0){ tick_old = tick_now; return; } if (tick_now >= tick_old){ diff_time = tick_now - tick_old; }else{ diff_time = 0xffffffff - (tick_old - tick_now); } tick_old = tick_now; tick_passed += diff_time; } long time(long *tm){ uint32_t seconds = CPU_TICK_TO_MS(tick_passed)/1000; if (tm){ *tm=seconds; } return seconds; } int main() { perf_control_t perf0, perf1; uint32_t perfcount[2]; interrupt_register(irq_timer, GUEST_TIMER_INT); /* peformance counter 0 - D-Cache Misses */ perf0.w = 0; //perf0.m = 1; perf0.ec = 2; perf0.event = 11; perf0.ie = 0; perf0.u = 0; perf0.k = 1; perf0.exl = 0; /* peformance counter 1 - I-Cache Misses */ perf1.w = 0; //perf1.m = 1; perf1.ec = 2; perf1.event = 9; perf1.ie = 0; perf1.u = 0; perf1.k = 1; perf1.exl = 0; performance_counter_start(perf0.w, perf1.w); main_dhry(RUNS); performance_counter_stop(perfcount); printf("\nD-Cache Misses: %d", perfcount[0]); printf("\nI-Cache Misses: %d", perfcount[1]); return 0; } <file_sep>/* Copyright (c) 2016, prpl Foundation Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. This code was written by <NAME> at Embedded System Group (GSE) at PUCRS/Brazil. */ /* Simple read flash sample. */ #include <arch.h> #include <libc.h> #include <hypercalls.h> #include <guest_interrupts.h> #include <platform.h> #include <io.h> uint32_t buffer[256]; int main() { uint32_t i; ENABLE_LED1; /* Turn on lead 1 */ TOGGLE_LED1; memset(buffer, 0, sizeof(buffer)); int32_t ret = read_1k_data_flash(buffer); for(i=0;i<sizeof(buffer)/4; i++){ printf("0x%x\t0x%08x\n", i*4, ((uint32_t*)buffer)[i]); } while(1){} return 0; } <file_sep>#include <config.h> #include <types.h> #include <pic32mz.h> #include <uart.h> /** * @file uart.c * * @section DESCRIPTION * * UART initialization and low level UART functions. * */ /** * @brief Configures UART2 as stdout alternative. * @param baudrate_u2 UART2 baudrate. * @param baudrate_u6 UART6 baudrate. * @param sysclk System clock. */ void init_uart(uint32_t baudrate_u2, uint32_t baudrate_u6, uint32_t sysclk){ U1RXR = 0b0011; /* // RPD10 -> U1RX */ RPD15R = 0b0001; /* RPD15 -> U1TX */ U1STA = 0; U1BRG = ((int)( ((sysclk/2) / (16*baudrate_u2)) -1)) + 1; U1MODE = UMODE_PDSEL_8NPAR | /* 8-bit data, no parity */ UMODE_ON; /* UART Enable */ U1STASET = USTA_URXEN | USTA_UTXEN; /* RX / TX Enable */ baudrate_u6 = 0; /* Only UART1 used for now. */ } /** * @brief Write char to UART2. * @param c Character to be writed. */ void putchar(uint8_t c){ while(U1STA&USTA_UTXBF); U1TXREG = c; } /** * @brief Block and wait for a character. * @return Read character. */ uint32_t getchar(void){ while(!(U1STA & USTA_URXDA)); return (uint32_t)U1RXREG; } <file_sep>#ifndef _UART_H #define _UART_H #include <types.h> void init_uart(uint32_t baudrate_u2, uint32_t baudrate_u6, uint32_t sysclk); void putchar(uint8_t c); uint32_t getchar(void); #endif <file_sep>/* Copyright (c) 2016, prpl Foundation Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. This code was written by <NAME> at Embedded System Group (GSE) at PUCRS/Brazil. */ /* * Copyright (c) 2016, prpl Foundation * * Permission to use, copy, modify, and/or distribute this software for any purpose with or without * fee is hereby granted, provided that the above copyright notice and this permission notice appear * in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE * FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * * This code was written by <NAME> at Embedded System Group (GSE) at PUCRS/Brazil. * */ /** * @file uart_driver.c * * @section DESCRIPTION * * Interrupt-driven virtualized console driver that queues the guest's UART read/write calls. * * The guest's call the HCALL_UART_SEND/HCALL_UART_RECV * hypercalls being blocked to wait by UART tranfers to complete * when necessary. * */ #include <globals.h> #include <hal.h> #include <baikal-t1.h> #include <mips_cp0.h> #include <libc.h> #include <hypercall_defines.h> #include <hypercall.h> #include <driver.h> #include <interrupts.h> #include <platform.h> /** * @brief UART TX hypercall. * Write characters to the hardware queue and block the VCPU when * the queue is full and still there are characteres to tranfer. */ static void send(){ /*TODO: Implement interrupt-driven support to avoid to block the hypervisor for long periods. */ uint32_t i = 0; char* str = (char*)MoveFromPreviousGuestGPR(REG_A0); uint32_t size = MoveFromPreviousGuestGPR(REG_A1); /* Map the guest's buffer. */ char* str_mapped = (char*)tlbCreateEntry((uint32_t)str, vm_in_execution->base_addr, size, 0xf, NONCACHEABLE); for(i=0; i<size; i++){ while(!(UART0_LSR & 0x40)); UART0_RBR = str_mapped[i]; } MoveToPreviousGuestGPR(REG_V0, size); } /** * @brief UART Driver init call. */ static void uart_driver_init(){ if (register_hypercall(send, HCALL_UART_SEND) < 0){ ERROR("Error registering the HCALL_GET_VM_ID hypercall"); return; } printf("\nUART driver enabled."); } driver_init(uart_driver_init);
766aab3ae97e3affa4f0838802f4518728aa946d
[ "Markdown", "JavaScript", "Makefile", "Python", "C", "Shell" ]
93
C
zanon005/hellfire-hypervisor
695ebba6ce8cd5c7c547158d68c8351c4f43ddef
3d213d322a01192a37dd373b16e88305050dec3a
refs/heads/master
<file_sep><?php //if(file_exists(__DIR__ . '/debug_mode')) { error_reporting(E_ALL); ini_set('display_errors', 'On'); ini_set('display_startup_errors', 'On'); //} use \Slim\Http\Request as Request; use \Slim\Http\Response as Response; require 'vendor/autoload.php'; session_cache_limiter(false); session_start(); // Create and configure slim app $config = ['settings' => [ 'addContentLengthHeader' => false, 'displayErrorDetails' => true, 'debug' => true, 'log' => [ 'name' => 'api.dashidashcam.com', 'level' => Monolog\Logger::DEBUG, 'path' => __DIR__ . '/logs/app.log', ], 'db' => [ 'host' => 'localhost', 'dbname' => 'Dashi', 'user' => 'api', 'pass' => '<PASSWORD>' ], ]]; $app = new \Slim\App($config); $container = $app->getContainer(); // Setup Monolog $container['log'] = function($c) { $log = new \Monolog\Logger($c['settings']['log']['name']); $fileHandler = new \Monolog\Handler\StreamHandler($c['settings']['log']['path'], $c['settings']['log']['level']); $log->pushHandler($fileHandler); return $log; }; // Setup Database Connection $container['db'] = function ($c) { $settings = $c->get('settings')['db']; $pdo = new PDO('mysql:host=' . $settings['host'] . ';dbname=' . $settings['dbname'], $settings['user'], $settings['pass']); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); return $pdo; }; # Middleware to easily capture request ip address $app->add(new RKA\Middleware\IpAddress(false)); # Middleware for addressing CORS issue on web frontend $app->add(function (Request $request, Response $response, $next) { $response = $next($request, $response); return $response ->withHeader('Access-Control-Allow-Origin', 'http://localhost:4200') ->withHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization') ->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS'); }); $app->get('/', function(Request $request, Response $response) { return $response->withRedirect('http://docs.dashidamcam.apiary.io/'); })->setName('index'); // Github webhook proxy (for deployment hooks) $app->post('/update/{project}', function (Request $request, Response $response, $args) { $data = $request->getParsedBody(); $cmd = escapeshellcmd(__DIR__ . '/get_updates.sh ' . $request->getAttribute('project')); // Run the command and log output with timestamps system("$cmd 2>&1 | while IFS= read -r line; do echo \"\$(date -u) \$line\"; done >> " . __DIR__ . '/logs/update.log'); })->setName('update'); # Include Routers require_once __DIR__ . '/routers/Accounts.php'; require_once __DIR__ . '/routers/Tokens.php'; require_once __DIR__ . '/routers/Videos.php'; require_once __DIR__ . '/routers/Shares.php'; $app->run(); <file_sep><?php use \Slim\Http\Request as Request; use \Slim\Http\Response as Response; require_once __DIR__ . '/../middleware/Auth.php'; $app->group('/oauth', function () use ($app) { $app->post('/token', function (Request $request, Response $response) use ($app) { $data = $request->getParsedBody(); $errors = []; $json = []; $accountID = null; // Validate global parameters if (isset($data['grant_type'])) { if ($data['grant_type'] === 'refresh_token') { // Validate related parameters if (!isset($data['refresh_token'])) { $errors[] = [ 'code' => 1011, 'field' => 'refresh_token', 'message' => 'Must provide refresh_token' ]; } // Advance only if no errors occurred if (count($errors) == 0) { $stmt = $this->db->prepare(" SELECT Auth_Tokens.id, accountID FROM Auth_Tokens JOIN Token_Types ON Auth_Tokens.typeID=Token_Types.id WHERE token=:token AND active=true AND `type`='refresh' AND expires > NOW(); "); $stmt->execute([':token' => $data['refresh_token']]); // Generate new access token if refresh token is valid if ($row = $stmt->fetch()) { // Extend lifespan of refresh token $stmt = $this->db->prepare(" UPDATE Auth_Tokens SET expires=DATE_ADD(NOW(), INTERVAL 60 DAY), lastUsed=NOW() WHERE id=:id "); $stmt->execute([':id' => $row['id']]); $json['refresh_token'] = $data['refresh_token']; $accountID = $row['accountID']; } else { $errors[] = [ 'code' => 1012, 'field' => 'refresh_token', 'message' => 'The provided refresh token is invalid, expired, or revoked' ]; } } } else if($data['grant_type'] === 'password') { // Validate related parameters if (!isset($data['username'])) { $errors[] = [ 'code' => 1007, 'field' => 'username', 'message' => 'Must provide username' ]; } if (!isset($data['password'])) { $errors[] = [ 'code' => 1009, 'field' => 'password', 'message' => 'Must provide password' ]; } // Advance only if no errors occurred if (count($errors) == 0) { // Check username / retrieve hash $stmt = $this->db->prepare("SELECT id, password FROM Accounts WHERE email=:email;"); $stmt->execute([':email' => $data['username']]); if ($sqlData = $stmt->fetch()) { $accountID = $sqlData['id']; // Generate refresh token if password is valid if (isset($sqlData['password']) && password_verify($data['password'], $sqlData['password'])) { // Load refresh type id $refresh_type_id = $this->db->query("SELECT id FROM Token_Types WHERE `type`='refresh'") ->fetchColumn(0); // Create new access token $json['refresh_token'] = bin2hex(random_bytes(64)); $stmt = $this->db->prepare(" INSERT INTO Auth_Tokens (token, accountID, expires, issuedTo, typeID) VALUES (:token, :accountID, ADDDATE(NOW(), INTERVAL 60 DAY), :issuedTo, :typeID); "); $stmt->execute([ ':token' => $json['refresh_token'], ':accountID' => $accountID, ':issuedTo' => $request->getAttribute('ip_address'), ':typeID' => $refresh_type_id ]); } else { $errors[] = [ 'code' => 1010, 'field' => 'password', 'message' => 'The provided password is incorrect' ]; } } else { $errors[] = [ 'code' => 1008, 'field' => 'username', 'message' => 'The provided username does not exist' ]; } } } else { $errors[] = [ 'code' => 1006, 'field' => 'grant_type', 'message' => 'grant_type must be "password" or "refresh_token"' ]; } } else { $errors[] = [ 'code' => 1005, 'field' => 'grant_type', 'message' => 'Must provide grant type' ]; } // Add token to db and return to user if no errors if (count($errors) == 0 ) { // Create new access token $json['access_token'] = bin2hex(random_bytes(64)); // Load access type id $access_type_id = $this->db->query("SELECT id FROM Token_Types WHERE `type`='access'")->fetchColumn(0); $stmt = $this->db->prepare(" INSERT INTO Auth_Tokens (token, accountID, expires, issuedTo, typeID) VALUES (:token, :accountID, ADDDATE(NOW(), INTERVAL 1 HOUR), :issuedTo, :typeID); "); $stmt->execute([ ':token' => $json['access_token'], ':accountID' => $accountID, ':issuedTo' => $request->getAttribute('ip_address'), ':typeID' => $access_type_id ]); $json['token_type'] = 'Bearer'; $json['scope'] = 'all'; $json['expires_in'] = 3600; return $response->withJson($json, 201); } else { return $response->withJson([ 'code' => 1024, 'message' => 'Validation Failed', 'description' => 'The provided input does not meet the required JSON schema', 'errors' => $errors ], 400); } }); $app->delete('/token', function (Request $request, Response $response) use ($app) { $stmt = $this->db->prepare("UPDATE Auth_Tokens SET active=false WHERE token=:token; "); // Deactivate access token if ($stmt->execute([':token' => $request->getAttribute('accountID')])->rowCount() != 1) { return $response->withJson([ 'code' => 1004, 'message' => 'Invalid Access Token', 'description' => 'The provided access token is invalid' ]); } // Deactivate refresh token (if supplied) if ($data = $request->getParsedBody() && isset($data['refresh_token'])) { if ($stmt->execute([':token' => $data['refresh_token']])->rowCount() != 1) { return $response->withJson([ 'code' => 1003, 'message' => 'Invalid Refresh Token', 'description' => 'The provided refresh token is invalid' ], 400); } } return $response->withStatus(204); })->add('Authentication'); }); <file_sep><?php use \Slim\Http\Request as Request; use \Slim\Http\Response as Response; require_once __DIR__ . '/../middleware/Auth.php'; $app->group('/Account', function () use ($app) { $app->get('/Videos', function (Request $request, Response $response) use ($app) { // Get meta data for all of user's videos $stmt = $this->db->prepare("SELECT id, thumbnail, started, `size`, `length`, startLat, startLong, endLat, endLong FROM Videos WHERE accountID=:accountID; "); $stmt->execute(['accountID' => $request->getAttribute('accountID')]); $data = $stmt->fetchAll(); // Client expects hex encoding foreach($data as $key => $datum) { $data[$key]['id'] = bin2hex($datum['id']); $data[$key]['thumbnail'] = base64_encode($datum['thumbnail']); } return $response->withJson($data); })->setName('downloadVideos'); $app->put('/Videos/{id}', function (Request $request, Response $response, $args) { $data = $request->getParsedBody(); $stmt = $this->db->prepare(" INSERT INTO Videos (id, accountID, thumbnail, started, `size`, `length`, startLat, startLong, endLat, endLong) VALUES (:id, :accountID, :thumbnail, :started, :size, :length, :startLat, :startLong, :endLat, :endLong); "); $errors = []; // Ensure ID is a valid SHA256 hash if (!ctype_xdigit($args['id']) || strlen($args['id']) != 64) { $errors[] = [ 'code' => 1650, 'field' => 'id', 'message' => 'ID must be hex representation of valid SHA256 hash' ]; } if (!isset($data['thumbnail'])) { $errors[] = [ 'code' => 1589, 'field' => 'thumbnail', 'message' => 'Must provide thumbnail (base64 encoded)' ]; } if (!isset($data['started'])) { $errors[] = [ 'code' => 1070, 'field' => 'started', 'message' => 'Must provide started timestamp' ]; } if (!isset($data['size'])) { $errors[] = [ 'code' => 1071, 'field' => 'size', 'message' => 'Must provide size (in bytes)' ]; } if (!isset($data['length'])) { $errors[] = [ 'code' => 1072, 'field' => 'length', 'message' => 'Must provide length (in seconds)' ]; } if (!isset($data['startLong'])) { $errors[] = [ 'code' => 1072, 'field' => 'startLong', 'message' => 'Must provide starting GPS Longitude' ]; } if (!isset($data['startLat'])) { $errors[] = [ 'code' => 1072, 'field' => 'startLat', 'message' => 'Must provide starting GPS Latitude' ]; } if (!isset($data['endLong'])) { $errors[] = [ 'code' => 1072, 'field' => 'endLong', 'message' => 'Must provide ending GPS Longitude' ]; } if (!isset($data['endLat'])) { $errors[] = [ 'code' => 1072, 'field' => 'endLat', 'message' => 'Must provide ending GPS Latitude' ]; } if (count($errors) == 0) { try { $stmt->bindValue(':id', hex2bin($args['id']), PDO::PARAM_LOB); $stmt->bindValue(':accountID', $request->getAttribute('accountID')); $stmt->bindValue(':thumbnail', base64_decode($data['thumbnail']), PDO::PARAM_LOB); $stmt->bindValue(':started', $data['started']); $stmt->bindValue(':size', $data['size']); $stmt->bindValue(':length', $data['length']); $stmt->bindValue(':startLat', $data['startLat']); $stmt->bindValue(':startLong', $data['startLong']); $stmt->bindValue(':endLat', $data['endLat']); $stmt->bindValue(':endLong', $data['endLong']); $stmt->execute(); return $response->withJson([], 201); //->withStatus(201) //->withHeader('Location', '/Videos/' . $args['id']); } catch (PDOException $e) { if ($e->getCode() == 23000) { return $response->withJson([ 'code' => 1025, 'message' => 'Input Constraint Violation', 'description' => 'The provided input violates data constraints', 'errors' => [ 'code' => 1073, 'field' => 'id', 'message' => 'Video id is invalid' ] ], 400); } else { var_dump($e); } } } else { return $response->withJson([ 'code' => 1024, 'message' => 'Validation Failed', 'description' => 'The provided input does not meet the required JSON schema', 'errors' => $errors ], 400); } })->setName('uploadVideo'); $app->put('/Videos/{id}/content', function (Request $request, Response $response, $args) { $videoContent = $request->getBody()->getContents(); $notFound = false; $stmt = $this->db->prepare("SELECT videoContent FROM Videos WHERE id=:id AND accountID=:accountID;"); // Ensure ID is a valid SHA256 hash if (!ctype_xdigit($args['id']) || strlen($args['id']) != 64) { return $response->withJson([ 'code' => 1024, 'message' => 'Validation Failed', 'description' => 'The provided input does not meet the required JSON schema', 'errors' => [ 'code' => 1650, 'field' => 'id', 'message' => 'ID must be hex representation of valid SHA256 hash' ] ], 400); } // Ensure offset given $offset = $request->getQueryParam('offset'); if (is_null($offset)) { return $response->withJson([ 'code' => 1024, 'message' => 'Validation Failed', 'description' => 'The provided input does not meet the required JSON schema', 'errors' => [ 'code' => 1650, 'field' => 'offset', 'message' => 'The video chunk offset (i.e. part) must be provided' ] ], 400); } $stmt->bindValue(':id', hex2bin($args['id']), PDO::PARAM_LOB); $stmt->bindValue(':accountID', $request->getAttribute('accountID')); $stmt->execute(); if ($row = $stmt->fetch()) { if ($offset == -1) { try { $stmt = $this->db->prepare(" SET group_concat_max_len = CAST( (SELECT SUM(LENGTH(content)) FROM VideoChunks WHERE videoID=:id) AS UNSIGNED ); UPDATE Videos as V inner join ( SELECT videoID, GROUP_CONCAT(content ORDER BY part SEPARATOR '') as videoContent FROM VideoChunks WHERE videoID=:id GROUP BY videoID ) as C on V.id = C.videoID SET V.videoContent = C.videoContent WHERE id=:id AND accountID=:accountID; "); $stmt->bindValue(':id', hex2bin($args['id']), PDO::PARAM_LOB); $stmt->bindValue(':accountID', $request->getAttribute('accountID')); $stmt->execute(); // TODO: Delete all chunks (they are now duplicates) to free up space return $response->withJSON([], 201); } catch (PDOException $e) { var_dump($e); } } else { $stmt = $this->db->prepare("INSERT INTO VideoChunks (part, videoID, content) VALUES (:part, :videoID, :content); "); $stmt->execute([ ':part' => $offset, ':videoID' => hex2bin($args['id']), ':content' => $videoContent ]); return $response->withJSON([], 200); } } else { return $response->withJson([ 'code' => 1054, 'message' => 'Video Not Found', 'description' => 'The provided video id is either invalid or you lack sufficient authorization' ], 404); } })->setName('uploadVideoContent'); })->add('Authentication'); $app->get('/Account/Videos/{id}/content', function (Request $request, Response $response, $args) { ini_set('memory_limit', '512M'); // Ensure ID is a valid SHA256 hash if (!ctype_xdigit($args['id']) || strlen($args['id']) != 64) { return $response->withJson([ 'code' => 1024, 'message' => 'Validation Failed', 'description' => 'The provided input does not meet the required JSON schema', 'errors' => [ 'code' => 1650, 'field' => 'id', 'message' => 'ID must be hex representation of valid SHA256 hash' ] ], 400); } $stmt = $this->db->prepare("SELECT videoContent, accountID FROM Videos WHERE id=:id"); $stmt->bindValue(':id', hex2bin($args['id']), PDO::PARAM_LOB); $stmt->execute(); $row = $stmt->fetch(); if ($row) {//} && $row['accountID'] == $request->getAttribute('accountID')) { return $response->getBody()->write($row['videoContent']); } else { return $response->withJson([ 'code' => 1054, 'message' => 'Video Not Found', 'description' => 'The provided video id is either invalid or you lack sufficient authorization' ], 404); } })->setName('downloadVideoContent'); <file_sep><?php use \Slim\Http\Request as Request; use \Slim\Http\Response as Response; require_once __DIR__ . '/../middleware/Auth.php'; $app->get('/Share/{id}', function (Request $request, Response $response, $args) use ($app) { $stmt = $this->db->prepare("SELECT videoContent FROM Shares JOIN Videos ON Shares.videoID=Videos.id WHERE Shares.id=:id"); $stmt->bindValue(':id', base64_decode($args['id']), PDO::PARAM_LOB); $stmt->execute(); $row = $stmt->fetch(); if ($row) { $response->getBody()->write($row['videoContent']); return $response->withHeader('Content-Type', 'video/quicktime') ->withHeader('Content-Transfer-Encoding', 'binary') ->withHeader('Content-Disposition', 'inline; filename="' . basename('dashi_video.MOV') . '"'); } else { return $response->withJson([ 'code' => 1054, 'message' => 'Video Not Found', 'description' => 'The provided video id is either invalid or you lack sufficient authorization' ], 404); } })->setName('downloadSharedVideo'); $app->post('/Share', function (Request $request, Response $response) use ($app) { $data = $request->getParsedBody(); $stmt = $this->db->prepare("SELECT id FROM Videos WHERE id=:id;"); $stmt->bindValue(':id', hex2bin($data['id']), PDO::PARAM_LOB); $stmt->execute(); if ($row = $stmt->fetch()) { $stmt = $this->db->prepare("INSERT INTO Shares (id, videoID) VALUES (:id, :videoID);"); $share_id = random_bytes(255); $stmt->bindValue(':id', $share_id, PDO::PARAM_LOB); $stmt->bindValue(':videoID', hex2bin($data['id']), PDO::PARAM_LOB); $stmt->execute(); return $response->withJson([ 'shareID' => urlencode(base64_encode($share_id)) ]); } else { return $response->withJson([ 'code' => 1054, 'message' => 'Video Not Found', 'description' => 'The provided video id is either invalid or you lack sufficient authorization' ], 404); } })->setName('shareVideo'); <file_sep>#!/usr/bin/env bash # Define constants ONE=1 DNS_FRONTEND="192.168.33.105 dashidashcam.com" DNS_API="192.168.33.105 api.dashidashcam.com" # Require script to be run as root if [[ $(/usr/bin/id -u) -ne 0 ]]; then echo "Not running as root" exit fi # Add DNS record for frontend if one does not exist grep -Fxq "$DNS_FRONTEND" /etc/hosts if [ $? -eq $ONE ]; then echo "DNS record for Frontend missing, adding" echo "$DNS_FRONTEND" >> /etc/hosts fi # Add DNS record for api if one does not exist grep -Fxq "$DNS_API" /etc/hosts if [ $? -eq $ONE ]; then echo "DNS record for API missing, adding" echo "$DNS_API" >> /etc/hosts fi <file_sep><?php // Import Dependencies /** @noinspection PhpIncludeInspection */ require 'vendor/autoload.php'; use \Slim\Http\Request as Request; use \Slim\Http\Response as Response; class Authentication { private $container; public function __construct($container) { $this->container = $container; } public function __invoke(Request $request, Response $response, $next) { // Deny if missing Authorization header if ($request->hasHeader('Authorization')) { $auth_header = explode(' ', $request->getHeader('Authorization')[0]); $type = $auth_header[0]; $token = $auth_header[1]; // Only process if token type is valid if ($type === 'Bearer') { $stmt = $this->container->db->prepare(" SELECT Auth_Tokens.id, accountID, expires, NOW() as sql_time FROM Auth_Tokens JOIN Token_Types ON Auth_Tokens.typeID=Token_Types.id WHERE token=:token AND active=true AND `type`='access'; "); $stmt->execute([':token' => $token]); $data = $stmt->fetch(); // Update last used timestamp if token was valid if($data) $this->container->db->exec("UPDATE Auth_Tokens SET lastUsed=NOW() WHERE id=${data['id']}"); // Authorization is valid, allow request to precede if ($data && $data['expires'] > $data['sql_time']) { // Pass account id to request as attribute and continue to application return $next( $request ->withAttribute('accountID', $data['accountID']) ->withAttribute('accessToken', $token), $response ); } else { return $response ->withJson([ 'code' => 1002, 'message' => 'Unauthorized', 'description' => 'The provided access token is invalid, expired, or revoked' ], 401) ->withHeader('WWW-Authenticate', 'Bearer'); } } else { return $response->withJson([ 'code' => 1001, 'message' => 'Malformed Authorization', 'description' => 'Authorization header is malformed. Proper format: "Authorization: Bearer <token>"' ], 400); } } else { return $response ->withJson([ 'code' => 1000, 'message' => 'No Authorization Provided', 'description' => 'HTTP Authorization header required (e.g. Authorization: Bearer <token>)' ],401) ->withHeader('WWW-Authenticate', 'Bearer'); } } }<file_sep>#!/usr/bin/env bash # Constants defining the different modes DEV_MODE="DEV" PRODUCTION_MODE="PRODUCTION" DEFAULT_SITE_PATH="/etc/nginx/sites-enabled/default" # Load config file . $1 # Ensure required variables exist and are valid (NOTE: FRONT_END_REPO is optional, no check required) if [ -z ${MODE+x} ]; then echo "MODE is unset in $1, exiting"; exit 1; fi if [ "$MODE" -ne "$DEV_MODE" ] && [ "$MODE" -ne "$PRODUCTION_MODE" ]; then echo "MODE must be either \"DEV\" or \"PRODUCTION\"" fi if [ -z ${DOMAIN+x} ]; then echo "DOMAIN is unset in $1, exiting"; exit 1; fi if [ -z ${BACK_END_REPO+x} ]; then echo "BACK_END_REPO is unset in $1, exiting"; exit 1; fi if [ -z ${DB_PASSWORD+x} ]; then echo "DB_PASSWORD is unset in $1, exiting"; exit 1; fi if [ -z ${SHARE_ROOT+x} ]; then echo "SHARE_ROOT is unset in $1, exiting"; exit 1; fi # Nginx web root path API_WEB_ROOT="/var/www/api.$DOMAIN" FRONT_END_WEB_ROOT="/var/www/$DOMAIN" # Switch to root sudo su export DEBIAN_FRONTEND=noninteractive apt-get -y update ################################################## INSTALL SOFTWARE ################################################## # Install Nginx + PHP 7 apt-get install -y nginx php-fpm # Install MySQL + dependencies debconf-set-selections <<< "mysql-server mysql-server/root_password password $DB_PASSWORD" debconf-set-selections <<< "mysql-server mysql-server/root_password_again password $DB_PASSWORD" apt-get -y install mysql-server php-mysql # Install phpMyAdmin if in dev mode if [ $MODE = $DEV_MODE ]; then debconf-set-selections <<< "phpmyadmin phpmyadmin/dbconfig-install boolean true" debconf-set-selections <<< "phpmyadmin phpmyadmin/app-password-confirm password $DB_PASSWORD" debconf-set-selections <<< "phpmyadmin phpmyadmin/mysql/admin-pass password $DB_PASSWORD" debconf-set-selections <<< "phpmyadmin phpmyadmin/mysql/app-pass password $DB_PASSWORD" debconf-set-selections <<< "phpmyadmin phpmyadmin/reconfigure-webserver multiselect apache2" apt-get install -y phpmyadmin fi # Install composer dependencies apt-get -y install git zip unzip php7.0-zip # Allow for installation of composer chown -R `whoami`:root /usr/local/bin chown -R `whoami`:root /usr/local/share # Install Composer curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer ################################################## DOWNLOAD CODE ################################################## # Download frontend code if ! [ -z ${FRONT_END_REPO+x} ]; then git clone $FRONT_END_REPO $FRONT_END_WEB_ROOT fi # Download backend code (needed since not "shared" through vagrant in production) if [ $MODE = $PRODUCTION_MODE ]; then # API Code git clone $BACK_END_REPO $API_WEB_ROOT # Otherwise link the shared folder to supply code else # Link API root to Nginx's expected path (if needed) if ! [ -L $API_WEB_ROOT ]; then rm -rf $API_WEB_ROOT ln -fs $SHARE_ROOT $API_WEB_ROOT fi fi # Run composer (download dependencies) composer --working-dir=$API_WEB_ROOT install ################################################## NGINX CONFIG ################################################## # Destroy default site (if needed) if [ -L $DEFAULT_SITE_PATH ]; then rm -f $DEFAULT_SITE_PATH fi # Create virtual server configs (link if dev copy if production) if [ $MODE = $DEV_MODE ]; then ln -fs "$API_WEB_ROOT/api.$DOMAIN" "/etc/nginx/sites-available/api.$DOMAIN" if ! [ -z ${FRONT_END_REPO+x} ]; then ln -fs "$FRONT_END_WEB_ROOT/$DOMAIN" "/etc/nginx/sites-available/$DOMAIN" fi else cp "$API_WEB_ROOT/api.$DOMAIN" "/etc/nginx/sites-available/api.$DOMAIN" if ! [ -z ${FRONT_END_REPO+x} ]; then cp "$FRONT_END_WEB_ROOT/$DOMAIN" "/etc/nginx/sites-available/$DOMAIN" fi fi ln -fs "/etc/nginx/sites-available/api.$DOMAIN" "/etc/nginx/sites-enabled/api.$DOMAIN" if ! [ -z ${FRONT_END_REPO+x} ]; then ln -fs "/etc/nginx/sites-available/$DOMAIN" "/etc/nginx/sites-enabled/$DOMAIN" fi # Configure web root permissions if in dev mode if [ $MODE = $DEV_MODE ] then adduser ubuntu www-data chown -R www-data:www-data /var/www chmod -R g+rw /var/www fi ################################################## RESTART SERVICES ################################################## # Restart Nginx service nginx restart ################################################## MYSQL CONFIG ################################################## if [ $MODE = $PRODUCTION_MODE ]; then # Remove debug signal if [ -L "$API_WEB_ROOT/debug_mode" ]; then rm "$API_WEB_ROOT/debug_mode" fi # Modifies the passwords in source code according to custom script (including sql file) if [ -L "$API_WEB_ROOT/cred_config.sh" ]; then bash $API_WEB_ROOT/cred_config.sh fi fi # Use tmp file to securely supply mysql password OPTFILE="$(mktemp -q --tmpdir "${inname}.XXXXXX")" trap 'rm -f "$OPTFILE"' EXIT chmod 0600 "$OPTFILE" cat >"$OPTFILE" <<EOF [client] password="${<PASSWORD>}" EOF # Build the database schema mysql --defaults-extra-file="$OPTFILE" --user="root" < "$API_WEB_ROOT/schema.sql" <file_sep><?php use \Slim\Http\Request as Request; use \Slim\Http\Response as Response; require_once __DIR__ . '/../middleware/Auth.php'; $app->get('/Account', function (Request $request, Response $response) use ($app) { $stmt = $this->db->prepare("SELECT id, email, fullName, created FROM Accounts WHERE id=:id"); $stmt->execute([':id' => $request->getAttribute('accountID')]); return $response->withJson($stmt->fetch()); })->add('Authentication'); $app->post('/Accounts', function (Request $request, Response $response) use ($app) { $data = $request->getParsedBody(); $errors = []; // Validate input data if (!isset($data['email'])) { $errors[] = [ 'code' => 1014, 'field' => 'email', 'message' => 'Must provide email' ]; } else if (preg_match('/^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/', $data['email']) === 0) { $errors[] = [ 'code' => 1015, 'field' => 'email', 'message' => 'Not a valid email address' ]; } if (!isset($data['fullName'])) { $errors[] = [ 'code' => 1016, 'field' => 'fullName', 'message' => 'Must provide full name' ]; } else if (preg_match('/^\S+.*$/', $data['fullName']) === 0) { $errors[] = [ 'code' => 1017, 'field' => 'fullName', 'message' => 'Full name must not be blank' ]; } if (!isset($data['password'])) { $errors[] = [ 'code' => 1018, 'field' => 'password', 'message' => 'Must provide password' ]; } else if (preg_match('/^(?=.*[A-Z].*)(?=.*[0-9].*)(?=.*[a-z].*)(?=.*\W.*).{8,}$/', $data['password']) === 0) { $errors[] = [ 'code' => 1019, 'field' => 'password', 'message' => 'Password is too weak' ]; } // Input data is valid if (count($errors) == 0) { try { $stmt = $this->db->prepare(" INSERT INTO Accounts (email, fullName, password) VALUES (:email, :fullName, :password); "); $stmt->execute([ ':email' => $data['email'], ':fullName' => $data['fullName'], ':password' => password_hash($data['password'], PASSWORD_BCRYPT, ['cost' => 10]) ]); $accountID = $this->db->lastInsertId(); return $response->withJson([], 201); //->withStatus(201) //->withHeader('Location', "/Accounts/$accountID"); } catch(PDOException $e) { if ($e->getCode() == 23000) { return $response->withJson([ 'code' => 1025, 'message' => 'Input Constraint Violation', 'description' => 'The provided input does violates data constraints', 'errors' => [ 'code' => 1013, 'field' => 'email', 'message' => 'Email address is already in use' ] ], 400); } else { throw $e; } } } else { return $response->withJson([ 'code' => 1024, 'message' => 'Validation Failed', 'description' => 'The provided input does not meet the required JSON schema', 'errors' => $errors ], 400); } }); $app->patch('/Accounts/{id}', function (Request $request, Response $response, $args) use ($app) { $data = $request->getParsedBody(); $errors = []; if ($request->getAttribute('accountID') == $args['id']) { foreach ($data as $key => $value) { switch ($key) { case 'email': if (preg_match('/^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/', $value) === 0) { $errors = [ 'code' => 1015, 'field' => 'email', 'message' => 'Not a valid email address' ]; } break; case 'password'; if (preg_match('/^(?=.*[A-Z].*)(?=.*[0-9].*)(?=.*[a-z].*)(?=.*\W.*).{8,}$/', $value) === 0) { $errors = [ 'code' => 1019, 'field' => 'password', 'message' => 'Password is too <PASSWORD>' ]; } break; case 'fullName': if (preg_match('/^\S+.*$/', $data['fullName']) === 0) { $errors = [ 'code' => 1017, 'field' => 'fullName', 'message' => 'Full name must not be blank' ]; } break; default: $errors = [ 'code' => 1035, 'field' => $value, 'message' => 'Unsupported Field' ]; } } } else { return $response->withJson([ 'code' => 1030, 'message' => 'Account Not Found', 'description' => 'The provided account id is either invalid or you lack sufficient authorization' ], 404); } // Return the modified resource or error message if (count($errors) == 0) { $sql = "UPDATE Accounts SET "; $cols = ['fullName', 'email', 'password']; $sql_cols = []; foreach($cols as $col) $sql_cols[] = isset($data[$col]) ? $col . '=:' . $col : $col . '=' . $col; $stmt = $this->db->prepare($sql . implode(',', $sql_cols) . " WHERE id=:id;"); $sql_data = [':id' => $request->getAttribute('accountID')]; foreach($data as $key => $value) $sql_data[':' . $key] = $value; $stmt->execute($sql_data); $stmt = $this->db->prepare("SELECT * FROM Accounts WHERE id=:id;"); $stmt->execute([':id' => $request->getAttribute('accountID')]); return $response->withJson($stmt->fetch(), 200); } else { return $response->withJson([ 'code' => 1024, 'message' => 'Validation Failed', 'description' => 'The provided input does not meet the required JSON schema', 'errors' => $errors ], 400); } })->add('Authentication'); <file_sep> # Backend Server Vagrant.configure("2") do |config| # Base VM config.vm.box = "ubuntu/xenial64" # Use the bash provisioning script to configure the vm config.vm.provision "shell" do |s| s.path = "provision.sh" s.args = "/vagrant/dev_provision.conf" end # Forward port config.vm.network "forwarded_port", guest: 80, host: 8080 # Set up private networking config.vm.network "private_network", ip: "192.168.33.105" # Mount project directory to /vagrant as a shared directory config.vm.synced_folder "./", "/vagrant", owner: "www-data", group: "www-data" end <file_sep>CREATE DATABASE `Dashi`; USE `Dashi`; CREATE TABLE Accounts ( id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, email VARCHAR(64) UNIQUE NOT NULL, password VARCHAR(96) NOT NULL, fullName VARCHAR(64) NOT NULL, created DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ); CREATE TABLE Videos ( id BINARY(32) UNIQUE NOT NULL, accountID INT NOT NULL, thumbnail MEDIUMBLOB NOT NULL, videoContent LONGBLOB DEFAULT NULL, started DATETIME NOT NULL, size INT NOT NULL, length INT NOT NULL, startLat FLOAT DEFAULT NULL, startLong FLOAT DEFAULT NULL, endLat FLOAT DEFAULT NULL, endLong FLOAT DEFAULT NULL, PRIMARY KEY (id), FOREIGN KEY (accountID) REFERENCES Accounts (id) ); CREATE TABLE VideoChunks ( id INT NOT NULL AUTO_INCREMENT, part INT NOT NULL, videoID BINARY(32) NOT NULL, content LONGBLOB NOT NULL, PRIMARY KEY (id, part), FOREIGN KEY (videoID) REFERENCES Videos (id) ); CREATE TABLE Shares ( id BINARY(255) UNIQUE NOT NULL, videoID BINARY(32) NOT NULL, PRIMARY KEY (id), FOREIGN KEY (videoID) REFERENCES Videos (id) ); CREATE TABLE Token_Types ( id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, type VARCHAR(7) NOT NULL ); /* Populate table with the valid token types */ INSERT INTO Token_Types (type) VALUES ('access'); INSERT INTO Token_Types (type) VALUES ('refresh'); CREATE TABLE Auth_Tokens ( id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, token VARCHAR(1024) NOT NULL UNIQUE, accountID INT NOT NULL, created DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, lastUsed DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, expires DATETIME NOT NULL, active BOOL NOT NULL DEFAULT TRUE, issuedTo VARCHAR(15) NOT NULL, typeID INT NOT NULL, FOREIGN KEY (accountID) REFERENCES Accounts (id), FOREIGN KEY (typeID) REFERENCES Token_Types (id) ); CREATE USER 'api'@'localhost' IDENTIFIED BY '<PASSWORD>'; GRANT SELECT ON Dashi.* TO 'api'@'localhost'; GRANT UPDATE ON Dashi.* TO 'api'@'localhost'; GRANT INSERT ON Dashi.* TO 'api'@'localhost'; GRANT DELETE ON Dashi.* TO 'api'@'localhost'; <file_sep>#!/usr/bin/env bash # Apache web root path API_WEB_ROOT="/var/www/api.dashidashcam.com" ANG_WEB_ROOT="/var/www/dashidashcam.com" DEFAULT_SITE_PATH="/etc/apache2/sites-enabled/000-default.conf" # Path to code (will by symlinked into web root) SHARE_ROOT=$1 # Password for database server (root) PASSWORD=$(<$2) # Mode for server configuration MODE=$3 # Constants defining the different modes DEV_MODE="DEV" PRODUCTION_MODE="PRODUCTION" # Password for api database user (accept commandline param or default to password for devmode) if [ $MODE = $DEV_MODE ]; then API_USER_PASSWORD="$PASSWORD" else API_USER_PASSWORD=$(<$4) fi # Switch to root sudo su export DEBIAN_FRONTEND=noninteractive apt-get -y update ################################################## INSTALL SOFTWARE ################################################## # Install Nginx + PHP 7 apt-get install -y nginx php-fpm # Install MySQL + dependencies debconf-set-selections <<< "mysql-server mysql-server/root_password password $PASSWORD" debconf-set-selections <<< "mysql-server mysql-server/root_password_again password $PASSWORD" apt-get -y install mysql-server php-mysql # Install phpMyAdmin if in dev mode if [ $MODE = $DEV_MODE ]; then debconf-set-selections <<< "phpmyadmin phpmyadmin/dbconfig-install boolean true" debconf-set-selections <<< "phpmyadmin phpmyadmin/app-password-confirm password $PASSWORD" debconf-set-selections <<< "phpmyadmin phpmyadmin/mysql/admin-pass password $PASSWORD" debconf-set-selections <<< "phpmyadmin phpmyadmin/mysql/app-pass password $PASSWORD" debconf-set-selections <<< "phpmyadmin phpmyadmin/reconfigure-webserver multiselect apache2" apt-get install -y phpmyadmin fi # Install composer dependencies apt-get -y install git zip unzip php7.0-zip # Allow for installation of composer chown -R `whoami`:root /usr/local/bin chown -R `whoami`:root /usr/local/share # Install Composer curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer ################################################## DOWNLOAD CODE ################################################## # Download frontend code #git clone https://github.com/ $ANG_WEB_ROOT # Download backend code (needed since not "shared" through vagrant in production) if [ $MODE = $PRODUCTION_MODE ]; then # API Code git clone <EMAIL>:DashiDashCam/DashiWebAPI.git $API_WEB_ROOT # Otherwise link the shared folder to supply code else # Link API root to Apache2's expected path (if needed) if ! [ -L $API_WEB_ROOT ]; then rm -rf $API_WEB_ROOT ln -fs $SHARE_ROOT $API_WEB_ROOT fi fi # Run composer (download dependencies) composer --working-dir=$API_WEB_ROOT install ################################################## APACHE CONFIG ################################################## # Destroy default site (if needed) if [ -L $DEFAULT_SITE_PATH ]; then rm -f $DEFAULT_SITE_PATH fi # Create virtual server configs (link if dev copy if production) if [ $MODE = $DEV_MODE ]; then ln -fs $API_WEB_ROOT/api.conf /etc/apache2/sites-enabled/api.dashidashcam.com.conf #ln -fs $API_WEB_ROOT/insecurity.conf /etc/apache2/sites-enabled/dashidashcam.com.conf else cp $API_WEB_ROOT/api.conf /etc/apache2/sites-enabled/api.dashidashcam.com.conf #cp $API_WEB_ROOT/insecurity.conf /etc/apache2/sites-enabled/dashidashcam.com.conf fi # Configure web root permissions if in dev mode if [ $MODE = $DEV_MODE ] then adduser ubuntu www-data chown -R www-data:www-data /var/www chmod -R g+rw /var/www fi # Enable Apache mod_rewrite a2enmod rewrite ################################################## RESTART SERVICES ################################################## # Restart Apache2 service apache2 restart ################################################## MYSQL CONFIG ################################################## if [ $MODE = $PRODUCTION_MODE ]; then # Remove debug signal rm "$API_WEB_ROOT/debug_mode" # Modifies the passwords in source code of core.php and scanner.py bash $API_WEB_ROOT/cred_config.sh $API_USER_PASSWORD fi # Use tmp file to securely supply mysql password OPTFILE="$(mktemp -q --tmpdir "${inname}.XXXXXX")" trap 'rm -f "$OPTFILE"' EXIT chmod 0600 "$OPTFILE" cat >"$OPTFILE" <<EOF [client] password="${<PASSWORD>}" EOF # Build the database schema mysql --defaults-extra-file="$OPTFILE" --user="root" < "$API_WEB_ROOT/schema.sql" # Create API user in db mysql --defaults-extra-file="$OPTFILE" --user="root" Dashi <<EOF CREATE USER 'api'@'localhost' IDENTIFIED BY '$API_USER_PASSWORD'; GRANT SELECT ON Dashi.* TO 'api'@'localhost'; GRANT UPDATE ON Dashi.* TO 'api'@'localhost'; GRANT INSERT ON Dashi.* TO 'api'@'localhost'; GRANT DELETE ON Dashi.* TO 'api'@'localhost'; EOF
d8aefa70e0b34f8270ce151c880b405c6d7981d7
[ "SQL", "Ruby", "PHP", "Shell" ]
11
PHP
DashiDashCam/DashiWebAPI
17563044ac4466f8fd3a39c4e425e84d2ccdb8bc
5b3329b8ce5315a95c3e445b7441e8de0a2845a5
refs/heads/master
<repo_name>Lukxsx/fuel-logger<file_sep>/fuel-logger/documentation/testing.md # Testing The software is tested with automated JUnit tests and manually testing the features on different platforms. ## JUnit tests Most of the tests are testing the application logic in the _fuellogger.logic_ package. Tests are simulating typical uses of the application. Tests of _RefuelManager_ class are testing adding and managing the cars and refuelings. The tests of _StatisticsManager_ are testing mainly validity of different calculations. The tests of _Database_ class are testing if the SQLite database works correctly. The tests are performed on a temporary test database that is automatically deleted after the tests. Database tests are testing if data is saved correctly and cases like duplicates. There are not many tests on _Car_ and _Refueling_ classes, because they are mostly only classes to store data. They consist mainly of getters. There are tests for the _Refueling_ class that test if refueling cost is calculated correctly. The _ConfigFile_ class has also few tests. The user interface is not tested. ## Test coverage ![test coverage](images/testcoverage.png) ## Manual testing The software is also tested on Cubbli virtual machine, my own PC running Arch Linux and a laptop running Cubbli. All requirements are tested and they are working. Input fields validations are also tested with wrong inputs and there are no problems. However the virtual Cubbli installation has some issues occasionally with SQLite. It gives an error message of a locked or missing database. Other students in this course have also had the same problem with virtual Cubbli. <file_sep>/fuel-logger/src/main/java/fuellogger/domain/Refueling.java package fuellogger.domain; import java.time.LocalDate; import java.util.Objects; /** * Contains basic information of the refueling. */ public class Refueling implements Comparable<Refueling> { /* these variables are public because this class is mainly used for storing data and these values are referenced and needed very often. */ /** * Car that this refueling belongs to */ public Car car; /** * Odometer value */ public int odometer; /** * Volume in liter */ public double volume; /** * Date of the refueling */ public LocalDate date; /** * Price of fuel per liter in euros */ public double price; public Refueling(Car car, int odometer, double volume, double price, LocalDate date) { this.car = car; this.odometer = odometer; this.volume = volume; this.date = date; this.price = price; } // these getter methods are required to make the GUI's tableview work public int getOdometer() { return odometer; } public Car getCar() { return car; } public double getPrice() { return price; } public LocalDate getDate() { return date; } public double getVolume() { return volume; } /** * Returns the cost of refueling (price x amount) * @return cost of refueling */ public double getCost() { return this.volume * this.price; } /** * Compares two refueling objects based on the odometer value * @param t * @return */ @Override public int compareTo(Refueling t) { if (t.odometer < this.odometer) { return 1; } if (t.odometer > this.odometer) { return -1; } return 0; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } final Refueling other = (Refueling) obj; if (this.odometer != other.odometer) { return false; } if (!Objects.equals(this.car, other.car)) { return false; } return true; } } <file_sep>/fuel-logger/src/test/java/fuellogger/dao/ConfigFileTest.java package fuellogger.dao; import java.io.File; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; public class ConfigFileTest { public ConfigFileTest() { } @BeforeClass public static void setUpClass() { } @Before public void setUp() { File testconf = new File("test.conf"); testconf.delete(); } @After public void tearDown() { File testconf = new File("test.conf"); testconf.delete(); } @Test public void newFileIsCreatedIfFileMissing() { File test = new File("test.conf"); assertEquals(false, test.exists()); ConfigFile c = new ConfigFile("test.conf"); assertEquals(true, test.exists()); } @Test public void correctDefaultValue() { ConfigFile c = new ConfigFile("test.conf"); ConfigFile c2 = new ConfigFile("test.conf"); assertEquals(true, c2.getDbname().equals("database.db")); } } <file_sep>/fuel-logger/src/main/java/fuellogger/Main.java package fuellogger; import fuellogger.gui.GUI; /** * The main class that launches the GUI's main function. This fixes launching * JavaFX applications from the jar. */ public class Main { public static void main(String[] args) { GUI.main(args); } } <file_sep>/README.md # Fuel logger A program to keep track of the fuel consumption of a car. It can show interesting charts and data of your car's fuel consumption and cost of ownership. ## Releases * [Final release](https://github.com/Lukxsx/ot-harjoitustyo/releases/tag/final) * [Viikko 6](https://github.com/Lukxsx/ot-harjoitustyo/releases/tag/viikko6) * [Viikko 5](https://github.com/Lukxsx/ot-harjoitustyo/releases/tag/viikko5) ## Documentation * [Requirements](fuel-logger/documentation/requirements.md) * [User manual](fuel-logger/documentation/user-manual.md) * [Architecture](fuel-logger/documentation/architecture.md) * [Working hours](fuel-logger/documentation/working%20hours.md) * [Testing report](fuel-logger/documentation/testing.md) ## Commands ### Running from Maven ``` mvn compile exec:java -Dexec.mainClass=fuellogger.Main ``` ### Package jar ``` mvn package ``` Jar file will be generated in _target/fuel-logger-1.0-SNAPSHOT.jar_ ### Running tests ``` mvn test ``` ### Test coverage ``` mvn test jacoco:report ``` ### Checkstyle ``` mvn jxr:jxr checkstyle:checkstyle ``` Checkstyle is generated in _target/site/checkstyle.html_ ### Javadoc ``` mvn javadoc:javadoc ``` Javadoc is generated in _target/site/apidocs/index.html_ <file_sep>/fuel-logger/src/test/java/fuellogger/logic/RefuelManagerTest.java package fuellogger.logic; import fuellogger.dao.Database; import fuellogger.domain.Car; import fuellogger.domain.Refueling; import java.io.File; import java.time.LocalDate; import org.junit.After; import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; public class RefuelManagerTest { RefuelManager rm; Database db; public RefuelManagerTest() { db = new Database("rmtest.db"); rm = new RefuelManager(db); } @Before public void setUp() { rm.clearDB(); } @After public void tearDown() { File dbfile = new File("rmtest.db"); dbfile.delete(); } @Test public void addingCarAddsToList() { Car c = new Car("Volvo", 80); rm.addCar(c); assertEquals(true, rm.cars.contains(c)); Car c2 = new Car("Toyota", 60); rm.addCar(c2); assertEquals(true, rm.cars.get(1).equals(c2)); } @Test public void cantAddSameCarMultipleTimes() { Car c = new Car("Volvo", 80); rm.addCar(c); rm.addCar(c); assertEquals(true, rm.cars.size() == 1); } @Test public void gettingRefuelingsFromDBWorks() { Car c = new Car("Volvo", 80); rm.addCar(c); LocalDate d1 = LocalDate.of(2020, 2, 16); Refueling r1 = new Refueling(c, 373020, 69.92, 0, d1); LocalDate d2 = LocalDate.of(2020, 2, 28); Refueling r2 = new Refueling(c, 373773, 70.13, 0, d2); LocalDate d3 = LocalDate.of(2020, 3, 13); Refueling r3 = new Refueling(c, 374545, 71.61, 0, d3); rm.addRefueling(r1); rm.addRefueling(r2); rm.addRefueling(r3); RefuelManager rm2 = new RefuelManager(db); assertEquals(true, rm2.refuelings.get(c).size() == 3); } @Test public void refuelingAmountIsCorrect() { Car c1 = new Car("Volvo", 80); Car c2 = new Car ("BMW", 70); LocalDate d1 = LocalDate.of(2020, 2, 16); Refueling r1 = new Refueling(c1, 373020, 69.92, 0, d1); LocalDate d2 = LocalDate.of(2020, 2, 28); Refueling r2 = new Refueling(c2, 373773, 70.13, 0, d2); LocalDate d3 = LocalDate.of(2020, 3, 13); Refueling r3 = new Refueling(c1, 374545, 71.61, 0, d3); rm.addCar(c1); rm.addCar(c2); rm.addRefueling(r1); rm.addRefueling(r2); rm.addRefueling(r3); assertEquals(true, rm.numberOfRefuelings(c1) == 2); assertEquals(true, rm.numberOfRefuelings(c2) == 1); } } <file_sep>/fuel-logger/documentation/user-manual.md # User manual ## Running ### From Maven ```mvn compile exec:java -Dexec.mainClass=fuellogger.Main``` ### Jar file ```java -jar fuel-logger-1.0-SNAPSHOT.jar``` or ```java -jar fuel-logger.jar``` depending on the filename. ## Configuration The application generates automatically database file called _database.db_ and a config file _fuellogger.conf_ into the folder from which it is executed. There is no need to configure the software in normal use use but if desired, the user can change the database file used using the _fuellogger.conf_ file. The config file looks like this ```dbname=database.db```. The database name can be changed by changing _database.db_ to some other name. ## Usage All data inserted to the application is automatically stored in the database. ### Car selection view When the application is launched, it will initially open in the car selection view. A new car can be added with the dialog at the bottom. A car needs a name and fuel tank capacity in liters. Select the car from the list and click "Select" button to continue. ![selection view](images/manual1.png) ### Refueling view Refueling view shows a list of refuelings for the selected car. A new refueling can be added with the dialog in the bottom. A new refueling needs following information: * Odometer value * Volume in liters * Price of fuel in euros (per liter) * Date of refueling Fill in the information and click the "Add" button. At least two refuelings are required to measure the average consumption. Statistics of the car are shown in the bottom. Press "Charts" for the charts view or press "Car selection" to go back to the car selection. ![refueling view](images/manual2.png) ### Charts and graphs Click the "Charts" button in refueling view to show the charts view. There are currently three charts available * Fuel consumption by month * Cost by month * Kilometers by month Select the chart and year from the drop-down menus and click "Select". The graph will be shown. Click "Back" to go back to the refueling view. ![charts view](images/manual3.png) <file_sep>/fuel-logger/documentation/requirements.md # Requirements specification ## Purpose The purpose of this software is to keep logs of refueling costs of a car. The software can then view graphs and other interesting stats of your car and it's costs. You can add multiple cars to the software. ## Users There will be no other roles than normal users because there is no really need for them. ## Basic functionality - [x] Graphical user interface - [x] Data is stored in SQLite database - [x] Adding a car (name, fuel tank capacity etc.) - [x] Selecting a car to use - [x] Logging a refueling (kilometrage, volume in litres) - [x] Viewing average fuel consumption - [x] Viewing graphs of fuel consumption - [x] Viewing graphs of cost - [x] Viewing graphs of driven kilometres - [x] Configuration file to specify database file name ## Future features - [ ] Text-based UI for quick fuel logging without need for opening the graphical UI - [ ] Logging of other costs like repairs, taxes and insurances - [ ] Support for other than SI and euro units (miles, dollars etc.) - [ ] Exporting data as CSV or some other common file type - [ ] Backup and restore of the data to a file (to use the software easily on another computer) ## Limitations * Only works when tank is filled full, no partial refuelings * Min. 2 refuelings needed to count fuel consumptions * Must work on common Linux distributions * Only supports SI units and euros * Data is saved locally <file_sep>/fuel-logger/documentation/architecture.md # Architecture ## Structure ![package structure](images/packages.png) * _fuellogger.ui_ contains a graphical user interface. * _fuellogger.logic_ contains the main application logic that manages cars and refuelings. It also performs calculations used for statistic views and charts. * _fuellogger.domain_ contains the Car and Refueling classes that are used to store information in the application. * _fuellogger.dao_ contains classes used to save data into the hard disk. (SQLite database and config file) ## Class diagram ![diagram](images/class%20diagram.png) ## Application logic Application logic is implemented with the _RefuelManager_ and _StatisticsManager_ classes. * __RefuelManager__ manages and stores cars and refuelings. It also uses _Database_ class to store data to the database. * Adding a car * Listing of cars * Adding a refueling * Listing of refuelings * Listing of refuelings by month and year * __StatisticsManager__ performs calculations to be displayed in the graphical * Getting statistics of a car * Getting statistics of refuelings * Output data to generate charts in the GUI Logic classes use the _Car_ and _Refueling_ classes from _fuellogger.domain_ package to store the information locally. _RefuelingManager_ uses _Database_ class from _fuellogger.dao_ package to save the data to a SQLite database. ## Data storage ### Database This application uses a SQLite database to save the Car and Refueling objects. __Database__ class handles reading and inserting to the database. The database file is created and read to the directory where the application is executed. By default the name of the file is _database.db_. The database uses ```UNIQUE``` constraints to avoid duplicate entries in the database. #### Database schema ``` CREATE TABLE Car (id INTEGER PRIMARY KEY, name TEXT UNIQUE, fuel_capacity INTEGER NOT NULL); CREATE TABLE Refueling (id INTEGER PRIMARY KEY, car_id INTEGER, odometer INTEGER UNIQUE, volume REAL, day INTEGER, month INTEGER, year INTEGER, price REAL); ``` ### Config file There is a configuration file called _fuellogger.conf_ that is used to specify the database file SQLite uses. The configuration file is created automatically with the default value if no such file exists. There is no need to create the config file manually. There is currently no way to validate if the config file is correct. It is only checked if the file exists. However in case the file is missing or it doesn't contain the dbname property, default value _database.db_ is used instead. The configuration file looks like this: ```dbname=database.db``` ## Sequences ### Startup sequence ![startup sequence](images/startupseq.png) JavaFX GUI is launched. GUI creates a new ConfigFile. Database name value is read from ConfigFile. A new Database is created with dbName. A new RefuelManager is created with the Database. A new StatisticsManager is created with RefuelManager. GUI asks RefuelManager for a list of cars. RefuelManager fetches cars from the Database. A list of cars is shown in the GUI. ### Car adding sequence diagram ![car adding sequence](images/caraddseq.png) User inserts car's details in fields and clicks car adding button. A new car object is created and addCar() method in RefuelingManager class is called. RefuelManager tries to add car into the Database with Database's addCar() method. If it returns true the car is also added into RefuelManager's local ArrayList of cars. The created car object is added to GUIs observablelist. ### Refueling adding sequence diagram ![refuel adding seq](images/refueladdseq.png) User inserts refueling details in fields and clicks adding button. A new refueling object is created and addRefueling() method in RefuelingManager class is called. RefuelManager calls Database's addRefueling(). If it returns true, the refueling is also added into RefuelingManager's local HashMap of <Car, Refueling> pairs. Databases addRefueling() tries to insert refueling into the database, if the insertion is success it returns true. The created refueling object is added to GUIs observablelist. <file_sep>/fuel-logger/src/test/java/fuellogger/logic/StatisticsManagerTest.java package fuellogger.logic; import fuellogger.dao.Database; import fuellogger.domain.Car; import fuellogger.domain.Refueling; import java.io.File; import java.sql.SQLException; import java.time.LocalDate; import org.junit.After; import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; public class StatisticsManagerTest { RefuelManager rm; StatisticsManager sm; public StatisticsManagerTest() { Database test = new Database("smtest.db"); rm = new RefuelManager(test); sm = new StatisticsManager(rm); } @Before public void setUp() { rm.clearDB(); } @After public void tearDown() { File dbfile = new File("smtest.db"); dbfile.delete(); } @Test public void avgConsumptionReturnsZeroIfOnlyOneRefueling() { Car c = new Car("Volvo", 80); LocalDate d = LocalDate.of(2020, 1, 1); Refueling r = new Refueling(c, 100000, 70, 1.5, d); rm.addCar(c); rm.addRefueling(r); assertEquals(true, sm.avgConsumption(c) == 0); } @Test public void avgConsumptionReturnsZeroIfNoRefuelings() { Car c = new Car("Volvo", 80); rm.addCar(c); assertEquals(true, sm.avgConsumption(c) == 0); } @Test public void avgConsumptionCorrectWhenTwoRefuelings() { Car c = new Car("Volvo", 80); rm.addCar(c); LocalDate d1 = LocalDate.of(2020, 2, 28); Refueling r1 = new Refueling(c, 373773, 70.13, 1.5, d1); LocalDate d2 = LocalDate.of(2020, 3, 13); Refueling r2 = new Refueling(c, 374545, 71.61, 1.5, d2); rm.addRefueling(r1); rm.addRefueling(r2); assertEquals(true, sm.avgConsumption(c) == 9.275906735751295); } @Test public void avgConsumptionCorrectWhenMultipleRefuelings() { Car c = new Car("Volvo", 80); rm.addCar(c); LocalDate d1 = LocalDate.of(2020, 2, 16); Refueling r1 = new Refueling(c, 373020, 69.92, 1.5, d1); LocalDate d2 = LocalDate.of(2020, 2, 28); Refueling r2 = new Refueling(c, 373773, 70.13, 1.5, d2); LocalDate d3 = LocalDate.of(2020, 3, 13); Refueling r3 = new Refueling(c, 374545, 71.61, 1.5, d3); rm.addRefueling(r1); rm.addRefueling(r2); rm.addRefueling(r3); assertEquals(true, sm.avgConsumption(c) == 9.294426229508197); } @Test public void refuelingConsumptionTest1() { // return 0 if can't count consumption Car c = new Car("Volvo", 80); rm.addCar(c); LocalDate d1 = LocalDate.of(2020, 2, 16); Refueling r1 = new Refueling(c, 373020, 69.92, 0, d1); LocalDate d2 = LocalDate.of(2020, 2, 28); Refueling r2 = new Refueling(c, 373773, 70.13, 0, d2); LocalDate d3 = LocalDate.of(2020, 3, 13); Refueling r3 = new Refueling(c, 374545, 71.61, 0, d3); rm.addRefueling(r1); rm.addRefueling(r2); rm.addRefueling(r3); assertEquals(true, sm.getConsumption(r3) == 0); } @Test public void refuelingConsumptionTest2() { // tests if method counts the consumption correctly Car c = new Car("Volvo", 80); rm.addCar(c); LocalDate d1 = LocalDate.of(2020, 2, 16); Refueling r1 = new Refueling(c, 373020, 69.92, 0, d1); LocalDate d2 = LocalDate.of(2020, 2, 28); Refueling r2 = new Refueling(c, 373773, 70.13, 0, d2); LocalDate d3 = LocalDate.of(2020, 3, 13); Refueling r3 = new Refueling(c, 374545, 71.61, 0, d3); rm.addRefueling(r1); rm.addRefueling(r2); rm.addRefueling(r3); assertEquals(true, sm.getConsumption(r2) == 9.275906735751295); } @Test public void monthAvgReturnsZeroIfNoRefuelingsInMonth() { Car c = new Car("Volvo", 80); rm.addCar(c); LocalDate d1 = LocalDate.of(2020, 2, 16); Refueling r1 = new Refueling(c, 373020, 69.92, 0, d1); LocalDate d2 = LocalDate.of(2020, 2, 28); Refueling r2 = new Refueling(c, 373773, 70.13, 0, d2); LocalDate d3 = LocalDate.of(2020, 3, 13); Refueling r3 = new Refueling(c, 374545, 71.61, 0, d3); rm.addRefueling(r1); rm.addRefueling(r2); rm.addRefueling(r3); assertEquals(true, sm.monthAvg(c, 1, 2020) == 0); } @Test public void monthAvgTest() { Car c = new Car("Volvo", 80); rm.addCar(c); LocalDate d1 = LocalDate.of(2019, 5, 24); Refueling r1 = new Refueling(c, 363619, 69.02, 0, d1); LocalDate d2 = LocalDate.of(2019, 5, 9); Refueling r2 = new Refueling(c, 362919, 68.05, 0, d2); LocalDate d3 = LocalDate.of(2019, 4, 23); Refueling r3 = new Refueling(c, 362268, 66.75, 0, d3); rm.addRefueling(r1); rm.addRefueling(r2); rm.addRefueling(r3); assertEquals(true, sm.monthAvg(c, 5, 2019) == 9.86); assertEquals(true, sm.monthAvg(c, 4, 2019) == 10.453149001536097); } @Test public void monthAvgMultipleYearTest() { Car c = new Car("Volvo", 80); rm.addCar(c); LocalDate d1 = LocalDate.of(2020, 1, 31); Refueling r1 = new Refueling(c, 372358, 66.63, 0, d1); LocalDate d2 = LocalDate.of(2020, 1, 15); Refueling r2 = new Refueling(c, 371707, 70.23, 0, d2); LocalDate d3 = LocalDate.of(2019, 12, 18); Refueling r3 = new Refueling(c, 371014, 66.53, 0, d3); LocalDate d4 = LocalDate.of(2019, 11, 22); Refueling r4 = new Refueling(c, 370426, 70.59, 0, d4); rm.addRefueling(r1); rm.addRefueling(r2); rm.addRefueling(r3); rm.addRefueling(r4); assertEquals(true, sm.monthAvg(c, 1, 2020) == 10.235023041474655); assertEquals(true, sm.monthAvg(c, 12, 2019) == 10.134199134199134); } @Test public void monthAvgReturnsZeroIfNoRefuelingsOnYear() { Car c = new Car("Volvo", 80); rm.addCar(c); LocalDate d1 = LocalDate.of(2020, 1, 31); Refueling r1 = new Refueling(c, 372358, 66.63, 0, d1); LocalDate d2 = LocalDate.of(2020, 1, 15); Refueling r2 = new Refueling(c, 371707, 70.23, 0, d2); rm.addRefueling(r1); rm.addRefueling(r2); assertEquals(true, sm.monthAvg(c, 12, 2019) == 0); } @Test public void kmsInMonthReturnsZeroIfNoRefuelingsInMonth() { Car c = new Car("Volvo", 80); rm.addCar(c); LocalDate d1 = LocalDate.of(2020, 2, 16); Refueling r1 = new Refueling(c, 373020, 69.92, 0, d1); LocalDate d2 = LocalDate.of(2020, 2, 28); Refueling r2 = new Refueling(c, 373773, 70.13, 0, d2); LocalDate d3 = LocalDate.of(2020, 3, 13); Refueling r3 = new Refueling(c, 374545, 71.61, 0, d3); rm.addRefueling(r1); rm.addRefueling(r2); rm.addRefueling(r3); assertEquals(true, sm.kmsInMonth(c, 4, 2020) == 0); } @Test public void kmsInMonthTest1() { Car c = new Car("Volvo", 80); rm.addCar(c); LocalDate d1 = LocalDate.of(2020, 2, 16); Refueling r1 = new Refueling(c, 373020, 69.92, 0, d1); LocalDate d2 = LocalDate.of(2020, 2, 28); Refueling r2 = new Refueling(c, 373773, 70.13, 0, d2); LocalDate d3 = LocalDate.of(2020, 3, 13); Refueling r3 = new Refueling(c, 374545, 71.61, 0, d3); rm.addRefueling(r1); rm.addRefueling(r2); rm.addRefueling(r3); assertEquals(true, sm.kmsInMonth(c, 2, 2020) == 753); } @Test public void kmsInMonthTest2() { Car c = new Car("Volvo", 80); rm.addCar(c); LocalDate d1 = LocalDate.of(2020, 2, 16); Refueling r1 = new Refueling(c, 373020, 69.92, 0, d1); LocalDate d2 = LocalDate.of(2020, 2, 28); Refueling r2 = new Refueling(c, 373773, 70.13, 0, d2); LocalDate d3 = LocalDate.of(2020, 3, 13); Refueling r3 = new Refueling(c, 374545, 71.61, 0, d3); rm.addRefueling(r1); rm.addRefueling(r2); rm.addRefueling(r3); assertEquals(true, sm.kmsInMonth(c, 3, 2020) == 0); } @Test public void totalKmsWorksCorrectly() { Car c = new Car("Volvo", 80); rm.addCar(c); LocalDate d1 = LocalDate.of(2020, 1, 31); Refueling r1 = new Refueling(c, 372358, 66.63, 0, d1); LocalDate d2 = LocalDate.of(2020, 1, 15); Refueling r2 = new Refueling(c, 371707, 70.23, 0, d2); LocalDate d3 = LocalDate.of(2019, 12, 18); Refueling r3 = new Refueling(c, 371014, 66.53, 0, d3); LocalDate d4 = LocalDate.of(2019, 11, 22); Refueling r4 = new Refueling(c, 370426, 70.59, 0, d4); rm.addRefueling(r1); rm.addRefueling(r2); rm.addRefueling(r3); rm.addRefueling(r4); assertEquals(true, sm.totalKms(c) == 1932); } @Test public void totalKmsReturnsZeroIfNoRefuelings() { Car c = new Car("Volvo", 80); rm.addCar(c); assertEquals(true, sm.totalKms(c) == 0); } @Test public void totalDoubleReturnsCorrectAmount() { Car c1 = new Car("Volvo", 80); Car c2 = new Car("BMW", 70); rm.addCar(c1); rm.addCar(c2); LocalDate d1 = LocalDate.of(2020, 2, 16); Refueling r1 = new Refueling(c1, 373020, 69.92, 0, d1); LocalDate d2 = LocalDate.of(2020, 2, 28); Refueling r2 = new Refueling(c1, 373773, 70.13, 0, d2); LocalDate d3 = LocalDate.of(2020, 3, 13); Refueling r3 = new Refueling(c1, 374545, 71.61, 0, d3); rm.addRefueling(r1); rm.addRefueling(r2); rm.addRefueling(r3); LocalDate d4 = LocalDate.of(2020, 1, 15); Refueling r4 = new Refueling(c2, 371707, 70.23, 0, d4); LocalDate d5 = LocalDate.of(2019, 12, 18); Refueling r5 = new Refueling(c2, 371014, 66.53, 0, d5); LocalDate d6 = LocalDate.of(2019, 11, 22); Refueling r6 = new Refueling(c2, 370426, 70.59, 0, d6); rm.addRefueling(r4); rm.addRefueling(r5); rm.addRefueling(r6); assertEquals(true, sm.totalVolume(c1) == 211.66000000000003); assertEquals(true, sm.totalVolume(c2) == 207.35); } @Test public void totalCostReturnsCorrectAmount() { Car c1 = new Car("Volvo", 80); Car c2 = new Car("BMW", 70); rm.addCar(c1); rm.addCar(c2); LocalDate d1 = LocalDate.of(2020, 2, 16); Refueling r1 = new Refueling(c1, 373020, 69.92, 1.54, d1); LocalDate d2 = LocalDate.of(2020, 2, 28); Refueling r2 = new Refueling(c1, 373773, 70.13, 1.56, d2); LocalDate d3 = LocalDate.of(2020, 3, 13); Refueling r3 = new Refueling(c1, 374545, 71.61, 1.49, d3); rm.addRefueling(r1); rm.addRefueling(r2); rm.addRefueling(r3); LocalDate d4 = LocalDate.of(2020, 1, 15); Refueling r4 = new Refueling(c2, 371707, 70.23, 1.34, d4); LocalDate d5 = LocalDate.of(2019, 12, 18); Refueling r5 = new Refueling(c2, 371014, 66.53, 1.28, d5); LocalDate d6 = LocalDate.of(2019, 11, 22); Refueling r6 = new Refueling(c2, 370426, 70.59, 1.42, d6); rm.addRefueling(r4); rm.addRefueling(r5); rm.addRefueling(r6); assertEquals(true, sm.totalCost(c1) == 323.7785); assertEquals(true, sm.totalCost(c2) == 279.50440000000003); } @Test public void costPerMonthTest() { Car c1 = new Car("Volvo", 80); Car c2 = new Car("BMW", 70); rm.addCar(c1); rm.addCar(c2); LocalDate d1 = LocalDate.of(2020, 2, 16); Refueling r1 = new Refueling(c1, 373020, 69.92, 1.54, d1); LocalDate d2 = LocalDate.of(2020, 2, 28); Refueling r2 = new Refueling(c1, 373773, 70.13, 1.56, d2); LocalDate d3 = LocalDate.of(2020, 3, 13); Refueling r3 = new Refueling(c1, 374545, 71.61, 1.49, d3); rm.addRefueling(r1); rm.addRefueling(r2); rm.addRefueling(r3); LocalDate d4 = LocalDate.of(2020, 1, 15); Refueling r4 = new Refueling(c2, 371707, 70.23, 1.34, d4); LocalDate d5 = LocalDate.of(2019, 12, 18); Refueling r5 = new Refueling(c2, 371014, 66.53, 1.28, d5); LocalDate d6 = LocalDate.of(2019, 11, 22); Refueling r6 = new Refueling(c2, 370426, 70.59, 1.42, d6); rm.addRefueling(r4); rm.addRefueling(r5); rm.addRefueling(r6); assertEquals(true, sm.costPerMonth(c1, 2, 2020) == 217.0796); assertEquals(true, sm.costPerMonth(c2, 12, 2019) == 85.1584); } } <file_sep>/fuel-logger/documentation/working hours.md | day | hours | description | | :----:|:-----| :-----| | 23.3. | 2 | requirements specification, starting the project | | 30.3. | 1 | coding starts, configuring maven project | | 31.3. | 3 | adding a car and the database works, messing with maven and pom | | 6.4. | 3 | adding refuelings to the database and gui for refuelings listing | | 7.4. | 3 | added checkstyle and more tests, refuelings can be added from gui, class diagram | | 18.4. | 2 | added methods to count consumptions + consumption graph | | 20.4. | 2 | added more tests + sequence diagram off adding cars | | 21.4. | 3 | monthly fuel consumption chart, added more tests, release | | 25.4. | 0.5 | fixes, helper methods to logic class | | 28.4. | 4 | monthly cost chart, monthly kilometer chart, javadocs, release | | 6.5. | 0.5 | validations on input dialogs | | 7.5. | 0.5 | more validations on input dialogs, improved appearance | | 8.5. | 2 | config file, separate logic classes, error dialogs | | 9.5 | 2 | more tests, documentation | | 10.5. | 3 | bigfixes, documentations, javadocs, final release | | total | 31.5 | |
8dc4ead023a3627f5cc52718ac2b64e1b75ce721
[ "Markdown", "Java" ]
11
Markdown
Lukxsx/fuel-logger
8f1783a93f8da588d9191c5fa72bafb6bad3654e
bae918b032adedaa138bd655a55bd3d18f1b1fa0
refs/heads/main
<file_sep>import os from flask import Flask, render_template, request, jsonify import chat app = Flask(__name__) @app.route("/predict", methods = ['POST']) def predict(): ans_pdc = sentence = '' if request.method == "POST": sentence = request.form["que"] if sentence != '': ans_pdc = chat.ans_prediction(sentence) data = {'que': sentence, 'prediction': ans_pdc} return jsonify(data) @app.route("/", methods = ['GET', 'POST']) def hello(): ans_pdc = sentence = '' if request.method == "POST": sentence = request.form["que"] if sentence != '': ans_pdc = chat.ans_prediction(sentence) return render_template("index.html", que = sentence, pred = ans_pdc) #if __name__ == "__main__": # app.run(debug=True) if __name__ == '__main__': app.run(debug=True, port=int(os.environ.get('PORT', 5001))) <file_sep>-f https://download.pytorch.org/whl/torch_stable.html certifi==2020.6.20 chardet==3.0.4 click==8.0.1 cycler==0.10.0 Flask==2.0.1 future==0.18.2 gunicorn==20.1.0 idna==2.10 importlib-metadata==4.6.3 itsdangerous==2.0.1 Jinja2==3.0.1 joblib==1.0.1 kiwisolver==1.3.1 MarkupSafe==2.0.1 matplotlib==3.4.2 nltk==3.6.2 numpy==1.21.1 pandas==1.1.5 Pillow==8.3.1 protobuf==3.17.3 pyparsing==2.4.7 PyQt3D==5.15.4 PyQt5==5.15.4 PyQt5-sip==12.9.0 PyQtChart==5.15.4 PyQtDataVisualization==5.15.4 PyQtNetworkAuth==5.15.4 PyQtPurchasing==5.15.4 PyQtWebEngine==5.15.4 python-dateutil==2.8.2 pytz==2021.1 regex==2021.8.3 requests==2.24.0 scikit-learn==0.24.2 scipy==1.7.1 six==1.16.0 sklearn==0.0 threadpoolctl==2.2.0 torch==1.7.1+cpu torchvision==0.8.2+cpu tqdm==4.62.1 typing-extensions==3.10.0.0 urllib3==1.25.10 Werkzeug==2.0.1 zipp==3.5.0 <file_sep>import requests # https://pitorch-flask.herokuapp.com/predict # http://localhost:5000/predict resp = requests.post("http://localhost:5000/predict", data={'que': 'hi'}) print(resp.text)
0b3104ad9cf72f75d61b422afadd632184d7bccc
[ "Python", "Text" ]
3
Python
pravinsapkal/cb
3e2bfdf1b0f63799360b7116d3012837c0be8335
247ba24f5d5165a2e99cba3f0e4cbbdd1b611ae3
refs/heads/master
<repo_name>definename/mysql_samples<file_sep>/CMakeLists.txt cmake_minimum_required(VERSION 3.11.4) project(mysql_samples) list(APPEND CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake") option(BUILD_WITH_MYSQL_CONNECTOR_C616 "Build with mysql connector c version 6.1.6" OFF) option(BUILD_WITH_MYSQL_CONNECTOR_C6111 "Build with mysql connector c version 6.1.11" ON) include(ExternalProject) include(PCHSupport) include(CRTLinkage) # Executable output set(EXECUTABLE_OUTPUT_PATH ${CMAKE_BINARY_DIR}/bin) # External directory set(EXTERNAL_PATH ${CMAKE_SOURCE_DIR}/external) # Patch directory set(PATCH_PATH ${EXTERNAL_PATH}/patches) # External install directory set(EXTERNAL_INSTALL_PATH ${CMAKE_BINARY_DIR}/external) # MYSQL connector C root set(MYSQL_CONNECTOR_ROOT ${EXTERNAL_INSTALL_PATH}/MYSQL_CONNECTOR_C) ############################################################ # This version works up to Visual Studio 2013 ############## if(BUILD_WITH_MYSQL_CONNECTOR_C616) ExternalProject_Add( mysql_connector_c URL "${EXTERNAL_PATH}/mysql-connector-c-6.1.6.zip" URL_MD5 4A380EB34990DD0E1D5AE16AF71D2D54 CMAKE_ARGS -DCMAKE_INSTALL_PREFIX:PATH=${MYSQL_CONNECTOR_ROOT} ) endif() ############################################################ # This version works since Visual Studio 2017 ############## if(BUILD_WITH_MYSQL_CONNECTOR_C6111) ExternalProject_Add( mysql_connector_c URL "${EXTERNAL_PATH}/mysql-connector-c-6.1.11.zip" URL_MD5 62de01beffc48348708c983a585b4dc1 CMAKE_ARGS -DCMAKE_INSTALL_PREFIX:PATH=${MYSQL_CONNECTOR_ROOT} ) endif() set(MYSQL_INCLUDE_DIR ${MYSQL_CONNECTOR_ROOT}/include) set(MYSQL_LIBRARIES ${MYSQL_CONNECTOR_ROOT}/lib/libmysql.lib) set(MYSQL_BINARY_FILENAME libmysql.dll) set(MYSQL_BINARIES ${MYSQL_CONNECTOR_ROOT}/lib/${MYSQL_BINARY_FILENAME}) SET_PROPERTY(GLOBAL PROPERTY USE_FOLDERS ON) SET_PROPERTY(TARGET mysql_connector_c PROPERTY FOLDER "External") add_subdirectory(modules/mysql_test)<file_sep>/README.md # MySql Connect to mysql: `mysql -u db_user -p123456` Create table: ``` create table manufacturer( id serial, name varchar(255) not null, primary key(id)) engine innodb character set utf8; ``` Create table with foreign key: ``` create table component( id serial, name varchar(255) not null, manufacturer_id bigint unsigned not null, primary key(id), foreign key(manufacturer_id) references manufacturer(id) on delete restrict on update cascade) engine innodb character set utf8; ``` Dump database with all data: ``` mysqldump -h localhost -u db_user -p123456 tprs_master > trps_master_data.sql ``` Dump database with no data: ``` mysqldump -d -h localhost -u db_user -p123456 tprs_master > trps_master_no_data.sql ``` Load database: ``` mysql -h localhost -u db_user -p123456 trps_master < trps_master_no_data.sql ``` <file_sep>/trps_master/trps_master_data.sql -- MySQL dump 10.13 Distrib 5.7.28, for Win64 (x86_64) -- -- Host: localhost Database: tprs_master -- ------------------------------------------------------ -- Server version 5.7.28-log /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; /*!40103 SET TIME_ZONE='+00:00' */; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; -- -- Table structure for table `component` -- DROP TABLE IF EXISTS `component`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `component` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(255) NOT NULL, `manufacturer_id` bigint(20) unsigned NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `id` (`id`), KEY `manufacturer_id` (`manufacturer_id`), CONSTRAINT `component_ibfk_1` FOREIGN KEY (`manufacturer_id`) REFERENCES `manufacturer` (`id`) ON UPDATE CASCADE ) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `component` -- LOCK TABLES `component` WRITE; /*!40000 ALTER TABLE `component` DISABLE KEYS */; INSERT INTO `component` VALUES (1,'processor_intel',10),(2,'processor_amd',20),(4,'chipset_intel',10),(5,'chipset_amd',20),(6,'motherboard_intel',10),(7,'motherboard_amd',20); /*!40000 ALTER TABLE `component` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `manufacturer` -- DROP TABLE IF EXISTS `manufacturer`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `manufacturer` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(255) NOT NULL, `rating` tinyint(3) unsigned NOT NULL DEFAULT '0', `description` varchar(255) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `id` (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=21 DEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `manufacturer` -- LOCK TABLES `manufacturer` WRITE; /*!40000 ALTER TABLE `manufacturer` DISABLE KEYS */; INSERT INTO `manufacturer` VALUES (10,'intel',100,'Intel Corporation'),(20,'amd',100,'Advanced Micro Devices'); /*!40000 ALTER TABLE `manufacturer` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `product` -- DROP TABLE IF EXISTS `product`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `product` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(255) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `id` (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=301 DEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `product` -- LOCK TABLES `product` WRITE; /*!40000 ALTER TABLE `product` DISABLE KEYS */; INSERT INTO `product` VALUES (100,'super_computer1'),(200,'super_computer2'),(300,'super_computer3'); /*!40000 ALTER TABLE `product` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `product_component` -- DROP TABLE IF EXISTS `product_component`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `product_component` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `product_id` bigint(20) unsigned NOT NULL, `component_id` bigint(20) unsigned NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `id` (`id`), KEY `product_id` (`product_id`), KEY `component_id` (`component_id`), CONSTRAINT `product_component_ibfk_1` FOREIGN KEY (`product_id`) REFERENCES `product` (`id`) ON UPDATE CASCADE, CONSTRAINT `product_component_ibfk_2` FOREIGN KEY (`component_id`) REFERENCES `component` (`id`) ON UPDATE CASCADE ) ENGINE=InnoDB AUTO_INCREMENT=120 DEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `product_component` -- LOCK TABLES `product_component` WRITE; /*!40000 ALTER TABLE `product_component` DISABLE KEYS */; INSERT INTO `product_component` VALUES (111,100,1),(112,100,4),(113,100,6),(114,200,1),(115,200,4),(116,200,7),(117,300,2),(118,300,5),(119,300,6); /*!40000 ALTER TABLE `product_component` ENABLE KEYS */; UNLOCK TABLES; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; -- Dump completed on 2020-01-02 14:32:40 <file_sep>/trps_master/olehk13_2.sql /* Збільшити рейтинг постачальника, що виконав більше число постачань, на вказану величину: */ update manufacturer as UP_RATING, (select manufacturer.id as MAN_ID, count(manufacturer.id) as MAN_COUNT from product_component, component, manufacturer where product_component.component_id = component.id and component.manufacturer_id = manufacturer.id group by manufacturer.id having MAN_COUNT = (select MAX(A.MAN_COUNT) from (select manufacturer.id, count(manufacturer.id) as MAN_COUNT from product_component, component, manufacturer where product_component.component_id = component.id and component.manufacturer_id = manufacturer.id group by manufacturer.id ) as A ) ) as B set UP_RATING.rating = 100 where UP_RATING.id = B.MAN_ID;<file_sep>/trps_master/olehk13_1.sql /* Вивести інформацію про постачальників, які здійснювали постачання деталей для вказаного виробу */ select manufacturer.name, manufacturer.description, manufacturer.rating from product_component, component, manufacturer where product_id in (select id from product where name = "super_computer2") and component.id = component_id and manufacturer.id = manufacturer_id;<file_sep>/trps_master/trps_master_no_data.sql -- MySQL dump 10.13 Distrib 5.7.28, for Win64 (x86_64) -- -- Host: localhost Database: tprs_master -- ------------------------------------------------------ -- Server version 5.7.28-log /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; /*!40103 SET TIME_ZONE='+00:00' */; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; -- -- Table structure for table `component` -- DROP TABLE IF EXISTS `component`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `component` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(255) NOT NULL, `manufacturer_id` bigint(20) unsigned NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `id` (`id`), KEY `manufacturer_id` (`manufacturer_id`), CONSTRAINT `component_ibfk_1` FOREIGN KEY (`manufacturer_id`) REFERENCES `manufacturer` (`id`) ON UPDATE CASCADE ) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `manufacturer` -- DROP TABLE IF EXISTS `manufacturer`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `manufacturer` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(255) NOT NULL, `rating` tinyint(3) unsigned NOT NULL DEFAULT '0', `description` varchar(255) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `id` (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=21 DEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `product` -- DROP TABLE IF EXISTS `product`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `product` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(255) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `id` (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=301 DEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `product_component` -- DROP TABLE IF EXISTS `product_component`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `product_component` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `product_id` bigint(20) unsigned NOT NULL, `component_id` bigint(20) unsigned NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `id` (`id`), KEY `product_id` (`product_id`), KEY `component_id` (`component_id`), CONSTRAINT `product_component_ibfk_1` FOREIGN KEY (`product_id`) REFERENCES `product` (`id`) ON UPDATE CASCADE, CONSTRAINT `product_component_ibfk_2` FOREIGN KEY (`component_id`) REFERENCES `component` (`id`) ON UPDATE CASCADE ) ENGINE=InnoDB AUTO_INCREMENT=120 DEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; -- Dump completed on 2020-01-02 14:33:03
47563e07f5aed276e7011478401bee2b3d431339
[ "Markdown", "SQL", "CMake" ]
6
CMake
definename/mysql_samples
62bf27ecc974895d47ac56d53bb9ad4dbf4fbe30
75e2f0a753a1426a2a7e254867d2e4546e9b0011
refs/heads/master
<file_sep>function tasks(parent, args, context, info) { return context.prisma.tasks() } function users(parent, args, context, info) { return context.prisma.users() } function task(parent, args, context, info) { return context.prisma.task({id: args.id}); } module.exports = { tasks, users, task }<file_sep>function createdBy(parent, args, context) { return context.prisma.task({ id: parent.id }).createdBy() } function todos(parent, args, context) { return context.prisma.task({ id: parent.id }).todos() } module.exports = { createdBy, todos, }<file_sep>function newTaskSubscribe(parent, args, context, info) { return context.prisma.$subscribe.task({ mutation_in: ['CREATED'] }).node() } const newTask = { subscribe: newTaskSubscribe, resolve: payload => { return payload }, } function newTodoSubscribe(parent, args, context, info) { return context.prisma.$subscribe.todo({ mutation_in: ['CREATED'] }).node() } const newTodo = { subscribe: newTodoSubscribe, resolve: payload => { return payload }, } module.exports = { newTask, newTodo, }
25f7a6f00166752ee16685a9aef2600b1d8b1562
[ "JavaScript" ]
3
JavaScript
mcqua007/graphql-hackernews-api
cd729b4153f4a71d380aa111fa74f2d6c4c1a8c0
d9128701269785ce102027b161c1573e43fd11f4
refs/heads/master
<repo_name>zshamrock/dot-files<file_sep>/.bash_aliases #alias e='emacsclient -t' #alias ec='emacsclient -c' #alias vim='emacsclient -t' #alias vi='emacsclient -t' alias groovy=groovyclient alias grep='grep --color' <file_sep>/README.md Share all my sync files (actually, maybe it can be done through the dropbox, will see). Provide the script to setup the whole (ideally fresh new OS) with all the configurations I got used to. The following vim plugins are not provided from github (or there are very old versions), so need to download it manually from sourceforge, for example. Of course, even this can be automated, just need to put my hands into it: - taglist.vim [http://sourceforge.net/projects/vim-taglist/files/] (ctags is required, see below) - ctags [http://ctags.sourceforge.net/] (need to build it manually) <file_sep>/.gradle/gradle.properties org.gradle.daemon=true org.gradle.jvmargs=-XX:MetaspaceSize=512m -Xmx512m -Dfile.encoding=UTF-8 <file_sep>/.profile # ~/.profile: executed by the command interpreter for login shells. # This file is not read by bash(1), if ~/.bash_profile or ~/.bash_login # exists. # see /usr/share/doc/bash/examples/startup-files for examples. # the files are located in the bash-doc package. # the default umask is set in /etc/profile; for setting the umask # for ssh logins, install and configure the libpam-umask package. #umask 022 # if running bash if [ -n "$BASH_VERSION" ]; then # include .bashrc if it exists if [ -f "$HOME/.bashrc" ]; then . "$HOME/.bashrc" fi fi #disable console beep #setterm --blength 0 #~/bin/disable-touchpad-if-logitech-mouse-is-connected.sh ~/bin/cpufreq-setup.sh # set PATH so it includes user's private bin if it exists if [ -d "$HOME/bin" ] ; then PATH="$HOME/bin:$HOME/bin/dev:$PATH" fi #export _JAVA_OPTIONS="-Dawt.useSystemAAFontSettings=on -Dswing.aatext=true" JAVA7_HOME=/usr/lib/jvm/jdk1.7.0_71 JAVA8_HOME=/usr/lib/jvm/jdk1.8.0_25 java_version=`java -version 2>&1 | head -n 1 | awk -F '"' '{print $2}'` echo "Using Java version ${java_version}" export JAVA_HOME=/usr/lib/jvm/jdk${java_version} JRE_HOME=$JAVA_HOME/jre export JRE_HOME # clojure export CLOJURE_HOME=$HOME/tools/clojure/clojure-1.7.0 export CLOJURE_JAR=$CLOJURE_HOME/clojure-1.7.0.jar ASPECTJ_HOME="$HOME/tools/aspectj/aspectj-1.7" export ASPECTJ_HOME CLASSPATH="${ASPECTJ_HOME}/lib/aspectjrt.jar:${CLOJURE_JAR}:." export CLASSPATH M2_HOME=$HOME/tools/apache-maven-3.0.4 export M2_HOME VWS_HOME=$HOME/programming/virgo/virgo-web-server-2.1.1.RELEASE LUCENE_HOME=$HOME/tools/lucene/3.6.1 FORGE_HOME=$HOME/tools/jboss-forge/jboss-forge-1.1.1.Final export LUCENE_HOME export VWS_HOME export P4CONFIG=.p4config export OPENWAVE_HOME=$HOME/openwave export P4V_HOME=$HOME/tools/p4v export NODE_PATH=/usr/local/lib/node:/usr/local/lib/node_modules export MAVEN_OPTS="-Xms128M -Xmx256M -XX:MaxPermSize=256m" #export VIRTUALENV_DISTRIBUTE=true # configure perl5 to add path into @INC while searching for modules and documentation export PERL5LIB=$HOME/perl5/lib/perl5 # configure perlbrew source $HOME/perl5/perlbrew/etc/bashrc export GOPATH=$HOME/go export GOLANG_HOME=/usr/local/go export PATH="$PATH:$JAVA_HOME/bin:/usr/local/bin:/usr/share/doc/git-core/contrib/fast-import:/usr/sbin:$P4V_HOME/bin:/var/lib/gems/1.8/bin:$HOME/tools/play2:/usr/local/Trolltech/Qt-4.8.2/bin:$FORGE_HOME/bin:/usr/local/bin/mongo:$ASPECTJ_HOME/bin:$GOLANG_HOME/bin:$GOPATH/bin" export PYTHONSTARTUP=$HOME/.pythonstartup # python virtualenvwrapper #export PROJECT_HOME=$HOME/dev/sandbox/python #export WORKON_HOME=$HOME/.virtualenvs #export VIRTUALENVWRAPPER_VIRTUALENV_ARGS='--system-site-packages' #source /usr/local/bin/virtualenvwrapper.sh #THIS MUST BE AT THE END OF THE FILE FOR GVM TO WORK!!! [[ -s "/home/alex/.gvm/bin/gvm-init.sh" ]] && source "/home/alex/.gvm/bin/gvm-init.sh" <file_sep>/grab-git-remote-vim-plugins.sh #!/bin/bash PLUGINS_DIR=${HOME}/.vim/bundle cwd=`pwd` cd ${PLUGINS_DIR} plugins=(`ls -1 ${PLUGINS_DIR}`) for plugin in "${plugins[@]}" do cd ${plugin} if [ -d .git ] then repo=`git remote -v | grep "fetch" | cut -f 2 | cut -f 1 -d ' '` plugin_path=`echo ${repo} | cut -f 4,5 -d / | sed -e "s/\.git//"` echo "${plugin_path}" >> ${cwd}/vim-plugins.txt fi cd .. done cd ${cwd} # remove duplicate lines (-u unique) sort -u vim-plugins.txt -o vim-plugins.txt <file_sep>/setup.sh #!/bin/bash HOME_DOT_FILES=(".vimrc" ".bash_aliases") PWD=`pwd` setup_symlinks() { for f in "${HOME_DOT_FILES[@]}" do file_full_path="$HOME/${f}" if [ ! -f "${file_full_path}" ] then echo "Making a symlink for '${f}'" `ln -s "${PWD}/${f}" "${file_full_path}"` else echo "Skipping ${f}, because it already exists." fi done } setup_all() { setup_symlinks } setup_all
bf9d76bbc777edcc32ac073509b9ca27f864a508
[ "Markdown", "INI", "Shell" ]
6
Shell
zshamrock/dot-files
f00cb31c762a682d06a0a6a9d5ee36d6ef2bfd4e
28edf3e7c327acccdb53d45c582a9792cb71c4cb
refs/heads/master
<file_sep># read-more-react <file_sep>var ReadmoreText = React.createClass({ getInitialState: function () { var string =this.props.text; var limit = 50; var limit_crossed = false; if (string.length > limit) { limit_crossed = true; } else { limit_crossed = false; } return ({ limit_crossed: limit_crossed, flip: true, display_text: string.substring(0, limit), original_text: string, text: string.substring(0, limit), read_text: " --Read more" }); }, readmore: function () { this.setState({flip: !this.state.flip}, function () { this.setState({ display_text: this.state.flip ? this.state.text : this.state.original_text, read_text: this.state.flip ? " ---Read more" : " ---Read less" }); }); }, render: function () { if (this.state.limit_crossed) { return (<div>{this.state.display_text}<a onClick={this.readmore}>{this.state.read_text}</a></div>) } else { return (<div>{this.state.text}</div>) } } }); window.ReadmoreText=ReadmoreText
ce296f64e4a4bd22b3332e180f3f77da1f1dd37f
[ "Markdown", "JavaScript" ]
2
Markdown
Javasamurai/read-more-react
bd8a9436fd7cf8a0ad91e636eecbc0ec869b2572
dd4e9fb70b3a553c68789593647b66731ccdde72
refs/heads/main
<repo_name>nand-nor/yabts<file_sep>/src/message.rs use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Debug, Copy, Clone)] pub struct MessageHeader { magic: u32, length: u16, code: u16, } impl MessageHeader { pub fn new(length: u16, code: u16) -> MessageHeader { MessageHeader { magic: super::MAGIC, length: length, code: code, } } pub fn default() -> MessageHeader { MessageHeader { magic: super::MAGIC, length: 0, code: 0, } } pub fn set(&mut self, length: u16, code: u16) { self.length = length; self.code = code; } pub fn get(&self) -> (u16, u16) { (self.length, self.code) } pub fn code(&self) -> u16 { self.code } pub fn is_valid(&self) -> bool { self.magic == super::MAGIC } } #[derive(Serialize, Deserialize, Debug)] pub struct Message { header: MessageHeader, payload: Vec<u8>, } impl Message { pub fn default() -> Message { Message { header: MessageHeader::default(), payload: Vec::new(), } } pub fn new(length: u16, code: u16, payload: Option<Vec<u8>>) -> Message { let mut message = Message::default(); message.set_header(length, code); if let Some(payload) = payload { message.set_payload(payload); } message } pub fn payload_len(&self) -> usize { return self.payload.len(); } pub fn get_payload(&self) -> Option<Vec<u8>> { if self.payload.len() != 0 { Some(self.payload.clone()) } else { None } } pub fn get_header(&self) -> MessageHeader { self.header } fn set_payload(&mut self, payload: Vec<u8>) { self.payload = payload.clone() } fn set_header(&mut self, length: u16, code: u16) { self.header.set(length, code); } } <file_sep>/src/stats.rs pub struct ServerStats { bytes_sent: u64, //all bytes sent, including headers bytes_received: u64, //all bytes received, including headers compress_sent: u64, //all -valid- bytes sent (excludes invalid compression requests) compress_rcv: u64, //all -valid- bytes received (excludes invalid compression requests) decompress_sent: u64, //all -valid- bytes sent (excludes invalid decompression requests) decompress_rcv: u64, //all -valid- bytes received (excludes invalid decompression requests) compression_ratio: u8, //ratio of all uncompressed bytes (excluding headers) received versus compressed size //space_saving: u8, // 1 - uncompressed/compressed decompression_ratio: u8, //ratio of all uncompressed bytes (excluding headers) received versus compressed size encode_ratio: u8, decode_ratio: u8, encode_sent: u64, encode_rcv: u64, decode_sent: u64, decode_rcv: u64, } impl ServerStats { pub fn new() -> ServerStats { ServerStats { bytes_sent: 0, bytes_received: 0, compress_sent: 0, compress_rcv: 0, compression_ratio: 0, decompress_sent: 0, decompress_rcv: 0, decompression_ratio: 0, encode_sent: 0, encode_rcv: 0, encode_ratio: 0, decode_sent: 0, decode_rcv: 0, decode_ratio: 0, } } pub fn get_stats(&self) -> (u64, u64, u8, u8, u8, u8) { ( self.bytes_sent, self.bytes_received, self.compression_ratio, self.decompression_ratio, self.encode_ratio, self.decode_ratio, ) } //ensure safe addition-- if overflow will occur, do wrapping add pub fn add_compression_data(&mut self, rcv: u64, sent: u64) { if self.compress_sent.checked_add(sent).is_some() { self.compress_sent += sent; } else { self.compress_sent = self.compress_sent.wrapping_add(sent); } //ensure no overflow -- check add and if not safe then wrapping add if self.compress_rcv.checked_add(rcv).is_some() { self.compress_rcv += rcv; } else { self.compress_rcv = self.compress_rcv.wrapping_add(rcv); } //only update this when we compress data //ensure safe division & safe multiplication if self.compress_rcv.checked_div(self.compress_sent).is_some() { self.compression_ratio = ((self.compress_rcv as f64 / self.compress_sent as f64) * 100 as f64) as u8; } else { //retain the old ratio } } //ensure safe addition-- if overflow will occur, do wrapping add pub fn add_decompression_data(&mut self, rcv: u64, sent: u64) { if self.decompress_sent.checked_add(sent).is_some() { self.decompress_sent += sent; } else { self.decompress_sent = self.decompress_sent.wrapping_add(sent); } //ensure no overflow -- check add and if not safe then wrapping add if self.decompress_rcv.checked_add(rcv).is_some() { self.decompress_rcv += rcv; } else { self.decompress_rcv = self.decompress_rcv.wrapping_add(rcv); } //only update this when we compress data //ensure safe division & safe multiplication if self .decompress_rcv .checked_div(self.decompress_sent) .is_some() { self.decompression_ratio = ((self.decompress_rcv as f64 / self.decompress_sent as f64) * 100 as f64) as u8; } else { //retain the old ratio } } //ensure safe addition-- if overflow will occur, do wrapping add pub fn add_decode_data(&mut self, rcv: u64, sent: u64) { if self.decode_sent.checked_add(sent).is_some() { self.decode_sent += sent; } else { self.decode_sent = self.decode_sent.wrapping_add(sent); } //ensure no overflow -- check add and if not safe then wrapping add if self.decode_rcv.checked_add(rcv).is_some() { self.decode_rcv += rcv; } else { self.decode_rcv = self.decode_rcv.wrapping_add(rcv); } //only update this when we compress data //ensure safe division & safe multiplication if self.decode_rcv.checked_div(self.decode_sent).is_some() { self.decode_ratio = ((self.decode_rcv as f64 / self.decode_sent as f64) * 100 as f64) as u8; } else { //retain the old ratio } } //ensure safe addition-- if overflow will occur, do wrapping add pub fn add_encode_data(&mut self, rcv: u64, sent: u64) { if self.encode_sent.checked_add(sent).is_some() { self.encode_sent += sent; } else { self.encode_sent = self.encode_sent.wrapping_add(sent); } //ensure no overflow -- check add and if not safe then wrapping add if self.encode_rcv.checked_add(rcv).is_some() { self.encode_rcv += rcv; } else { self.encode_rcv = self.encode_rcv.wrapping_add(rcv); } //only update this when we compress data //ensure safe division & safe multiplication if self.encode_rcv.checked_div(self.encode_sent).is_some() { self.encode_ratio = ((self.encode_rcv as f64 / self.encode_sent as f64) * 100 as f64) as u8; } else { //retain the old ratio } } //reset stats pub fn reset_stats(&mut self) { self.bytes_sent = 0; self.bytes_received = 0; self.compress_rcv = 0; self.compress_sent = 0; self.compression_ratio = 0; self.decompress_rcv = 0; self.decompress_sent = 0; self.decompression_ratio = 0; self.encode_rcv = 0; self.encode_sent = 0; self.encode_ratio = 0; self.decode_rcv = 0; self.decode_sent = 0; self.decode_ratio = 0; } //safely update the server's inner stats pub fn update_stats(&mut self, update_sent: u64, update_recv: u64) { //ensure no overflow -- check add and if not safe then wrapping add if self.bytes_sent.checked_add(update_sent).is_some() { self.bytes_sent += update_sent; } else { self.bytes_sent = self.bytes_sent.wrapping_add(update_sent); } //ensure no overflow -- check add and if not safe then wrapping add if self.bytes_received.checked_add(update_recv).is_some() { self.bytes_received += update_recv; } else { self.bytes_received = self.bytes_received.wrapping_add(update_recv); } } } <file_sep>/README.md # YABTS: Yet Another Byte Transformation Service # This crate provides a simple data transformation service and includes a library and trait definitions for user-extensibility. It provides both server and client modes for a socket-based (currently TCP) mechanism to transform data in both directions (e.g. compression on server end, decompression on client end). The data transformation provided by this service is intended to be easily extended by a user, but includes some basic algorithms. This transformation is in addition to the byte serialization/ deserialization needed for sending data via network socket. A data payload, provided via `stdin` or file, is transformed according to the user-specified trait implementation via a series of generic functions for encoding/decoding, compressing/decompressing, etc., and then further transformed to handle byte marshalling across sockets. The `examples` dir contains examples of already-implemented data transforms, specifically compression/ decompression and encoding/decoding implementations of: – Base 64 – COBS (Consistent Overhead Byte Stuffing) – "Simple" compression scheme for a trivial compression/decompression (see example) – Using 3rd party crate for Snappy algorithm implementation (WIP) – Possibly others, TBD ### Why do? ### Great question. I initially wrote this for an interview code assignment asking for a TCP-based compression service with a lot of "hidden gotchas" requirements. So a lot of the initial structure is based on the specification document. I have since begun to build up more functionality and turn it into something new for the following reasons: - I enjoyed the overall concept as something that exercises multiple skillsets (algorithms, networks, etc.) - I wanted to showcase some of the more interesting features of Rust (such as dynamic trait objects). - Most of all I wanted to implement more interesting and complex encoding and compression algorithms and this is a very easy vessel to do so. As such this is a work in progress and mainly exists for my own edification. Also, all company-specific details (e.g. solutions) have been obscured per request. ## Target Platform // Development Environment ## Development environment is Ubuntu 18.04.3 LTS. It is written in Rust using the as-of-this-writing latest stable toolchain e.g. rustc 1.48.0 (7eac88abb 2020-11-16). ## Description ## The service uses a simple client-server design pattern: it is a single threaded TCP server that responds to the various requests as listed in the initial spec. The crate is composed of a library and a series of example binaries which can run in either client or server mode. ``` pub fn display_useage() { println!( "Useage:{} [-p <port>] [-a <address>] [-m <runmode>] [-r <request>] [-f <file name>]\n\ -p : \tspecify port for server (default is 4000)\n\ -a : \tspecify address for server(default is 127.0.0.1)\n\ -m : \tuse 'client' for client mode, 'server' for server mode. \n\ -r : \tfor client mode only, specify request using one of: encode/decode/compress/decompress\n\ -f : \tfor client mode only, optional file name for byte transform request\n\ \nIf no args provided, will default to run in server mode on 127.0.0.1:4000", env::args().nth(0).unwrap() ); } ``` ## 3rd Party Libraries ## For this service I have used the `serde` and `bincode` libraries, which together perform serialization and deserialization of bytes sent over the TCP socket. From `bincode`'s documentation: "A compact encoder / decoder pair that uses a binary zero-fluff encoding scheme" This handles encoding and decoding network byte order. Also used is the `argparse` crate for commandline option parsing<file_sep>/src/server.rs use bincode; use std::io::prelude::*; use std::io::Write; use std::net::{IpAddr, Ipv4Addr, SocketAddr, TcpListener, TcpStream}; use std::str::FromStr; use crate::message::*; use crate::stats::*; use crate::transform::*; use super::MAX_MSG_LEN; use super::MAX_PAYLOAD_LEN; pub struct Server { addr: Ipv4Addr, port: u16, stats: ServerStats, error_state: Option<u16>, method: Box<dyn Transform>, } impl Server { pub fn new<B: 'static + Transform>( method: B, addr: String, _port: String, ) -> Result<Server, u16> { let ip = Ipv4Addr::from_str(&addr); let port = u16::from_str_radix(&_port, 10); if ip.is_err() { println!("\nSERVER: Invalid server address provided"); return Err(super::EINVAL); } if port.is_err() { println!("\nSERVER: Invalid server port provided"); return Err(super::EINVAL); } Ok(Server { addr: ip.unwrap(), port: port.unwrap(), stats: ServerStats::new(), error_state: None, method: Box::new(method), }) } pub fn listen(&mut self) -> u16 { let socket = SocketAddr::new( IpAddr::V4(self.addr), //ip.unwrap()), self.port, //u16::from_str_radix(&port, 10).unwrap(), ); let bind = TcpListener::bind(&socket); if bind.is_err() { println!("\nSERVER: Cannot bind! Exiting"); return super::UNKNOWN; } let listener = bind.unwrap(); for stream in listener.incoming() { match stream { Ok(stream) => { self.handle_client(stream); } Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock || e.kind() == std::io::ErrorKind::BrokenPipe => { //just move on, someday implement something nicer here continue; } Err(e) => { //Return to main as this is an unrecoverable state println!("\nSERVER: Encountered error {:?}, exiting", e); return super::UNKNOWN; } } } 0 } //get stats does not include the bytes that are about to be generated & sent in //response to the message fn get_stats(&self) -> (u64, u64, u8, u8, u8, u8) { return self.stats.get_stats(); } //reset all internal stats to 0 fn reset_stats(&mut self) -> Message { self.stats.reset_stats(); Message::new(0, super::OK, None) } fn update_stats(&mut self, update_sent: u64, update_recv: u64) { self.stats.update_stats(update_sent, update_recv) } ///TODO need to fix this-- three copies of the same damn vec is bad fn transform_payload(&mut self, direction: bool, mut payload: Vec<u8>) -> Result<Vec<u8>, ()> { let cp: Vec<u8>; // = Vec::new(); match self.method.transform(direction, &mut payload) { Ok(()) => { cp = payload.clone(); Ok(cp.clone()) } Err(t) => { //TODO set internal error state? println!("SERVER: Encountered error transforming bytes: {:?}", t); Err(()) } } } fn generate_encode(&mut self, payload: Vec<u8>) -> Message { let old_len = payload.len(); let encode = self.transform_payload(true, payload); if encode.is_err() { //internal error occurred return self.generate_msg(super::OTHER_ERROR, None); } let msg = encode.unwrap(); self.stats.add_encode_data(msg.len() as u64, old_len as u64); Message::new(msg.len() as u16, 0, Some(msg.clone())) } fn generate_decode(&mut self, payload: Vec<u8>) -> Message { let old_len = payload.len(); let decode = self.transform_payload(false, payload); if decode.is_err() { //internal error occurred return self.generate_msg(super::OTHER_ERROR, None); } let msg = decode.unwrap(); self.stats.add_decode_data(msg.len() as u64, old_len as u64); Message::new(msg.len() as u16, 0, Some(msg.clone())) } fn generate_compression(&mut self, payload: Vec<u8>) -> Message { let old_len = payload.len(); let compressed = self.transform_payload(true, payload); if compressed.is_err() { //internal error occurred return self.generate_msg(super::OTHER_ERROR, None); } let msg = compressed.unwrap(); self.stats .add_compression_data(msg.len() as u64, old_len as u64); Message::new(msg.len() as u16, 0, Some(msg.clone())) } fn generate_decompression(&mut self, payload: Vec<u8>) -> Message { let old_len = payload.len(); let decompressed = self.transform_payload(false, payload); if decompressed.is_err() { //internal error occurred return self.generate_msg(super::OTHER_ERROR, None); } let msg = decompressed.unwrap(); self.stats .add_decompression_data(msg.len() as u64, old_len as u64); Message::new(msg.len() as u16, 0, Some(msg.clone())) } //Generate a statistics message by deserializing the two u64's into //big endiann bytes, pushing all bytes including the u8 ratio byte //into a vector of 20 u8's. This then gets populated as a message //payload fn generate_stats(&mut self) -> Message { //}, usize) { let (sent, rcv, cratio, dratio, eratio, deratio) = self.get_stats(); let mut sent_bytes = sent.to_ne_bytes().to_vec(); let mut rcv_bytes = rcv.to_ne_bytes().to_vec(); let mut payload: Vec<u8> = Vec::new(); payload.append(&mut sent_bytes); payload.append(&mut rcv_bytes); payload.push(cratio); payload.push(dratio); payload.push(eratio); payload.push(deratio); let len = payload.len(); Message::new(len as u16, super::OK, Some(payload)) } /// Return the requested generated message /// This function will only ever be called to generate an error message /// Or a message with a payload, so we know that if payload == None then /// we are creating an error message fn generate_msg(&mut self, mtype: u16, payload: Option<Vec<u8>>) -> Message { if let Some(payload) = payload { match mtype { x if x == super::REQUEST::COMPRESS as u16 => self.generate_compression(payload), x if x == super::REQUEST::DECOMPRESS as u16 => self.generate_decompression(payload), x if x == super::REQUEST::ENCODE as u16 => self.generate_encode(payload), x if x == super::REQUEST::DECODE as u16 => self.generate_decode(payload), _ => Message::new(0, super::ENOSUP, None), } } else { Message::new(0, mtype, None) } } fn get_request(&mut self, mut stream: &TcpStream) -> Result<Message, Message> { if let Some(state) = self.error_state { return Err(self.generate_msg(state, None)); } let mut bytes: [u8; std::mem::size_of::<MessageHeader>()] = [0; std::mem::size_of::<MessageHeader>()]; let mut full_bytes = [0u8; MAX_MSG_LEN]; let payload; // = None; let mut bytes_rcv = std::mem::size_of::<MessageHeader>(); let res = match stream.peek(&mut bytes) { Ok(_t) => bincode::deserialize(&bytes), Err(e) => { println!("\nSERVER: Failure to read stream-- error: {:?}", e); return Err(self.generate_msg(super::EINVAL, None)); } }; let header: MessageHeader; let (len, request) = match res { Ok(_t) => { header = res.unwrap(); match header.is_valid() { true => header.get(), false => { println!("\nSERVER: Failure to parse correct message header"); return Err(self.generate_msg(super::EINVAL, None)); } } } Err(e) => { println!("\nSERVER: Failure to deserialize sent bytes: {:?}", e); return Err(self.generate_msg(super::EINVAL, None)); } }; if len as usize > MAX_PAYLOAD_LEN { println!("\nSERVER: Invalid length, returning error"); return Err(self.generate_msg(super::EINVAL, None)); } let full: Result<Message, bincode::Error> = match stream.read(&mut full_bytes) { Ok(_t) => bincode::deserialize(&full_bytes), Err(e) => { println!("\nSERVER: Failure to read stream-- drop connection {:?}", e); return Err(self.generate_msg(super::INTERNAL_ERROR, None)); } }; let deserialized_msg: Message; match full { Ok(t) => { deserialized_msg = t; //full.unwrap(); if let Some(msg_payload) = deserialized_msg.get_payload() { if len as usize == msg_payload.len() { payload = Some(msg_payload); bytes_rcv += len as usize; self.stats.update_stats(0, bytes_rcv as u64); //TODO determine if this is needed? Can I just use the // deserialized message, or will that mess with ownership? Ok(Message::new(len, request, payload)) } else { println!("\nSERVER: length is not correctly reported, returning error"); //TODO determine is errorneous bytes e.g. // non-transformed bytes should be stored bytes_rcv += msg_payload.len(); self.stats.update_stats(0, bytes_rcv as u64); Err(self.generate_msg(super::EINVAL, None)) } } else { Err(self.generate_msg(super::EINVAL, None)) } } Err(e) => { println!( "\nSERVER: Unable to deserialize message request, Error {:?}", e ); //invalid message structure parsed Err(self.generate_msg(super::EINVAL, None)) } } } fn process(&mut self, msg: Message) -> Message { match msg.get_header().code() { x if x == super::REQUEST::PING as u16 => Message::new(0, super::OK, None), x if x == super::REQUEST::GET as u16 => self.generate_stats(), x if x == super::REQUEST::RESET as u16 => self.reset_stats(), request => self.generate_msg(request, msg.get_payload()), } } //This function handles reading bytes in from a TCP stream, serializing, //parsing a request, then processing an appropriate response and writing //back to the stream. The mutability of a stream object prevents this //from being more easily modularized, need to look into this further fn handle_client(&mut self, mut stream: TcpStream) { let response = match self.get_request(&stream) { Ok(r) => self.process(r), Err(r) => r, }; match bincode::serialize(&response) { Ok(mut t) => { match stream.write(&mut t) { Ok(t) => { let send_len = t - std::mem::size_of::<MessageHeader>(); //Note: if reset request was made, this will add 8 bytes to each self.update_stats(send_len as u64, 0); } Err(e) => { println!("\nSERVER: Failure to write stream: {:?}", e); //TODO Set internal error state // Err(e) } } } Err(e) => { println!("\nSERVER: Failure to serialize response bytes: {:?}", e); //TODO convert from Box<bincode::ErrorKInd> to std::io::ErrorKind //set internal error state! // return Err(std::io::Error::new(std::io::ErrorKind::Other, "Bincode error")) } } } } <file_sep>/Makefile CARGO = cargo +stable all: client_test server unit_test release examples tests server: $(CARGO) build client_test: $(CARGO) build --features="client" unit_test: $(CARGO) build --features="test" release: $(CARGO) build --release #.PHONY: tests #tests: # $(CARGO) test --test client .PHONY: examples examples: $(CARGO) build --example b64 $(CARGO) build --example simple $(CARGO) build --example snappy clean: $(CARGO) clean <file_sep>/examples/cobs/cobs.rs use std::io; //error::Error; use std::iter::Iterator; use yabts::transform::*; #[derive(Copy, Clone)] pub struct COBS {} impl _Encode for COBS { fn _encode(&self, payload: &mut Vec<u8>) -> Result<(), io::Error> { println!("Running the inner Encode method!!!\n"); let mut new_vec: Vec<u8> = Vec::new(); stuffdata(payload, &mut new_vec); payload.clear(); *payload = new_vec.clone(); Ok(()) } } impl _Decode for COBS { fn _decode(&self, payload: &mut Vec<u8>) -> Result<(), io::Error> { println!("Running the inner Decode method!!!\n"); let mut new_vec: Vec<u8> = Vec::new(); unstuffdata(payload, &mut new_vec); payload.clear(); *payload = new_vec.clone(); Ok(()) } } fn stuffdata(src: &mut Vec<u8>, dst: &mut Vec<u8>) -> Result<(), ()> { let src_len = src.len(); let mut search_len: u8 = 1; for i in 0..src_len { if src[i] == 0 { dst.push(search_len); search_len = 1; } else { search_len += 1; dst.push(src[i]); if search_len == 0xFF { dst.push(search_len); search_len = 1; } } } dst.push(search_len); Ok(()) } fn unstuffdata(src: &mut Vec<u8>, dst: &mut Vec<u8>) -> Result<(), ()> { let mut remaining_bytes: usize = 0; let mut src_byte: u8 = 0; let mut len_code: u8 = 0; let src_len = src.len(); for i in 0..src_len { len_code = src[i]; if len_code == 0 { break; } len_code -= 1; remaining_bytes = src_len - i; if len_code as usize > remaining_bytes { // TODO fix this dangerous game len_code = remaining_bytes as u8; } // for i in std::iter::range_step(len_code as usize, 0, -1){ //for j in (0isize..len_code as isize).step_by(-1){ for j in (0isize..len_code as isize).rev() { src_byte = src[j as usize]; //*src_read_ptr++; if (src_byte == 0) { break; } dst.push(src_byte); } if (len_code != 0xFE) { dst.push(0); } } Ok(()) } <file_sep>/src/helpers.rs use crate::*; use std::env; use std::process; use argparse::{ArgumentParser, StoreOption}; pub fn run_client_mode( addr: String, port: String, request: Option<super::REQUEST>, file: Option<String>, ) -> u16 { if let Some(req) = request { client::run_client(addr, port, req, file) } else { return super::EINVAL; } } ///Parse args such that a user can enter args in any order and all are optional pub fn parse_args() -> RUNMODE { let mut mode: Option<String> = None; let mut file: Option<String> = None; let mut addr_str: Option<String> = Some("127.0.0.1".to_string()); let mut port_str: Option<String> = Some("4000".to_string()); //let mut request: Option<String> = None; let mut req: Option<super::REQUEST> = None; { let mut parser = ArgumentParser::new(); parser.set_description("YABTS: Transform some bytes via TCP service"); parser.refer(&mut mode).add_option( &["-m", "--mode"], StoreOption, r#"RUNMODE: default is server, use client for client mode"#, ); parser.refer(&mut req).add_option( &["-r", "--request"], StoreOption, r#"REQUEST: If in client mode, specify the request to send to server"#, ); parser.refer(&mut file).add_option( &["-f", "--file"], StoreOption, r#"FILE: If in client mode and requestin transformation, specify file"#, ); parser.refer(&mut addr_str).add_option( &["-a", "--address"], StoreOption, r#"SERVER ADDRESS (default is 127.0.0.1)"#, ); parser.refer(&mut port_str).add_option( &["-p", "--port"], StoreOption, r#"SERVER PORT (default is 4000)"#, ); parser.parse_args_or_exit(); } if let Some(mode) = mode { match mode.as_str() { "client" => RUNMODE::CLIENT(addr_str.unwrap(), port_str.unwrap(), req, file), "server" => RUNMODE::SERVER(addr_str.unwrap(), port_str.unwrap()), _ => RUNMODE::SERVER(addr_str.unwrap(), port_str.unwrap()), } } else { RUNMODE::SERVER(addr_str.unwrap(), port_str.unwrap()) } } pub fn display_useage() { println!( "Useage:{} [-p <port>] [-a <address>] [-m <runmode>] [-r <request>] [-f <file name>]\n\ -p : \tspecify port for server (default is 4000)\n\ -a : \tspecify address for server(default is 127.0.0.1)\n\ -m : \tuse 'client' for client mode, 'server' for server mode. \n\ -r : \tfor client mode only, specify request using one of: encode/decode/compress/decompress\n\ -f : \tfor client mode only, optional file name for byte transform request\n\ \nIf no args provided, will default to run in server mode on 127.0.0.1:4000", env::args().nth(0).unwrap() ); } pub fn exit(status: u16) { process::exit(status as _); } <file_sep>/examples/snappy/main.rs extern crate snap; extern crate yabts; //use std::io; fn main() {} <file_sep>/examples/b64/b64.rs use std::io; use std::iter::Iterator; use yabts::transform::*; #[derive(Copy, Clone)] pub struct B64 {} impl _Encode for B64 { fn _encode(&self, payload: &mut Vec<u8>) -> Result<(), io::Error> { let mut new_vec: Vec<u8> = Vec::new(); let res = base64encode(payload, &mut new_vec); payload.clear(); *payload = new_vec.clone(); res } } impl _Decode for B64 { fn _decode(&self, payload: &mut Vec<u8>) -> Result<(), io::Error> { let mut new_vec: Vec<u8> = Vec::new(); let res = base64decode(payload, &mut new_vec); payload.clear(); *payload = new_vec.clone(); res } } //TODO: IS there a "safe" way to have the b64 char vec global? fn base64encode(input: &mut Vec<u8>, output: &mut Vec<u8>) -> Result<(), io::Error> { let in_len: usize = input.len(); let pad: usize = in_len % 3; let mut n: u32; // = 0; let mut n0: u8; // = 0; let mut n1: u8; // = 0; let mut n2: u8; // = 0; let mut n3: u8; // = 0; let mut i = 0; let b64charvec: Vec<char> = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" .chars() .collect(); // for i in (0..in_len).step_by(3) { while i < in_len { n = (input[i] as u32) << 16; if (i + 1) < in_len { n += (input[i + 1] as u32) << 8; } if (i + 2) < in_len { n += input[i + 2] as u32; } /* this 24-bit number gets separated into four 6-bit numbers */ n0 = ((n >> 18) & 63) as u8; n1 = ((n >> 12) & 63) as u8; n2 = ((n >> 6) & 63) as u8; n3 = (n & 63) as u8; output.push(b64charvec[n0 as usize] as u8); output.push(b64charvec[n1 as usize] as u8); if (i + 1) < in_len { output.push(b64charvec[n2 as usize] as u8); } if (i + 2) < in_len { output.push(b64charvec[n3 as usize] as u8); } i += 3; } if pad > 0 { for _i in pad..3 { output.push(0x3d); } } output.push(0); Ok(()) } //TODO!! Implement this fn base64decode(input: &mut Vec<u8>, output: &mut Vec<u8>) -> Result<(), io::Error> { let in_len: usize = input.len(); let mut i = 0; let d: Vec<u8> = vec![ 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 64, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 62, 66, 66, 66, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 66, 66, 66, 65, 66, 66, 66, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 66, 66, 66, 66, 66, 66, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, ]; let mut iter: u8 = 0; let mut buf: u32 = 0; while i < in_len { let idx = input[i]; let c = d[idx as usize]; match c { 64 => { i += 1; continue; } 65 => { break; } 66 => { //TODO err return Err(io::Error::new( io::ErrorKind::Other, "Invalid bytes for b64 decoding", )); } _ => { buf = buf << 6 | c as u32; iter += 1; if iter == 4 { output.push(((buf >> 16) & 255) as u8); output.push(((buf >> 8) & 255) as u8); output.push((buf & 255) as u8); buf = 0; iter = 0; } } }; i += 1; } if iter == 3 { output.push(((buf >> 10) & 255) as u8); output.push(((buf >> 2) & 255) as u8); } else if iter == 2 { output.push(((buf >> 4) & 255) as u8); } Ok(()) } <file_sep>/examples/b64/main.rs extern crate yabts; use yabts::{helpers::*, *}; pub mod b64; use b64::*; fn main() { let status = match parse_args() { RUNMODE::CLIENT(addr, port, mode, file) => run_client_mode(addr, port, mode, file), RUNMODE::SERVER(addr, port) => { let method = B64 {}; let server = server::Server::new( transform::TransformPayload { to_method_e: Some(Box::new(method)), from_method_ed: Some(Box::new(method.clone())), to_method_c: None, from_method_cd: None, }, addr, port, ); if server.is_err() { println!("\nERROR: internal server error\n"); display_useage(); exit(EINVAL); } let mut server = server.unwrap(); server.listen() } }; exit(status); } <file_sep>/src/lib.rs extern crate argparse; extern crate bincode; extern crate serde; pub mod client; pub mod helpers; pub mod message; pub mod server; pub mod stats; pub mod transform; ///end users may want to modify for different MTUs pub const MAX_MSG_LEN: usize = 4000; ///header size is 8 bytes pub const MAX_PAYLOAD_LEN: usize = MAX_MSG_LEN - 8; ///deadbeef for valid header magic pub const MAGIC: u32 = 0xDEADBEEF; /// Valid Statuses w.r.t incoming requests / outgoing responses pub const OK: u16 = 0; //OK request/response pub const UNKNOWN: u16 = 1; //unknown internal error pub const EINVAL: u16 = 2; //invalid request e.g. message too large; pub const ENOSUP: u16 = 3; //Unsupported request type // RESERVE 4-32 pub const INTERNAL_ERROR: u16 = 33; //some internal error state pub const OTHER_ERROR: u16 = 34; /// Valid Client Requests #[derive(Copy, Clone)] pub enum REQUEST { NONE = 0, PING = 1, GET, RESET, COMPRESS, DECOMPRESS, ENCODE, DECODE, } impl std::str::FromStr for REQUEST { type Err = std::io::Error; fn from_str(request: &str) -> Result<REQUEST, std::io::Error> { match request { "ping" => Ok(REQUEST::PING), "get" => Ok(REQUEST::GET), "reset" => Ok(REQUEST::RESET), "compress" => Ok(REQUEST::COMPRESS), "decompress" => Ok(REQUEST::DECOMPRESS), "encode" => Ok(REQUEST::ENCODE), "decode" => Ok(REQUEST::DECODE), _ => { return Err(std::io::Error::new( std::io::ErrorKind::Other, "Invalid request provided", )) } } } } use std::convert::TryFrom; impl TryFrom<u16> for REQUEST { type Error = (); fn try_from(v: u16) -> Result<Self, Self::Error> { match v { x if x == REQUEST::NONE as u16 => Ok(REQUEST::NONE), x if x == REQUEST::PING as u16 => Ok(REQUEST::PING), x if x == REQUEST::GET as u16 => Ok(REQUEST::GET), x if x == REQUEST::RESET as u16 => Ok(REQUEST::RESET), x if x == REQUEST::COMPRESS as u16 => Ok(REQUEST::COMPRESS), x if x == REQUEST::DECOMPRESS as u16 => Ok(REQUEST::DECOMPRESS), x if x == REQUEST::ENCODE as u16 => Ok(REQUEST::ENCODE), x if x == REQUEST::DECODE as u16 => Ok(REQUEST::DECODE), _ => Err(()), } } } pub enum RUNMODE { CLIENT(String, String, Option<REQUEST>, Option<String>), SERVER(String, String), } <file_sep>/src/transform.rs use std::io; //error::Error; pub struct TransformPayload { ///* TODO DO we want support for multiple types at once? e.g. vector of dynamic trait objects? pub to_method_e: Option<Box<dyn _Encode>>, pub from_method_ed: Option<Box<dyn _Decode>>, pub to_method_c: Option<Box<dyn _Compress>>, pub from_method_cd: Option<Box<dyn _Decompress>>, } pub trait Transform { fn transform(&self, direction: bool, payload: &mut Vec<u8>) -> Result<(), io::Error>; } impl Transform for TransformPayload { fn transform(&self, direction: bool, payload: &mut Vec<u8>) -> Result<(), io::Error> { match direction { true => match self.to_method_e.as_ref() { Some(e) => e._encode(payload), None => match self.to_method_c.as_ref() { Some(e) => e._compress(payload), None => Err(io::Error::new(io::ErrorKind::Other, "Not implemented")), }, }, false => match self.from_method_ed.as_ref() { Some(d) => d._decode(payload), None => match self.from_method_cd.as_ref() { Some(d) => d._decompress(payload), None => Err(io::Error::new(io::ErrorKind::Other, "Not implemented")), }, }, } } } pub trait _Encode { fn _encode(&self, payload: &mut Vec<u8>) -> Result<(), io::Error>; } pub trait _Decode { fn _decode(&self, payload: &mut Vec<u8>) -> Result<(), io::Error>; } pub trait _Compress { fn _compress(&self, payload: &mut Vec<u8>) -> Result<(), io::Error>; } pub trait _Decompress { fn _decompress(&self, payload: &mut Vec<u8>) -> Result<(), io::Error>; } /* * The following are generic traits that * users can implement dynamic trait objects on * e.g. users can implement Encode for some algorithm like * base 64. Then users can implement Encode<B: b64> for Vec<u8> * pub trait Compress<T> { // fn compress<T>(payload: Payload) fn _compress<T>(payload: Vec<u8>) -> Result<Vec<u8>, dyn Error>; fn __compress<T>(self) -> Result<Vec<u8>, dyn Error>; fn buf_compress<T>(self)-> Result<&[u8], dyn Error>; } pub trait Decompress<T> { fn decompress<T>(payload: Vec<u8>) -> Result<Vec<u8>, dyn Error>; } //Default associated type is self e.g. no encode pub trait Encode<T=Self> { fn encode<T>(payload: Vec<u8>) -> Result<Vec<u8>, dyn Error>; } */ /* pub trait ___Payload<E: _Encode> { type Input; fn encode<T>(&self, payload: &mut T) -> Result<(), io::Error>; } pub struct Payload { //<E: _Encode> { pub method: Box<dyn _Encode>, } impl Payload // where // E: _Encode, { pub fn run(&self, bytes: &mut Vec<u8>) { println!("Running the outer method!\n"); self.method._encode(bytes); } } pub struct EncodePayload { //<E: _Encode> { pub to_method: Box<dyn _Encode>, pub from_method: Box<dyn _Decode>, } impl EncodePayload // where // E: _Encode, { pub fn run_to(&self, bytes: &mut Vec<u8>) { println!("Running the outer encode method!\n"); self.to_method._encode(bytes); } pub fn run_from(&self, bytes: &mut Vec<u8>) { println!("Running the outer decode method!\n"); self.from_method._decode(bytes); } }*/ /* pub struct _Payload<T, F> { pub bytes: Vec<u8>, to_method: T, //Box<dyn T>, from_method: F, //Box<dyn F> } impl<T, F> _Payload<T, F> where T: _Encode, F: _Decode, { pub fn run_to_encode(&self, bytes: &mut Vec<u8>) { self.to_method._encode(bytes); } pub fn run_from_encode(&self, bytes: &mut Vec<u8>) { self.from_method._decode(bytes); } } impl<T, F> _Payload<T, F> where T: _Compress, F: _Decompress, { pub fn run_to_compress(&self, bytes: &mut Vec<u8>) { self.to_method._compress(bytes); } pub fn run_from_compress(&self, bytes: &mut Vec<u8>) { self.from_method._decompress(bytes); } } */ /* pub struct _Payload<'a, T> { pub bytes: Vec<u8>, pub bytes_unwrapped: &'a[u8], pub phantom: T } */ /* pub struct __Payload<E: Encode, D: Decode> { pub bytes: Vec<u8>, //pub bytes_unwrapped: &'a[u8], } */ pub struct __Payload<T> { pub bytes: T, //Vec<u8>, //pub bytes_unwrapped: &'a[u8], } #[derive(Copy, Clone)] pub struct Default {} impl _Encode for Default { fn _encode(&self, _payload: &mut Vec<u8>) -> Result<(), io::Error> { println!("Running the inner generic Encode method!!!\n"); Ok(()) } } impl _Decode for Default { fn _decode(&self, _payload: &mut Vec<u8>) -> Result<(), io::Error> { println!("Running the inner generic Decode method!!!\n"); Ok(()) } } impl _Compress for Default { fn _compress(&self, _payload: &mut Vec<u8>) -> Result<(), io::Error> { println!("Running the inner generic Encode method!!!\n"); Ok(()) } } impl _Decompress for Default { fn _decompress(&self, _payload: &mut Vec<u8>) -> Result<(), io::Error> { println!("Running the inner generic Decode method!!!\n"); Ok(()) } } <file_sep>/src/client.rs use bincode; use std::fs::File; use std::io::{Read, Write}; use std::net::{IpAddr, Ipv4Addr, SocketAddr, TcpStream}; use std::str; use std::str::FromStr; use crate::{message, MAX_MSG_LEN}; pub fn parse_payload(file: Option<String>) -> Option<Vec<u8>> { if let Some(file) = file { let mut fp = match File::open(file) { Err(why) => { println!("\nCLIENT: Could not open file, reason {:?}, exiting", why); return None; } Ok(fp) => fp, }; let mut file_payload: Vec<u8> = vec![]; if fp.read_to_end(&mut file_payload).is_err() { println!("\nCLIENT: process unable to read file, exiting"); return None; } println!("Got the payload: {:?}", file_payload); Some(file_payload) } else { None } } pub fn run_client( addr: String, _port: String, request: super::REQUEST, file: Option<String>, ) -> u16 { let send_payload: Option<Vec<u8>> = match request { super::REQUEST::COMPRESS => parse_payload(file), super::REQUEST::DECOMPRESS => parse_payload(file), super::REQUEST::ENCODE => parse_payload(file), super::REQUEST::DECODE => parse_payload(file), super::REQUEST::PING => None, super::REQUEST::GET => None, super::REQUEST::RESET => None, _ => { return super::EINVAL; } }; let ip = Ipv4Addr::from_str(&addr); let port = u16::from_str_radix(&_port, 10); let socket = match ip { Ok(a) => match port { Ok(p) => SocketAddr::new(IpAddr::V4(a), p), Err(e) => { println!("\nSERVER: Invalid server port provided {:?}", e); return super::EINVAL; } }, Err(e) => { println!("\nSERVER: Invalid server address provided: {:?}", e); return super::EINVAL; } }; let stream = TcpStream::connect(socket); if stream.is_ok() { let mut stream = stream.unwrap(); let request_msg = base_request(request as u16, send_payload); let send_bytes = bincode::serialize(&request_msg).unwrap(); if stream.write(send_bytes.as_slice()).is_err() { println!("\nCLIENT: Failure to write to TCP stream"); return super::UNKNOWN as _; } let mut read_it = [0u8; MAX_MSG_LEN]; if stream.read(&mut read_it).is_err() { println!("\nCLIENT: Failure to read TCP stream"); return super::UNKNOWN as _; } process_response(request, &read_it) } else { println!("\nCLIENT: unable to connect to TCP server at 127.0.0.1:4000, exiting"); return super::UNKNOWN as _; } } pub fn process_response(request: super::REQUEST, read_it: &[u8]) -> u16 { let msg: message::Message; match bincode::deserialize(&read_it) { Ok(message) => { msg = message; println!( "\nCLIENT: received response with header {:?} and payload {:?}", msg.get_header(), msg.get_payload() ); let (_, status) = msg.get_header().get(); if status != super::OK { println!("\nCLIENT: received error response {:?}", status); return status as _; } match request { super::REQUEST::PING => { println!("\nCLIENT: Ping: return status {:?}", status); } super::REQUEST::GET => { let res = serialize_to_stats(msg.get_payload().unwrap()); if res.is_err() { println!("\nCLIENT: unable to serialize received stats data"); return super::UNKNOWN; } else { let (returned_sent, returned_rcv, cratio, dratio, eratio, deratio) = res.unwrap(); println!( "\nCLIENT: Stats: return status {:?}, server returned sent bytes: {:?}, \ rcv'd bytes {:?}, compression ratio: {:?}, decompression ratio: {:?},\ encode ratio: {:?}, decode ratio: {:?}", status, returned_sent, returned_rcv, cratio, dratio, eratio, deratio ); } } super::REQUEST::RESET => { println!("\nCLIENT: Reset: return status {:?}", status); } _ => { match str::from_utf8(msg.get_payload().unwrap().as_slice()) { Ok(p) => { println!("\nCLIENT: transformed data:\n {:?}", p); } Err(e) => { println!( "\nCLIENT: unable to decode returned payload as utf: {:?}", e ); return super::UNKNOWN; } }; } }; } Err(e) => { println!("\nCLIENT: Unable to deserialize read-in bytes {:?}", e); return super::OTHER_ERROR; } }; return super::OK; } pub fn serialize_to_stats(payload: Vec<u8>) -> Result<(u64, u64, u8, u8, u8, u8), ()> { if payload.len() != 20 { println!( "\nCLIENT: Payload is longer than it should be! Length is {:?}", payload.len() ); return Err(()); } //copy_from_slice() and clone_from_slice both fail to copy over vec's bytes? let mut sent_bytes: [u8; 8] = [0; 8]; let mut rcv_bytes: [u8; 8] = [0; 8]; for i in 0..8 { sent_bytes[i] = payload[i]; rcv_bytes[i] = payload[i + 8]; } let sent = u64::from_ne_bytes(sent_bytes); let rcv = u64::from_ne_bytes(rcv_bytes); let cratio = payload[16]; let dratio = payload[17]; let eratio = payload[18]; let deratio = payload[19]; Ok((sent, rcv, cratio, dratio, eratio, deratio)) } fn base_request(request: u16, payload: Option<Vec<u8>>) -> message::Message { match request { x if x == super::REQUEST::PING as u16 => { println!("\nCLIENT: requesting ping..."); message::Message::new(0, request, None) } x if x == super::REQUEST::GET as u16 => { println!("\nCLIENT: requesting server stats..."); message::Message::new(0, request, None) } x if x == super::REQUEST::RESET as u16 => { println!("\nCLIENT: requesting server stat reset..."); message::Message::new(0, request, None) } x if x == super::REQUEST::COMPRESS as u16 => { println!("\nCLIENT: requesting compression..."); if let Some(payload) = payload { let length = payload.len(); message::Message::new(length as u16, request, Some(payload)) } else { println!("\nCLIENT: invalid request"); return message::Message::default(); } } x if x == super::REQUEST::DECOMPRESS as u16 => { println!("\nCLIENT: requesting compression..."); if let Some(payload) = payload { let length = payload.len(); message::Message::new(length as u16, request, Some(payload)) } else { println!("\nCLIENT: invalid request"); return message::Message::default(); } } x if x == super::REQUEST::ENCODE as u16 => { println!("\nCLIENT: requesting encoding..."); if let Some(payload) = payload { let length = payload.len(); message::Message::new(length as u16, request, Some(payload)) } else { println!("\nCLIENT: invalid request"); return message::Message::default(); } } x if x == super::REQUEST::DECODE as u16 => { println!("\nCLIENT: requesting decoding..."); if let Some(payload) = payload { let length = payload.len(); message::Message::new(length as u16, request, Some(payload)) } else { println!("\nCLIENT: invalid request"); return message::Message::default(); } } _ => { println!("\nCLIENT: invalid request"); return message::Message::default(); } } } <file_sep>/examples/simple/simple.rs use std::io; //error::Error; //use std::iter::Iterator; use yabts::transform::*; //use std::str; use std::slice; use std::str; #[derive(Copy, Clone)] pub struct Simple {} /// The simple compression algorithm cannot handle uppercase /// letters, numbers, or punctuation /// /// The algorithm compresses a given string by first converting to ascii utf8 encoding, ensuring /// that this is valid then back to raw bytes and iterating recursively over each repeated substring. /// To perform compression it iterates through a string by recursing over each repeating char /// substring and returning the count via a helper function. /// /// For example, a string `aaabbbccc` would be compressed to 3a3b3c /// /// If any error condition met, return Err(), else return with OK(()) /// /// To do: make this more memory efficient impl _Compress for Simple { fn _compress(&self, payload: &mut Vec<u8>) -> Result<(), io::Error> { //Make sure that the payload has a valid UTF8 encoding let ascii_slice = str::from_utf8(payload.as_slice()); if ascii_slice.is_ok() { let ascii_slice = ascii_slice.unwrap(); let length = ascii_slice.len(); let ptr = ascii_slice.as_ptr(); let slice = unsafe { // build a &[u8] slice::from_raw_parts(ptr, length) }; let mut counts: Vec<(usize, u8)> = Vec::new(); //vec![0usize, length, length]; //recursively count each repeating substring //reject string if anything other than lowercase chars // (numeric values, punctuation, uppercase) detected if count(slice, &mut counts, length).is_err() { return Err(io::Error::new(io::ErrorKind::Other, "Invalid string")); } //build a new vector of bytes from the returned counts and chars of each //repeating substring let mut new_string_vec: Vec<u8> = Vec::new(); for i in 0..counts.len() { let (count, char_byte) = counts[i]; match count { 1 => { //dont compress new_string_vec.push(char_byte); } 2 => { //dont compress new_string_vec.push(char_byte); new_string_vec.push(char_byte); } _ => { //if count is single digit, convert to a char let count_char = std::char::from_digit(count as u32, 10); if count_char.is_some() { let count_char = count_char.unwrap(); new_string_vec.push(count_char as u8); new_string_vec.push(char_byte); } else { //count is double to quadruple digit, so must get // the individual ascii values for each byte individually // by converting it to a string, then indexing it as a slice let chars = count.to_string(); let length = chars.len(); let ptr = chars.as_ptr(); let char_slice = unsafe { slice::from_raw_parts(ptr, length) }; if count >= 10 && count < 100 { //push the individual bytes new_string_vec.push(char_slice[0] as u8); new_string_vec.push(char_slice[1] as u8); new_string_vec.push(char_byte as u8); } else if count >= 100 && count < 1000 { new_string_vec.push(char_slice[0] as u8); new_string_vec.push(char_slice[1] as u8); new_string_vec.push(char_slice[2] as u8); new_string_vec.push(char_byte as u8); } else if count >= 1000 && count < super::MAX_MSG_LEN { new_string_vec.push(char_slice[0] as u8); new_string_vec.push(char_slice[1] as u8); new_string_vec.push(char_slice[2] as u8); new_string_vec.push(char_slice[3] as u8); new_string_vec.push(char_byte as u8); } else { //invalid string return Err(io::Error::new(io::ErrorKind::Other, "Invalid string")); } } } } } payload.clear(); *payload = new_string_vec.clone(); return Ok(()); } return Err(io::Error::new( io::ErrorKind::Other, "Cannot decode as utf8", )); } } impl _Decompress for Simple { fn _decompress(&self, _payload: &mut Vec<u8>) -> Result<(), io::Error> { Ok(()) } } /// Iterate over a substring and return the count pub fn count(slice: &[u8], counts: &mut Vec<(usize, u8)>, length: usize) -> Result<(), ()> { let mut index = 0; while index < length { if (slice[index] =< 122 && slice[index] >= 97) || (slice[index] =< 90 && slice[index] >= 41) { //EOF and \n are not considered invalid if at end of input if index == length - 1 && slice[index] == 0xa { break; } else { return Err(()); } } //recurse over the string until a new char is encountered, returning the count of the //repeating substring let char_count = helper(slice, slice[index], index, length); //push a tuple to the counts vector: the count and the char value counts.push((char_count, slice[index])); //increment the index if char_count == 0 { index += 1; } else { index += char_count; } } Ok(()) } ///Recursive helper function. Obtain counts of all chars in the string pub fn helper(slice: &[u8], char_byte: u8, index: usize, length: usize) -> usize { //base cases: string has been iterated through or char vals not equivalent if index == length || slice[index] != char_byte { return 0; } else if slice[index] == char_byte { return helper(slice, char_byte, index + 1, length) + 1; } else { return 0; } }
17a32120730f9077bdf4c81033ba4d0cf357629e
[ "Markdown", "Rust", "Makefile" ]
14
Rust
nand-nor/yabts
d5187057474b85545ce14c08736449268edd371e
8afca879b4bcd917885a10367258c4714dde00e4
refs/heads/master
<file_sep># EOS#46 EOS Smart Contract Features 1. event table: receive event reward deposit 2. deposit table: receieve data owner stake token 3. reward: send reward from contract vault to selected data owner 4. refund: send refund from contract vault to data owner<file_sep>{ "scripts": { "test": "jest" }, "devDependencies": { "@babel/core": "^7.1.2", "@babel/preset-env": "^7.1.0", "babel-core": "^7.0.0-bridge.0", "babel-jest": "^23.6.0", "eosjs": "20.0.0-beta2", "jest": "^23.6.0", "node-fetch": "^2.2.0", "regenerator-runtime": "^0.12.1" } } <file_sep>import { rpc } from './initAPI'; export async function events() { const query = { code: 'eventchainac', scope: 'eventchainac', table: 'eventstruct' }; const { rows } = await rpc.get_table_rows(query); return rows; } export async function deposits({ event_name}) { const query = { code: 'eventchainac', scope: event_name, table: 'depostruct' }; const { rows } = await rpc.get_table_rows(query); return rows; } <file_sep>cmake_minimum_required(VERSION 3.5) project(3rdex VERSION 1.0.0) find_package(eosio.cdt) add_contract( eventchain eventchain eventchain/eventchain.cpp ) set (deploy_command docker exec eosio_notechain_container /bin/bash -c 'deploy_contract.sh eventchain notechainacc notechainwal PW5J9A1K4TnRxA5Uoecm1ysGd1UfXH8qZMPTEJzA3cLhm6gMqmoaq') add_custom_target(deploy) add_custom_command( TARGET deploy POST_BUILD COMMAND ${deploy_command} WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} COMMENT "deploy" ) <file_sep>#include <eosiolib/eosio.hpp> #include <eosiolib/asset.hpp> using namespace eosio; using std::string; CONTRACT eventchain : public eosio::contract { private: TABLE eventstruct { uint64_t prim_key; name user; name event_name; asset reward; uint64_t timestamp; auto primary_key() const { return prim_key; } uint64_t index_by_name() const { return event_name.value; } }; TABLE depostruct { uint64_t prim_key; name user; asset deposit; uint64_t timestamp; auto primary_key() const { return prim_key; } uint64_t index_by_user() const { return user.value; } }; typedef eosio::multi_index< name("eventstruct"), eventstruct, indexed_by<name("byname"), const_mem_fun<eventstruct, uint64_t, &eventstruct::index_by_name>>> event_table; typedef eosio::multi_index< name("depostruct"), depostruct, indexed_by<name("byuser"), const_mem_fun<depostruct, uint64_t, &depostruct::index_by_user>>> deposit_table; event_table _events; bool is_event_exist(name event_name) { auto index = _events.get_index<name("byname")>(); auto itr = index.find(event_name.value); return itr != index.end(); } bool is_deposit_exist(deposit_table & deposits, name user) { auto index = deposits.get_index<name("byuser")>(); auto itr = index.find(user.value); return itr != index.end(); } public: using contract::contract; // constructor eventchain(name receiver, name code, datastream<const char *> ds) : contract(receiver, code, ds), _events(receiver, receiver.value) {} ACTION reward(name user, name owner, name event_name){ require_auth(user); auto index = _events.get_index<name("byname")>(); auto &event_entry = index.get(event_name.value); auto reward = event_entry.reward; action(permission_level{_self, name("active")}, name("eosio.token"), name("transfer"), std::make_tuple(_self, owner, reward, string("Thank you for your data."))) .send(); _events.erase(event_entry); } ACTION refund(name owner, name event_name) { eosio_assert(!is_event_exist(event_name), "can not refund while event ongoing"); deposit_table deposits = deposit_table(_self, event_name.value); auto index = deposits.get_index<name("byuser")>(); auto &deposit_entry = index.get(owner.value); action(permission_level{_self, name("active")}, name("eosio.token"), name("transfer"), std::make_tuple(_self, deposit_entry.user, deposit_entry.deposit, string("refund."))) .send(); deposits.erase(deposit_entry); } void data_owner_deposit(name user, name event_name, asset deposit) { eosio_assert(is_event_exist(event_name), "can not deposit to event end or not exist."); deposit_table deposits = deposit_table(_self, event_name.value); if (!is_deposit_exist(deposits, user)) { deposits.emplace(_self, [&](auto &item) { item.prim_key = deposits.available_primary_key(); item.user = user; item.deposit = deposit; item.timestamp = now(); }); } else { auto index = deposits.get_index<name("byuser")>(); auto &entry = index.get(event_name.value); deposits.modify(entry, _self, [&](auto &item) { item.deposit += deposit; item.timestamp = now(); }); } } void data_user_deposit(name user, name event_name, asset reward) { if (!is_event_exist(event_name)) { _events.emplace(_self, [&](auto &new_event) { new_event.prim_key = _events.available_primary_key(); new_event.user = user; new_event.event_name = event_name; new_event.reward = reward; new_event.timestamp = now(); }); } else { auto index = _events.get_index<name("byname")>(); auto &event_entry = index.get(event_name.value); _events.modify(event_entry, _self, [&](auto &modified_event) { modified_event.reward += reward; modified_event.timestamp = now(); }); } } struct transfer_struct { name from; name to; asset quantity; string memo; }; void on_transfer(uint64_t sender, uint64_t receiver) { auto transfer_data = unpack_action_data<transfer_struct>(); if (transfer_data.from == _self || transfer_data.to != _self) { return; } eosio_assert(transfer_data.quantity.is_valid(), "Invalid token transfer"); eosio_assert(transfer_data.quantity.amount > 0, "Quantity must be positive"); auto symbol = transfer_data.quantity.symbol; auto type = transfer_data.memo.substr(0, 1); auto event_name = transfer_data.memo.substr(1); if (type == "o") { data_owner_deposit(transfer_data.from, name(event_name), transfer_data.quantity); } else if (type == "u") { data_user_deposit(transfer_data.from, name(event_name), transfer_data.quantity); } } }; // specify the contract name, and export a public action: update extern "C" { void apply(uint64_t receiver, uint64_t code, uint64_t action) { if (code == receiver) { switch (action) { EOSIO_DISPATCH_HELPER(eventchain, (reward)(refund)) } } else if (action == name("transfer").value && code == name("eosio.token").value) { execute_action(name(receiver), name(code), &eventchain::on_transfer); } } }; <file_sep>export function data_user_deposit(from, quantity, event_name) { return { account: 'eosio.token', name: 'transfer', authorization: [{ actor: from, permission: 'active' }], data: { from: from, to: 'eventchainac', quantity: quantity, memo: `u${event_name}` }, }; } export function data_owner_deposit(from, quantity, event_name) { return { account: 'eosio.token', name: 'transfer', authorization: [{ actor: from, permission: 'active' }], data: { from: from, to: 'eventchainac', quantity: quantity, memo: `o${event_name}` }, }; } export function reward(from, to, event_name) { return { account: 'eventchainac', name: 'reward', authorization: [{ actor: from, permission: 'active' }], data: { user: from, owner: to, event_name}, }; } export function refund(owner, event_name) { return { account: 'eventchainac', name: 'refund', authorization: [{ actor: owner, permission: 'active' }], data: { owner, event_name }, }; }<file_sep>import { Api, JsonRpc, RpcError, JsSignatureProvider, SerialBuffer } from 'eosjs'; import fetch from 'node-fetch'; import { TextDecoder, TextEncoder } from 'text-encoding'; export const rpc = new JsonRpc('http://127.0.0.1:8888', { fetch }); export function initAPI(defaultPrivateKey){ // const defaultPrivateKey = "<KEY>"; const signatureProvider = new JsSignatureProvider([defaultPrivateKey]); const api = new Api({ rpc, signatureProvider, textDecoder: new TextDecoder(), textEncoder: new TextEncoder() }); return api; } export function name(name) { return name.split('').map(c=>c.charCodeAt(0)).reduce((r,x)=>{ return (r<<8) + x; },0); } export function parse_token(token_string){ const [amount, symbol] = token_string.split(' '); return Number(amount); }
1d7e7aaaebbe7395cbe861183b7f0d4c56d64f6b
[ "JSON", "CMake", "Markdown", "JavaScript", "C++" ]
7
Markdown
macctown/Vitadata-EOS-Contract
b2dd6da80543e3f783f5162c5dca8b035b263513
a425e77f798b3fef14cf2cb79bf7400f1c2643da
refs/heads/master
<repo_name>DeFreitas-Samuel/XamarinFeatures<file_sep>/XamarinFeatures/XamarinFeatures/ViewModels/HomeViewModel.cs using Prism.Commands; using Prism.Navigation; using System; using System.Collections.Generic; using System.Text; using System.Windows.Input; using Xamarin.Forms; using XamarinFeatures.Services; namespace XamarinFeatures.ViewModels { public class HomeViewModel : BaseViewModel { public HomeViewModel(INavigationService navigationService) : base(navigationService) { CheckPositionCommand = new DelegateCommand(CheckPosition); } private void CheckPosition() { var orientation = DependencyService.Get<IOrientationService>().GetOrientation(); if (orientation == Xamarin.Forms.Internals.DeviceOrientation.Portrait) { PositionText = "Portrait Orientation"; } else { PositionText = "Landscape Orientation"; } } public ICommand CheckPositionCommand { get; } public string PositionText { get; set; } } } <file_sep>/README.md # XamarinFeatures The three platform specifics that I used were: 1. A platform specific that puts the tab bar in the bottom of the page 2. A platform specific that allows you to swipe to change the tab you are on 3. A platform specific that allows you to position elements on top of other elements ![Screenshot_1633904206](https://user-images.githubusercontent.com/52897285/136714814-ab4ab92c-ff87-4a6d-bc31-1a30c237c92e.png) <file_sep>/XamarinFeatures/XamarinFeatures/App.xaml.cs using Prism; using Prism.Ioc; using Prism.Unity; using System; using Xamarin.Forms; using Xamarin.Forms.Xaml; using XamarinFeatures.ViewModels; using XamarinFeatures.Views; namespace XamarinFeatures { public partial class App : PrismApplication { public App(IPlatformInitializer platformInitializer): base(platformInitializer) { InitializeComponent(); } protected override void OnInitialized() { NavigationService.NavigateAsync("/MainPage"); } protected override void RegisterTypes(IContainerRegistry containerRegistry) { containerRegistry.RegisterForNavigation<HomePage, HomeViewModel>(); containerRegistry.RegisterForNavigation<MainPage>(); } } } <file_sep>/XamarinFeatures/XamarinFeatures.iOS/Renderers/CustomEntryRenderer.cs using Foundation; using System; using System.Collections.Generic; using System.Linq; using System.Text; using UIKit; using Xamarin.Forms; using Xamarin.Forms.Platform.iOS; namespace XamarinFeatures.iOS.Renderers { public class CustomEntryRenderer : EntryRenderer { protected override void OnElementChanged(ElementChangedEventArgs<Entry> e) { base.OnElementChanged(e); if (Control != null) { Control.BackgroundColor = UIColor.Blue; } } } }
cd5ecb88fdc9d59a8a86f20c11e61b47a11f1bdd
[ "Markdown", "C#" ]
4
C#
DeFreitas-Samuel/XamarinFeatures
3b0791394a518137d7f8a1128c21009d74ccbfda
164c7627be98c2e5f1b98e8e92dff38c24b5dc55
refs/heads/master
<repo_name>wennbergsmithe/ExoplanetVisualization<file_sep>/README.md # ExoplanetVisualization <b>Demonstrates</b>: Use of API, Data Structures, File IO, Basic Concepts in Astronomy <br> <br> <b>Exoplanets.py </b>: Pulls confirmed exoplanets database from Caltech API, calculates luminosity and the habitable zone of each host star, estimates the comosition of each exoplanet based on its density then writes results to planets.csv file for Cytoscape <br> <b>planets.csv</b>: Results from the python script. <br> <b>planets.pdf</b>: Planets ranked by mass, sized based on radius, and colored according to thier composition. <br> <b>DensitiesLegend.png</b>: Legend for compostion colors. <br> <b>planetsMethod.pdf</b>: Planets ranked by mass, sized based on radius, and colored according to the method used to discover them. <br> <b>MethodsLegend.png</b>: Legend for method colors. <br> <b>FinalWriteup.pdf</b>: PDF file describing my process. <br> <file_sep>/Exoplanets.py import requests s_boltz = 1.3*(10 ** -23) #pull data from API def apiRequest(): URL = "https://exoplanetarchive.ipac.caltech.edu/cgi-bin/nstedAPI/nph-nstedAPI?table=exoplanets&format=json" data = [] try: r = requests.get(url = URL) data = r.json() except Exception as e: print(e) #error handling return data #calculates stellar luminosity assuming mass and radius in solar units def stellarLum(mass,radius): return (mass**2)*(radius**4) #determines if the given of the planets lie withing the habitable zone of the given star #assumes earthlike albedo of .3 def habZone(lum, orbRad): aMax = (((1 - .3) * lum) / ((16 * 3.1415) * s_boltz * (275 ** 4)))**.5 aMin = (((1 - .3) * lum) / ((16 * 3.1415) * s_boltz * (375 ** 4)))**.5 #if lies within range if(orbRad <= aMax and orbRad >= aMin): return True else: return False #estimates composition of planet based on its density def estimateComp(dens): if(dens < 1): #automatically returns HJ if it is less than 1 because most are (for efficiency) return "Hot Jupiter" elif(dens == 1): return "water" #dictionary of common planetary materials and their densities commonDens = { "iron":7.86, "lead":11.36, "gold":19.32, "Earth":5.51, "Neptune":1.64, "Mars":3.93, "Hot Jupiter": 1.33} toReturn = "" #difference to determine which value is closest. #unreasonable initial value just to initaiate variable smallestDiff = 999 for material in commonDens: diff = commonDens[material] - dens absDiff = abs(diff) if(absDiff <= smallestDiff): smallestDiff = absDiff toReturn = material return toReturn #writes the data into a csv file to be used in cytoscape def format(planets): file = open("planets.csv","w") keys = planets[0].keys() firstline = "" for key in keys: firstline += key + "," firstline = firstline[:-1] firstline += "\n" file.write(firstline) for planet in planets: vals = planet.values() nextLine = "" for val in vals: nextLine += str(val) nextLine += "," nextLine = nextLine[:-1] nextLine += "\n" file.write(nextLine) file.close() def main(): data = apiRequest()#gather json data nodata = 0#just to know how many stars have no distance data narrowedData = []#list of planets with narrowed data and additional data computed by moi #for each planet within 20 parsecs for planet in data: try: #if there is data for density if(int(planet.get("pl_dens")) != None): planetDict = {"name":planet.get("pl_name"), "method":planet.get("pl_discmethod"), "orbitalPeriod": planet.get("pl_orbper"), "mass":planet.get("pl_bmassj"), "radius":planet.get("pl_radj"),"semimajor" : planet.get("pl_orbsmax"), "density":planet.get("pl_dens"), "composition":estimateComp(planet.get("pl_dens")), "dist": planet.get("st_dist"), "luminosity": stellarLum(planet.get("st_mass"),planet.get("st_rad")), "Habitable?" : habZone(stellarLum(planet.get("st_mass"),planet.get("st_rad")),planet.get("pl_orbsmax"))} narrowedData.append(planetDict) except: nodata += 1 format(narrowedData) main()
083fa4ceefc9d637c4ab4c13f04b79752f513767
[ "Markdown", "Python" ]
2
Markdown
wennbergsmithe/ExoplanetVisualization
b9d42e03eb851e91bd24091ae712a35c991c1834
b8a1561125473b7501dec0147988cd0535d06c70
refs/heads/master
<repo_name>shoujiaxin/NXP_Cup_CCD<file_sep>/main.c #include "adc.h" #include "cmt.h" #include "common,h" #include "control.h" #include "dma.h" #include "Drv_LCD.h" #include "ftm.h" #include "gpio.h" #include "io2iic.h" #include "main.h" #include "uart.h" uint16_t scheduler_5ms = 0; uint16_t scheduler_18ms = 0; uint16_t scheduler_50ms = 0; uint16_t scheduler_stop = 0; int main(void) { // SYSTICK初始化 MY_SYSTICK_Init(); DelayInit(); // PTA4设置为输入,防止死机 GPIO_QuickInit(HW_GPIOA, 4, kGPIO_Mode_OPP); // 指示灯初始化 GPIO_QuickInit(HW_GPIOA, 14, kGPIO_Mode_OPP); GPIO_QuickInit(HW_GPIOA, 15, kGPIO_Mode_OPP); // 蜂鸣器接口初始化(高电平工作) GPIO_QuickInit(HW_GPIOD, 6, kGPIO_Mode_OPP); GPIO_ResetBit(HW_GPIOD, 6); // 按键初始化 GPIO_QuickInit(HW_GPIOB, 4, kGPIO_Mode_IPU); GPIO_QuickInit(HW_GPIOB, 5, kGPIO_Mode_IPU); // 拨码开关初始化 GPIO_QuickInit(HW_GPIOB, 8, kGPIO_Mode_IPU); GPIO_QuickInit(HW_GPIOB, 9, kGPIO_Mode_IPU); GPIO_QuickInit(HW_GPIOB, 10, kGPIO_Mode_IPU); GPIO_QuickInit(HW_GPIOB, 11, kGPIO_Mode_IPU); // ADC端口初始化 MY_ADC_Init(); // UART0端口初始化 UART0_Init(115200); // DMA初始化 MY_DMA_Init(); // CCD初始化 TLS1401_Init(); // IO口模拟IIC端口初始化 GPIO_QuickInit(IIC_SCL_PORT, IIC_SCL_PIN, kGPIO_Mode_OPP); GPIO_QuickInit(IIC_SDA_PORT, IIC_SDA_PIN, kGPIO_Mode_OPP); // 舵机初始化 CMT_PWM_QuickInit(55, 0); // 设置舵机初始占空比,0-10000表示0%-100% CMT_PWM_ChangeDuty(990); // FTM快速初始化,设定频率为5000Hz FTM_PWM_QuickInit(FTM0_CH0_PC01, kPWM_EdgeAligned, 10000); FTM_PWM_QuickInit(FTM0_CH1_PC02, kPWM_EdgeAligned, 10000); FTM_PWM_QuickInit(FTM0_CH2_PC03, kPWM_EdgeAligned, 10000); FTM_PWM_QuickInit(FTM0_CH3_PC04, kPWM_EdgeAligned, 10000); // 设置FTM初始占空比,0-10000表示0%-100% FTM_PWM_ChangeDuty(HW_FTM0, HW_FTM_CH0, 0); FTM_PWM_ChangeDuty(HW_FTM0, HW_FTM_CH1, 0); FTM_PWM_ChangeDuty(HW_FTM0, HW_FTM_CH2, 0); FTM_PWM_ChangeDuty(HW_FTM0, HW_FTM_CH3, 0); // LCD初始化 LCD_Init(); while (1) { // 正常运行指示灯 GPIO_ToggleBit(HW_GPIOA, 14); Real_Time(); // 拨码开关1控制LCD显示 if (!GPIO_ReadBit(HW_GPIOB, 8)) { Printf(); } // 计时停止 if (scheduler_stop == 30000) { break; } } }
aecb93128018fd6329bbc1716d3e865fb6c8d389
[ "C" ]
1
C
shoujiaxin/NXP_Cup_CCD
7eb53107109cf3b8aba5cc74d1cfd7e4053ef6d3
8dce055a53a14c301b4d344809866426fc792bba
refs/heads/master
<repo_name>moba1/ctimer<file_sep>/src/main.cxx #include <iostream> #include <filesystem> #include <unistd.h> #include <thread> #include <chrono> #include <exception> void timer(unsigned long long time) { for (;time > 0; time--) { std::cout << "\r\033[2K" << time << " [sec]" << std::flush; std::this_thread::sleep_for(std::chrono::seconds(1)); } std::cout << "\r\033[2K" << "finish!" << std::endl; } void usage(const char *program_path) { const auto program_name = std::filesystem::path(program_path) .filename() .generic_string(); std::cout << "command line timer" << std::endl << std::endl << "Usage:" << std::endl << " " << program_name << " <time>" << std::endl << " " << program_name << " -h" << std::endl << " " << program_name << " -v" << std::endl << std::endl << "Arguments:" << std::endl << " <time>" << std::endl << " end time [sec]" << std::endl << std::endl << "Options" << std::endl << " -h" << std::endl << " show help" << std::endl << " -v" << std::endl << " show version" << std::endl; } const auto VERSION = "1.0"; void version(void) { std::cout << "version: " << VERSION << std::endl; } int main(int argc, char *argv[]) { int opt; while ((opt = getopt(argc, argv, "hv")) != -1) { switch (opt) { case 'h': usage(argv[0]); return 0; case 'v': version(); return 0; default: return 1; } } if (argc - optind < 1) { std::cerr << "<time> required" << std::endl; return 1; } try { const auto time = std::stoull(argv[optind]); timer(time); } catch (const std::invalid_argument& e) { std::cerr << "<time> must be non-negative integer" << std::endl; return 1; } catch (const std::out_of_range& e) { std::cerr << "<time> is larger than max"; return 1; } return 0; } <file_sep>/README.md # What's this command? Console timer # Usage ```bash $ timer ``` # build ```bash $ git clone https://github.com/moba1/timer $ cd <this project path> $ make ``` # run ```bash $ cd <this project path> $ bin/timer 10 # stop after 10 seconds ``` <file_sep>/Makefile BINDIR = ./bin TARGET = $(BINDIR)/$(shell basename `readlink -f .`) SRCDIR = ./src SOURCES = $(wildcard $(SRCDIR)/*.cxx) OBJDIR = ./obj OBJECTS = $(addprefix $(OBJDIR)/,$(notdir $(SOURCES:.cxx=.o))) CXXFLAGS = -std=c++17 -Wall -Wextra -pedantic -O2 -march=native .PHONY: all clean all: $(TARGET) $(TARGET): $(OBJECTS) -mkdir -p $(BINDIR) $(CXX) -o $@ $^ $(OBJDIR)/%.o: $(SRCDIR)/%.cxx -mkdir -p $(OBJDIR) $(CXX) $(CXXFLAGS) -o $@ -c $< clean: rm -Rf $(OBJDIR) $(BINDIR)
8b569d3a80e70c80f762c17e3096563eb74795b9
[ "Markdown", "Makefile", "C++" ]
3
C++
moba1/ctimer
cba2041ce5a6befe70b891dfdde674b08406c558
fef60018e3d0e7c4bb12ae932ec85861bf9f3315
refs/heads/main
<repo_name>yunasung1003/js-modal-onclickEvent<file_sep>/src/index.js import "./styles.css"; //돔 선택하고, 모달 열기 눌렀을 때, display:none -> flex 로 나타남 const open = document.getElementById("open"); const close = document.getElementById("close"); //class 로 되어있는 것은 쿼리로 선택 가능 //클래스 이름으로 찾을 땐 . 적어주기 const modal = document.querySelector(".modal-wrapper"); modal.style.display = "flex"; open.onclick = () => { modal.style.display = "flex"; }; close.onclick = () => { modal.style.display = "none"; }; <file_sep>/README.md # js-modal-onclickEvent Created with CodeSandbox
bc23bb4a02991673042ca14cf2f3c2d51eb32b9f
[ "JavaScript", "Markdown" ]
2
JavaScript
yunasung1003/js-modal-onclickEvent
9c8f49aa5070974fb0784c75f705d8394bbe38ae
ff2efbefeaf53d0eb2b5186b1f959157f49003b4
refs/heads/master
<repo_name>davidbreyault/vibes-in<file_sep>/js/app.js // Eléments du formulaire const formElt = document.querySelector('.form'); const dropdownElt = document.querySelector('.dropdown'); const dropdownListElt = document.querySelector('.dropdown__list'); const dropdownListItems = document.querySelectorAll('.dropdown__list--item'); const dropdownSelectSpan = document.querySelector('.dropdown__select span'); const dropdownSelectImg = document.querySelector('.dropdown__select img'); const selectSpanElt = document.querySelector('.dropdown__select span'); const searchSpanElt = document.querySelector('.search-span'); const searchInputElt = document.querySelector('#search-input'); const errorInfoElt = document.querySelector('.error-info'); // Eléments de la liste de résultats const resultsList = document.querySelector('.results-list'); const resultCounterElt = document.querySelector('.results-header__counter'); const resultInfoElt = document.querySelector('.results-header__info'); // Eléments de la modale const modalElt = document.querySelector('.modal'); const closeModalButton = document.querySelector('.close-modal__cross'); const modalInfoHeader = document.querySelector('.modal__header p'); const modalInfoTitle = document.querySelector('.modal__infos .title'); const modalInfoArtist = document.querySelector('.modal__infos .artist'); const modalInfoAlbum = document.querySelector('.modal__infos .album'); const modalInfoGenre = document.querySelector('.modal__infos .genre'); const modalInfoYear = document.querySelector('.modal__infos .year'); const modalInfoCountry = document.querySelector('.modal__infos .country'); const modalInfoLength = document.querySelector('.modal__infos .length'); const coversZoneElt = document.querySelector('.covers'); const starsRating = document.querySelectorAll('.star'); let parameter = null; let offset = 0; let cumulOffset = 0; let covers; // Transition du span du label lors du focus de l'input de recherche searchInputElt.addEventListener('focus', () => { searchSpanElt.classList.add('translate'); }) // Transition du span du label lors de la perte du focus seulement si l'input est vide searchInputElt.addEventListener('blur', () => { searchSpanElt.classList.remove('translate'); manageClass(searchSpanElt); }) // Gestion du mouvement du span du label de l'input de recherche function manageClass(element) { // Si le second paramètre est à true, ajoute cette classe, si non, supprime la. element.classList.toggle('translate', searchInputElt.value.length > 0); } // Fait apparaitre les options dropdownElt.addEventListener('click', () => { dropdownListElt.classList.toggle('dropdown__list--hidden'); dropdownSelectImg.classList.toggle('rotate'); }) // Remplace le contenu textuel dans le dropdown dropdownListItems.forEach((option) => { option.addEventListener('click', () => { dropdownSelectSpan.textContent = option.textContent; }) }) // Assignation de la variable parameter pour customiser l'URL de la future requête dropdownListItems.forEach((item) => { item.addEventListener('click', () => { selectSpanElt.setAttribute('data-value', item.getAttribute('data-value')); parameter = selectSpanElt.getAttribute('data-value'); }) }) // Contrôle la longueur de la chaine de caractères function limitCharacterLength(string, stringLength) { let newString = string.length > stringLength ? string.slice(0, stringLength - 3).concat('...') : string; return newString; } // Interdiction du scroll sur le body si la modale est ouverte function scrollManager() { modalElt.classList.contains('open') ? document.body.style.overflow = 'hidden' : document.body.style.overflow = 'scroll'; } // Création d'une ligne de données function createList(id, artist, title, album, mbid) { // Création des éléments let newId = document.createElement('p'); let newIdImg = document.createElement('img'); let newIdSpan = document.createElement('span'); // Artiste let newArtist= document.createElement('p'); let newArtistImg = document.createElement('img'); let newArtistSpan = document.createElement('span'); // Titre let newTitle = document.createElement('p'); let newTitleImg = document.createElement('img'); let newTitleSpan = document.createElement('span'); // Album let newAlbum = document.createElement('p'); let newAlbumImg = document.createElement('img'); let newAlbumSpan = document.createElement('span'); // bouton let newButton = document.createElement('button'); let newImgButton = document.createElement('img'); let newLine = document.createElement('li'); let newTitleMbid = mbid; // Distribution des classes newId.classList.add('results-list__item--id'); newArtist.classList.add('results-list__item--artist'); newTitle.classList.add('results-list__item--title'); newAlbum.classList.add('results-list__item--album'); newButton.classList.add('results-list__item--more'); newLine.classList.add('results-list__item'); // Attributs des logos newIdImg.src = 'img/icon-hashtag.svg'; newIdImg.alt = 'id_hashtag'; newArtistImg.src = 'img/icon-artist.svg'; newArtistImg.alt = 'artist_icon'; newTitleImg.src = 'img/icon-music-note.svg'; newTitleImg.alt = 'title_icon'; newAlbumImg.src = 'img/icon-disc.svg'; newAlbumImg.alt = 'album_icon'; newImgButton.src = 'img/icon-plus.svg'; newImgButton.alt = 'plus_icon'; // Contenu textuel des éléments newIdSpan.textContent = id; newArtistSpan.textContent = artist; newTitleSpan.textContent = title; newAlbumSpan.textContent = album; // Ajout images et span newId.appendChild(newIdImg); newId.appendChild(newIdSpan); newArtist.appendChild(newArtistImg); newArtist.appendChild(newArtistSpan); newTitle.appendChild(newTitleImg); newTitle.appendChild(newTitleSpan); newAlbum.appendChild(newAlbumImg); newAlbum.appendChild(newAlbumSpan); // bouton newButton.appendChild(newImgButton); // Lors du clique sur le bouton newButton.addEventListener('click', () => { //console.log(id + ' mbid : ' + newTitleMbid); covers = 0; // Ouverture de la fenêtre modale modalElt.classList.add('open'); // Scroll uniquement dans la modale scrollManager(); // Utilisation du innerHTML dans ce cas précis, afin de vider l'intégrité du contenu de l'élément coversZoneElt.innerHTML = ''; // Lancement d'une nouvelle requête pour récupérer les infos spécifiques et associées au titre en question lookupRequest(newTitleMbid, printDataInModal); // Lancement de la roulette de chargement createSpinnerLoader(coversZoneElt); }) // Ajout des éléments newLine.appendChild(newId); newLine.appendChild(newArtist); newLine.appendChild(newTitle); newLine.appendChild(newAlbum); newLine.appendChild(newButton); // Ajout de la nouvelle ligne resultsList.insertAdjacentElement('beforeend', newLine); } // Création de la roulette de chargement function createSpinnerLoader(location) { let newLoadingWheel = document.createElement('div'); newLoadingWheel.classList.add('loader'); location.appendChild(newLoadingWheel); } // Création du bouton qui affichera les résultats suivants function createShowMoreButton() { let showMoreButton = document.createElement('button'); showMoreButton.textContent = 'More results'; showMoreButton.classList.add('show-more-button'); // Lors du clique sur le nouveau bouton showMoreButton.addEventListener('click', (e) => { // Supression de ce dernier e.target.remove(); // Création du spinner de chargement createSpinnerLoader(resultsList); }) resultsList.appendChild(showMoreButton); } // Pour chaque nouvelle recherche formElt.addEventListener('submit', (e) => { // Empêche le comportement par défault de la soumission d'un formulaire e.preventDefault(); // Réinitialise le offset à zéro à chaque nouvelle recherche offset = 0; cumulOffset = 0; covers = 0; // Si l'utilisateur a rentré plusieurs mots, englobe la valeur de l'input entre guillemets, afin de filtrer plus précisément les résultats de la requête let findSpaceRegex = /\W/; let inputValue = findSpaceRegex.test(searchInputElt.value) ? '\"' + searchInputElt.value + '\"' : searchInputElt.value; // Si le champs de recherche n'est pas vide if (inputValue.length > 0) { // Si l'utilisateur a sélectionné un type de recherche if (selectSpanElt.hasAttribute('data-value')) { // Montre ou cache les éléments d'informations errorInfoElt.textContent = ''; resultCounterElt.style.display = 'block'; resultInfoElt.style.display = 'none'; // Vide 'resultList' a chaque soumission de formulaire pour afficher les nouveaux résultats de la requête while (resultsList.hasChildNodes()) { resultsList.firstChild.remove(); } // Création du loader de chargement createSpinnerLoader(resultsList); // Lancement de la requête searchRequest(parameter, encodeURIComponent(inputValue)); } else { errorInfoElt.textContent = 'Please select your type of search.'; } } else { errorInfoElt.textContent = 'Please enter something to search.'; } }) // GET Search Request : /<ENTITY_TYPE>?query=<QUERY>&limit=<LIMIT>&offset=<OFFSET> function searchRequest(parameter, value) { let request = new XMLHttpRequest(); // Construction de l'url en fonction de ce que recherche l'utilisateur let URL = selectSpanElt.getAttribute('data-value') !== 'all' ? `https://musicbrainz.org/ws/2/recording/?query=${parameter}:${value}&fmt=json&limit=50&offset=${offset}` : `https://musicbrainz.org/ws/2/recording/?query=release:${value}%20OR%20artist:${value}%20OR%20recording:${value}&fmt=json&limit=50&offset=${offset}`; // Lorsque l'état de chargement du protocole change request.addEventListener('readystatechange', () => { // Si l'opération de récupération est terminée if (request.readyState === XMLHttpRequest.DONE) { // Si la requête a été effectué avec succès if (request.status === 200) { // Suppression du loader de chargement s'il existe if (document.querySelector('.loader') !== null) { document.querySelector('.loader').remove(); } // Conversion des données JSON en données interprétables par le Javascript let response = JSON.parse(request.response); // Affiche le nombre de résultats trouvés let plurial = response.count > 1 ? 's' : ''; resultCounterElt.textContent = response.count + ' result' + plurial; // Si aucun résultat n'est trouvé if (response.count === 0) { // Affiche les infos a l'utilisateur resultInfoElt.style.display = 'block'; resultInfoElt.textContent = 'There is no result for your request.'; } else { // Si non lance la fonction createList pour chaque éléments du tableau recordings response.recordings.map((element, index) => { createList( response.offset + index + 1, limitCharacterLength(element['artist-credit'][0].name, 25), limitCharacterLength(element.title, 38), element.releases ? limitCharacterLength(element.releases[0].title, 38) : '', element.id ); }); // Incrémente le cumul cumulOffset += response.recordings.length; // S'il reste encore des résultat à afficher if (cumulOffset < response.count) { // Création d'un bouton pour afficher plus de résultats createShowMoreButton(); // Incrémentation de l'offset offset = response.offset + 50; // Lors du clique sur le bouton précedemment crée document.querySelector('.show-more-button').addEventListener('click', () => { // Laisse passer une seconde pour bien apercevoir le spinner setTimeout(() => { // Récursivité : envoie de la nouvelle requête pour récupérer les données suivantes searchRequest(parameter, value); }, 1000); }) } } } } }) request.open('GET', URL); request.send(); } // GET lookup Request : /<ENTITY_TYPE>/<MBID>?inc=<INC> function lookupRequest(mbid, callback) { let request = new XMLHttpRequest(); request.addEventListener('readystatechange', () => { if (request.readyState === XMLHttpRequest.DONE) { if (request.status === 200) { // Conversion des données JSON en données interprétables par le Javascript let response = JSON.parse(request.response); callback(response); } } }) request.open('GET', `https://musicbrainz.org/ws/2/recording/${mbid}?inc=artists+releases+ratings+release-groups+genres&fmt=json`); request.send(); } // Fonction de callback qui sera executée suite au succès de la lookup Request function printDataInModal(response) { modalInfoHeader.textContent = response['artist-credit'][0].name + ' - ' + response.title; modalInfoTitle.textContent = response.title; modalInfoArtist.textContent = response['artist-credit'][0].name; // Affichage de l'album const {releases} = response; let listAlbum = ''; if (releases.length > 0) { releases.map(element => { listAlbum += (releases.indexOf(element) === releases.length - 1) ? element.title : element.title.concat(' - '); }) } else { listAlbum = ' /'; } modalInfoAlbum.textContent = listAlbum; // Affichage du pays d'origine response.releases[0].country ? modalInfoCountry.textContent = response.releases[0].country : ' /'; // Affichage de la date response['first-release-date'] ? modalInfoYear.textContent = response['first-release-date'].slice(0, 4) : ' /'; // Affichage des genres s'ils sont renseignés let genres = ''; let dataGenres = response['artist-credit'][0].artist.genres; if (dataGenres.length > 0) { dataGenres.map((element) => { genres += (dataGenres.indexOf(element) === dataGenres.length - 1) ? element.name.charAt(0).toUpperCase() + element.name.slice(1) : element.name.charAt(0).toUpperCase() + element.name.slice(1).concat(', '); }) } else { genres = ' /'; } modalInfoGenre.textContent = genres; // Traitement et affichage de la durée modalInfoLength.textContent = response.length === null ? ' /' : convertLengthTitle(response.length); // Traitement des notes response.rating.value !== null ? ratingSystem(response.rating.value) : hideRatings(); // Récupération des id de tout les albums response.releases.map(album => { // Lancement de la requête pour récupérer les covers lookupRequestCover(album.id); }) setTimeout(() => { if (covers === 0) { coversZoneElt.textContent = 'Aucune pochette d\'album disponible.' } }, 5000); } // Transformation de la durée au format 'MM:SS' function convertLengthTitle(number) { // Convertion en minute de la durée exprimée en milliseconde let time = (Math.floor(number / 1000) / 60).toString(); // Trouve au moins un chiffre, puis un point, puis un ou plusieurs chiffres let regex = /^(\d{1,})\.(\d{1,})$/; // Regroupe minutes et secondes let groupMinutesSeconds = time.match(regex); // Récupération des minutes dans le tableau 'groupMinutesSeconds' let minutes = groupMinutesSeconds[1].padStart(2, '0'); // Traitement des secondes let seconds = (Math.round(number / 1000) % 60).toString().padStart(2, '0'); // Retourne l'affichage adéquat de la durée return minutes + ' : ' + seconds; } // Affichage dynamique des jaquettes d'album dans le DOM function printCovers(url) { if (url === undefined) { return; } else { let newCover = document.createElement('img'); newCover.src = url; newCover.alt = 'Album cover'; coversZoneElt.appendChild(newCover); covers++; } } // Fermeture de la fenêtre modale lors du clique sur le bouton prévu à cet effet closeModalButton.addEventListener('click', () => { modalElt.classList.remove('open'); scrollManager(); }) // GET Covers Request function lookupRequestCover(mbid) { let request = new XMLHttpRequest(); request.addEventListener('readystatechange', () => { if (request.readyState === XMLHttpRequest.DONE) { if (request.status === 200) { // Conversion des données JSON en données interprétables par le Javascript let response = JSON.parse(request.response); // Suppression du loader de chargement s'il existe if (document.querySelector('.loader') !== null) { document.querySelector('.loader').remove(); } // Pour chaque images présente dans le tableau response.images.map(item => { // Affiche l'image en question if (item.thumbnails['250']) { printCovers(item.thumbnails['250']); } else if (item.thumbnails.small) { printCovers(item.thumbnails.small); } else if (item.image) { printCovers(item.image); } }); } else { console.error('Aucune cover d\'album n\'a pu être trouvé avec cet mbid'); } } }); request.open('GET', `https://coverartarchive.org/release/${mbid}`); request.send(); } // Gestion des étoiles en fonction de la note function ratingSystem(rating) { const root = document.querySelector(':root'); let regex = /^(\d)\.(\d{1,})$/; // Affichage des étoiles starsRating.forEach(star => { star.style.display = 'block'; star.classList.remove('decimal'); }); // Si la note est un nombre entier if (!regex.test(rating)) { // Coloration des étoiles colorStars(rating); } else { // Séparation de l'entier et du décimal let ratingValues = rating.toString().match(regex); let integer = ratingValues[1]; let decimal = ratingValues[2]; // Coloration des étoiles pleines colorStars(integer); // Ajout de la classe 'décimal' sur l'étoile qui ne doit pas être remplie entièrement starsRating[integer].classList.add('decimal'); // Attribution de la largeur à coloriser let widthValue = decimal < 10 ? decimal * 10 : decimal; // Changement dynamique du remplissage de l'étoile root.style.setProperty('--pseudo-width', widthValue + '%'); } } // Remplissage des étoiles function colorStars(note) { starsRating.forEach((star, index) => { // Si l'unité de la note est supérieure ou égale à son étoile correspondante if (note >= index + 1) { // Coloration de l'étoile star.style.backgroundColor = '#ff4b23'; } }); } // Cache les étoiles si la note n'est pas définie function hideRatings() { starsRating.forEach(star => star.style.display = 'none'); }<file_sep>/README.md This application allows users to search for informations about music, by querying the MusicBrainz API. This is the validation project of the JavaScript module of the web developer training currently followed at CEFIM. The application is available online at this address https://vibesin.breyault.cefim.o2switch.site/ <file_sep>/js/scroll-top.js const btnScrollToTop = document.querySelector('#btn-scroll-top'); window.addEventListener('scroll', () => { btnScrollToTop.style.display = window.pageYOffset >= 1000 ? 'flex' : 'none'; }) btnScrollToTop.addEventListener('click', () => { window.scrollTo({ top: 0, left:0, behavior:"smooth" }); })
0ecec4f1ca02c0245f718a03940805ca9d45b0b0
[ "JavaScript", "Markdown" ]
3
JavaScript
davidbreyault/vibes-in
28d77258be5e06b1dec7821207de2c8d2dd7b1ad
97459e3c576048a4340914b095e89b7243a64d55
refs/heads/master
<repo_name>gulp-query/gulp-query-compress<file_sep>/readme.md ## gulp-query-compress Plugin for [gulp-query](https://github.com/gulp-query/gulp-query) Compress your images in other directory Uses [imagemin](https://www.npmjs.com/package/imagemin), [pngquant](https://www.npmjs.com/package/imagemin-pngquant) for PNG and [pngquant](https://www.npmjs.com/package/imagemin-mozjpeg) for JPEG This plugin provides automatic compress and copy. ``` npm install gulp-query gulp-query-compress ``` ### Example Paste the code into your `gulpfile.js` and configure it ```javascript let build = require('gulp-query') , compress = require('gulp-query-compress') ; build((query) => { query.plugins([compress]) // simple .compress('src/icons/*.png','images/') // multi .compress([ 'src/icons/*.png', {from:'src/bg/*',to: 'bg/'}, {from:'src/bg2/*',to: 'bg2/'} ], 'images/','admin') // multi and config .compress([ 'src/icons/*.png', {from:'src/bg/*',to: 'bg/'}, {from:'src/bg2/*',to: 'bg2/'} ], 'images/',{ png: { quality: '60-70', speed: 1 } }) // object .compress({ name: 'any', from: ['src/images/*.jpg'], to: 'images/', png: { quality: '60-70', speed: 1 }, jpeg: { quality: 60, } }) ; }); ``` And feel the freedom ``` gulp gulp --production // For production (minification) gulp watch // Watching change gulp compress // Only for compress gulp compress:admin // Only for task with name admin ... ``` ### Options ```javascript .compress({ name: "task_name", // For gulp js:task_name from: 'src/images/*.jpg', // ["src/images/*.jpg", "src/images2/*.jpg"] to: "images/", png: { quality: '60-70', speed: 1 }, jpeg: { quality: 60, } }) ```<file_sep>/index.js let Plugin = require('gulp-query').Plugin , glob = require('glob') , imagemin = require('gulp-imagemin') , gulp = require('gulp') , imageminPngquant = require('imagemin-pngquant') , imageminMozjpeg = require('imagemin-mozjpeg') ; class CompressPlugin extends Plugin { static method() { return 'compress'; } /** * * @param {GulpQuery} GulpQuery * @param configs */ constructor(GulpQuery, configs) { super(GulpQuery, configs); /** * @type {Object.<String,{from: Array, to: String, completeAmount: Number}>} * @private */ this._reportsOfCompress = {}; } watchFiles(config) { return []; } run(task_name, config, callback) { let from = config['from']; let path_to = this.path(config.to); let name = 'name' in config ? config['name'] : null; let parent_folder = 'parent_folder' in config ? config.parent_folder : null; if (!Array.isArray(from)) { from = [from]; } let imageminCfg = { png: { quality: '60-70', speed: 1 }, jpeg: { quality: 60, //targa: true } }; ['png', 'jpg'].forEach((c) => { if (!(c in config)) return; let _ci; for (_ci in imageminCfg[c]) { if (!imageminCfg[c].hasOwnProperty(_ci)) continue; if (_ci in config[c]) { imageminCfg[c][_ci] = config[c][_ci] } } }); let stream = []; let to, imagesList; from.forEach((f) => { if (typeof f === 'object') { from = this.path(parent_folder ? (parent_folder + f.from) : f.from); to = path_to + f.to; } else { from = this.path(parent_folder ? (parent_folder + f) : f); to = path_to; } imagesList = glob.sync(from); this._reportsOfCompress[from] = { from: imagesList, to: to, completeAmount: 0 }; stream.push(gulp.src(from) .pipe(imagemin([ imageminMozjpeg(imageminCfg.jpeg), imageminPngquant(imageminCfg.png) ])) .pipe(gulp.dest(to)) .pipe(this.notify(this.reportOfCompress.bind(this, task_name, from)))); }); return stream; } reportOfCompress(task_name, from) { if (!(from in this._reportsOfCompress)) { return; } ++this._reportsOfCompress[from].completeAmount; if (this._reportsOfCompress[from].completeAmount >= this._reportsOfCompress[from].from.length) { this.report( task_name, this._reportsOfCompress[from].from, this._reportsOfCompress[from].to, true ); delete this._reportsOfCompress[from]; } } } module.exports = CompressPlugin;
ec452571078f03ede5a1f7e8f5f3da82156ef436
[ "Markdown", "JavaScript" ]
2
Markdown
gulp-query/gulp-query-compress
95ad78f096c7a2f01e1759c36caf3542a2ebf779
d7db385f72afcb618dcd5303d07acebdb40e924a
refs/heads/master
<file_sep>// open_win function // INPUT: stringURL : the URL to open // winW : Width of window // winH : Height of window // OUTPUT: Will open a new browser window // with the strinURL location. // AUTHOR: dZ <<EMAIL>> function open_win(stringURL, winW, winH, winX, winY) { // Arbitrary "MAGIC" values have been restored. // It just works better this way, in every browser // -dZ. // BorderSize = 4; // 4px wide TitleBarIE = 14; // 14px per IE toolbar TitleBarNN = 20; // 20px per NN toolbar ToolBar = 'yes'; // Karen wants this StatBar = 'yes'; MenuBar = 'yes'; // and this... Sizable = 'yes'; if (!(winX && winY)) { winX = ((screen.width / 2) - (winW / 2)); winY = ((screen.height / 2) - (winH / 2)); } if (winW && winH) { ToolBar = 'no'; StatBar = 'no'; MenuBar = 'no'; Sizable = 'no'; } else { if ( is_IE() ) { winX = window.screenLeft - BorderSize; winX = (winX <= 0) ? 1 : (winX); // Don't ask me... THEY WORK! fuckit! winY = window.screenTop - (TitleBarIE * 7) - 1; winW = document.body.offsetWidth - BorderSize; winH = document.body.offsetHeight - TitleBarIE - BorderSize; } else { winX = window.screenX; winY = window.screenY + TitleBarNN + BorderSize - 1; winW = window.outerWidth - (BorderSize * 3); // Same here... oh well! winH = window.outerHeight - (TitleBarNN * 7) + BorderSize + 1; } } var win_args= "scrollbars"+ ",toolbar="+ToolBar+ ",status="+StatBar+ ",menubar="+MenuBar+ ",resizable="+Sizable+ ",location=no"+ ",width="+winW+ ",height="+winH+ ",left="+winX+ ",top="+winY+ ",screenX="+winX+ ",screenY="+winY; win_kid = window.open(stringURL, "winSpawnie", win_args); win_kid.opener = self; if (navigator.appName == 'Netscape') { win_kid.focus(); } } <file_sep><?php require_once "mserv.class.php"; require_once "config.inc.php"; require_once "misc.inc.php"; getHTMLHeader(); $ms = new MServ($g_host, $g_port, $g_user, $g_pass); if (!$ms->isServeronline()) { echo "Server not found !"; die; } echo "<PRE>\r\n"; $albumlist = explode ("<br>", $ms->getAlbumList("<br>")); foreach ($albumlist as $temp) { if (eregi("^([0-9]+)\t([^\t]+)\t(.*)", $temp, $regexp_res)) { echo " <a href=\"queue.php?p_album_nr=" . $regexp_res[1] . "&p_track_nr=\">[Q]</a>"; echo " <a href=\"queue.php?p_album_nr=" . $regexp_res[1] . "&p_track_nr=&p_random=1\">[Q R]</a>"; echo " RATE :"; echo " <a href=\"rate.php?p_album_nr=" . $regexp_res[1] . "&p_track_nr=&p_value=SUPERB\">[S]</a>"; echo " <a href=\"rate.php?p_album_nr=" . $regexp_res[1] . "&p_track_nr=&p_value=GOOD\">[G]</a>"; echo " <a href=\"rate.php?p_album_nr=" . $regexp_res[1] . "&p_track_nr=&p_value=NEUTRAL\">[N]</a>"; echo " <a href=\"rate.php?p_album_nr=" . $regexp_res[1] . "&p_track_nr=&p_value=BAD\">[B]</a>"; echo " <a href=\"rate.php?p_album_nr=" . $regexp_res[1] . "&p_track_nr=&p_value=AWFUL\">[A]</a>"; echo " $regexp_res[2] <a href=\"viewtracks.php?p_album_nr=" . $regexp_res[1] . "\">$regexp_res[3]</a>"; echo "<br>\r\n"; } } getHTMLFooter(); ?> <file_sep><?php include "db_inc.php"; $fh = fopen("http://cert.uni-stuttgart.de/ticker/news.php?count=800", "r"); if ($fh){ while (!feof ($fh)) { $buffer = fgets($fh, 4096); // echo $buffer; if (eregi("article.php\?mid\=([0-9]+)\"\>\[([^\/\Uu5D]+)\/(.+)\](.+)</a> \((.*)\)", $buffer, $regexp)) { echo $regexp[2] . "<br> \r\n"; echo $regexp[5] . " " . $regexp[4] . "<br> \r\n"; $mymain = explode(",", $regexp[2]); foreach ($mymain as $current_main) { if ($current_main == "MS") { $current_main = "Microsoft"; } $query = "REPLACE INTO cert_main_data (mid, main_text, main_desc, article_date) VALUES (" . $regexp[1] . " , '" . trim($current_main) . "' , '" . trim($regexp[4]) . "' , '" . $regexp[5] . "')"; echo $query; $result = mysql_query($query); } $myprods = explode(",", $regexp[3]); foreach ($myprods as $current_prod) { $query = "REPLACE INTO cert_prod_data (id_mid, prod_text) VALUES (" . $regexp[1] . " , '" . trim($current_prod) . "')"; $result = mysql_query($query); } } } } ?><file_sep><?php $g_user = "webuser"; $g_pass = "<PASSWORD>"; $g_host = "localhost"; $g_port = 4444; ?><file_sep><?php function getHTMLHeader() { for ($i = 0; $i < 400; $i++) { echo " "; } echo "\r\n"; echo "<span id=\"processing\">Updating ...</span>"; flush(); } function getHTMLFooter() { echo "<style type=\"text/css\"> \r\n"; echo "#processing { text-shadow:white; font-size:1pt; color:white; } \r\n"; echo "</style> \r\n"; echo "<script>processing.style.display='none'; \r\n"; echo "if(DHTML) { \r\n"; echo " setCont(\"id\",\"processing\",null,\"\"); \r\n"; echo " } \r\n"; echo " </script> \r\n"; } ?> <file_sep><?php require_once "telnet.class.php"; class MServ { // <EMAIL> 2001 var $error_result = "[] Command not understood"; var $tn_con = NULL; var $tn_host = NULL; var $tn_port = NULL; var $tn_user = NULL; var $tn_pass = NULL; function MServ($host,$port,$user,$pass) { $this->tn_host = $host; $this->tn_port = $port; $this->tn_user = $user; $this->tn_pass = $pass; } function isServeronline() { $fh = fsockopen($this->tn_host,$this->tn_port); if (!$fh) { return false; } fclose($fh); return true; } function close() { if ($this->tn_con) { $this->tn_con->close(); $this->sock = NULL; } } function connect() { $this->tn_con = new telnet($this->tn_host,$this->tn_port); $write_result = $this->tn_con->read_till("\r\n."); $this->tn_con->write("USER " . $this->tn_user . "\r\n"); $write_result = $this->tn_con->read_till("\r\n."); $this->tn_con->write("PASS " . $this->tn_pass . " <PASSWORD>"); $write_result = $this->tn_con->read_till("."); } function getInfo() { $this->connect(); // echo "connected <br>"; $this->tn_con->write("INFO\r\n"); $this->tn_con->write("error\r\n"); // echo "wrote info and error <br>"; $info_result = $this->tn_con->read_till($this->error_result); eregi("\[\]([^[]+)", $info_result, $return_res); $this->close(); return $return_res[1]; } function getAlbumList($separation_string) { $this->connect(); // echo "connected <br>"; $this->tn_con->write("ALBUMS\r\n"); $this->tn_con->write("error\r\n"); // echo "wrote info and error <br>"; $albums_result = $this->tn_con->read_till($this->error_result); $albums_result = str_replace ($this->error_result, "", $albums_result); $albums_result = str_replace ("\r\n", $separation_string, $albums_result); // $albums_result = str_replace ("[]", "", $albums_result); $this->close(); // echo $albums_result; return $albums_result; } function getTrackList($album_nr, $separation_string) { $this->connect(); // echo "connected <br>"; $this->tn_con->write("TRACKS " . $album_nr . "\r\n"); $this->tn_con->write("error\r\n"); // echo "wrote info and error <br>"; $tracks_result = $this->tn_con->read_till($this->error_result); $tracks_result = str_replace ($this->error_result, "", $tracks_result); $tracks_result = str_replace ("\r\n", $separation_string, $tracks_result); $tracks_result = str_replace ("[]", "", $tracks_result); $this->close(); return $tracks_result; } function Rate($album_nr, $track_nr, $rating) { // Keep Track Nr. empty if you want to rate the whole album // Keep Album and Track Nr. empty if you want to rate the current song. $this->connect(); // echo "connected <br>"; $this->tn_con->write("RATE " . $album_nr . " " . $track_nr . " " . $rating . "\r\n"); } function Queue($album_nr, $track_nr, $p_random = "") { // Keep Track Nr. empty if you want to rate the whole album // Keep Album and Track Nr. empty if you want to rate the current song. $this->connect(); // echo "connected <br>"; $s = "QUEUE " . $album_nr . " " . $track_nr; if ($p_random == "1") { $s .= " RANDOM "; } $this->tn_con->write($s . "\r\n"); } function getLevels() { $this->connect(); // echo "connected <br>"; $this->tn_con->write("VOLUME\r\n"); $this->tn_con->write("TREBLE\r\n"); $this->tn_con->write("BASS\r\n"); $this->tn_con->write("error\r\n"); // echo "wrote info and error <br>"; $levels_result = $this->tn_con->read_till($this->error_result); eregi("Volume is currently ([0-9]+)%", $levels_result, $regexp_res); $res_array['vol'] = $regexp_res[1]; eregi("Bass level is currently ([0-9]+)%", $levels_result, $regexp_res); $res_array['bas'] = $regexp_res[1]; eregi("Treble level is currently ([0-9]+)%", $levels_result, $regexp_res); $res_array['tre'] = $regexp_res[1]; return $res_array; } function setVolume($p_value) { $this->connect(); // echo "connected <br>"; $this->tn_con->write("VOLUME " . $p_value . "\r\n"); } function setBass($p_value) { $this->connect(); // echo "connected <br>"; $this->tn_con->write("BASS " . $p_value . "\r\n"); } function setTreble($p_value) { $this->connect(); // echo "connected <br>"; $this->tn_con->write("TREBLE " . $p_value . "\r\n"); } function getInfo($album_nr, $track_nr, $separation_string) { // Keep Track Nr. empty to get info about the whole album // Keep Album and Track Nr. empty to get info about the current song $this->connect(); // echo "connected <br>"; $this->tn_con->write("INFO $album_nr $track_nr \r\n"); $this->tn_con->write("error\r\n"); // echo "wrote info and error <br>"; $info_result = $this->tn_con->read_till($this->error_result); $info_result = str_replace ($this->error_result, "", $info_result); $info_result = str_replace ("\r\n", $separation_string, $info_result); $info_result = str_replace ("[]", "", $info_result); $this->close(); return $info_result; } function PlayControl($p_value) { $this->connect(); // echo "connected <br>"; $this->tn_con->write($p_value . "\r\n"); } } ?><file_sep><html> <head> <title> Cert - O - Matic -==- Info </title> </head> <link rel="stylesheet" href="style.css" type="text/css"> <body> <center> <?php echo "<h1> Articles for : \"" . $main_name . " / " . $prod_name . "\""; ?> <br><br> <table border="0" cellpadding="3" width="350"> <tr> <th> Cert-RUS Article (in german) </th> </tr> <?php include "db_inc.php"; $query = "SELECT md.mid, main_desc FROM cert_main_data md, cert_prod_data pd where pd.id_mid = md.mid and md.main_text = '$main_name' and pd.prod_text = '$prod_name' order by md.mid desc LIMIT 0, 20"; $result = mysql_query($query); while ($row = mysql_fetch_object($result)) { $cert_article_link = "http://cert.uni-stuttgart.de/ticker/article.php?mid=" . $row->mid; echo "<tr>\r\n"; echo " <td width=200 valign=\"top\" bgcolor=\"#CCCCCC\">\r\n"; echo " <a class=\"nobold\" href=\"" . $cert_article_link . "\" target=\"_blank\">$row->main_desc</a><br>\r\n"; echo " <a class=\"nobold\" href=\"http://translate.google.com/translate?hl=en&u=" . $cert_article_link . "\" target=\"_blank\">[ English / Google ] </a>\r\n"; echo " </td>\r\n"; echo "</tr>\r\n"; } $back_link = $HTTP_REFERER; ?> </table> <br> <?php echo "<a href=\"$back_link\">[ Back ]</a>"; ?> <a href="javascript:self.close();">[ Close this window ]</a> </body> </html> <file_sep>Nothing here in the moment Visit : http://www.ohardt.com<file_sep><?php require_once "mserv.class.php"; require_once "config.inc.php"; $ms = new MServ($g_host, $g_port, $g_user, $g_pass); $ms->Queue($p_album_nr, $p_track_nr) . "<BR>"; header ("Location: " . $HTTP_SERVER_VARS["HTTP_REFERER"]); ?><file_sep><script LANGUAGE="javascript"> <!-- function popup(path,x,y) { pop=window.open(path,'control','directories=0,location=0,menubar=0,resizable=0,scrollbars=0,status=0,toolbar=0,locationbar=0,width='+x+',height='+y+',innerwidth='+x+',innerheight='+y); pop.focus(); } //--> </script> <?php if (!isset($p_extra)) { $p_extra = "empty"; } if ($p_extra == "is_mini") { echo "<html><HEAD>\r\n"; echo "<title>Mini Control</title>\r\n"; echo "</HEAD>\r\n"; } require_once "mserv.class.php"; require_once "config.inc.php"; require_once "misc.inc.php"; getHTMLHeader(); $ms = new MServ($g_host, $g_port, $g_user, $g_pass); if (!$ms->isServeronline()) { echo "Server not found !"; die; } $res_test = $ms->getLevels(); echo "<PRE>"; echo "Volume : " . $res_test['vol'] . " <a href=\"level.php?p_action=vol&p_value=" . urlencode("+3") . "\">[+3]</a> <a href=\"level.php?p_action=vol&p_value=-3\">[-3]</a> "; echo "<a href=\"level.php?p_action=vol&p_value=0\">[00]</a>"; echo "<a href=\"level.php?p_action=vol&p_value=60\">[60]</a><br>"; echo "Bass : " . $res_test['bas'] . " <a href=\"level.php?p_action=bas&p_value=" . urlencode("+5") . "\">[+5]</a> <a href=\"level.php?p_action=bas&p_value=-5\">[-5]</a> <br>"; echo "Treble : " . $res_test['tre'] . " <a href=\"level.php?p_action=tre&p_value=" . urlencode("+5") . "\">[+5]</a> <a href=\"level.php?p_action=tre&p_value=-5\">[-5]</a> <br>"; echo "<a href=\"playcontrol.php?p_action=PLAY\">[PLAY]</a> "; echo "<a href=\"playcontrol.php?p_action=PAUSE\">[PAUSE] </a>"; echo "<a href=\"playcontrol.php?p_action=STOP\">[STOP] </a>"; echo "<a href=\"playcontrol.php?p_action=NEXT\">[NEXT]</a>"; echo "<br>"; echo "Rate :"; echo " <a href=\"rate.php?p_album_nr=&p_track_nr=&p_value=SUPERB\">[S]</a>"; echo " <a href=\"rate.php?p_album_nr=&p_track_nr=&p_value=GOOD\">[G]</a>"; echo " <a href=\"rate.php?p_album_nr=&p_track_nr=&p_value=NEUTRAL\">[N]</a>"; echo " <a href=\"rate.php?p_album_nr=&p_track_nr=&p_value=BAD\">[B]</a>"; echo " <a href=\"rate.php?p_album_nr=&p_track_nr=&p_value=AWFUL\">[A]</a>"; echo "<br>"; if ($p_extra != "is_mini") { echo "<a href=\"javascript:popup('playbar.php?p_extra=is_mini', 260, 130)\">Mini Control</a>"; } echo "</PRE>"; getHTMLFooter(); ?> <file_sep><?php require_once "mserv.class.php"; require_once "config.inc.php"; $ms = new MServ($g_host, $g_port, $g_user, $g_pass); if ($p_action == "vol") { $ms->setVolume($p_value); } if ($p_action == "bas") { $ms->setBass($p_value); } if ($p_action == "tre") { $ms->setTreble($p_value); } header ("Location: " . $HTTP_SERVER_VARS["HTTP_REFERER"]); ?><file_sep><html> <head> <title> Cert - O - Matic -==- Info </title> </head> <link rel="stylesheet" href="style.css" type="text/css"> <body> <center> <?php echo "<h1> Info for : \"" . $main_name . "\""; ?> <br><br> <table border="0" cellpadding="3" width="350"> <tr> <th> Product / Category </th> <th> Nr. of Bugs </th> </tr> <?php include "db_inc.php"; $query = "SELECT prod_text, count(*) as NrodProdBugs, DATE_FORMAT(max(article_date), '%d %M %Y') as date_formated FROM cert_main_data md, cert_prod_data pd where pd.id_mid = md.mid and md.main_text = '$main_name' group by pd.prod_text order by NrodProdBugs desc LIMIT 0, 20"; $result = mysql_query($query); while ($row = mysql_fetch_object($result)) { echo "<tr>"; echo " <td width=200 valign=\"top\" bgcolor=\"#CCCCCC\">"; echo " <a href=\"cert_article.php?main_name=" . $main_name . "&prod_name=" . $row->prod_text . "\">" . $row->prod_text . "</a>"; if ($row->date_formated == $p_lastupdate) { echo "<img src=new.gif>"; } echo " </td>"; echo " <td align=\"right\" valign=\"top\" bgcolor=\"#CCCCCC\">" . $row->NrodProdBugs . "</td>"; echo "</tr>"; } ?> </table> <br> <a href="javascript:self.close();">[ Close this window ]</a> </body> </html> <file_sep><html> <head> <title> Cert - O - Matic -==- Automated RUS-CERT bug checker </title> </head> <link rel="stylesheet" href="style.css" type="text/css"> <script LANGUAGE="JavaScript" src="js-lib.js"></SCRIPT> <body> <center> <h1> Cert - O - Matic </h1> <h3> An automated RUS-CERT bug checker </h3> <br> <table border="0" cellpadding="3" width=400> <tr> <th> Company / Organization </th> <th width=100> Nr. of Bugs </th> </tr> <?php include "db_inc.php"; $total_width = 150; $query = "SELECT count(*), DATE_FORMAT(max(article_date), '%d %M %Y') as date_formated FROM cert_main_data"; $result = mysql_query($query); $MaxNrofBugs = mysql_fetch_array($result); $LastUpdate = $MaxNrofBugs[1]; $LastUpdateParam = "&p_lastupdate=" . $LastUpdate; $MaxNrofBugs = $MaxNrofBugs[0]; $query = "SELECT main_text, DATE_FORMAT(max(article_date), '%d %M %Y') as date_formated, count(*) as NrofBugs FROM cert_main_data GROUP BY main_text ORDER BY NrofBugs desc, article_date desc LIMIT 0,12"; $result = mysql_query($query); while ($row = mysql_fetch_object($result)) { echo "<tr>"; echo " <td width=200 valign=\"top\" bgcolor=\"#CCCCCC\">"; echo "<a class=nobold href=\"javascript:top.open_win('prod_stats.php?main_name=" . $row->main_text . $LastUpdateParam . "', 400, 350, 100, 100);\">" . $row->main_text . "</a>"; // if ($row->date_formated == $LastUpdate) { // echo "<img src=new.gif>"; // } echo " \r\n <br> \r\n"; $myWidth = round ((($row->NrofBugs / $MaxNrofBugs) * $total_width) , 0); echo "<img src=tiny_red.png width=\"$myWidth\" height=4>"; $myWidth = $total_width - $myWidth; echo "<img src=tiny_green.png width=\"$myWidth\" height=4> <span class=tiny> (" . round (($row->NrofBugs / $MaxNrofBugs)*100, 0) . "%)</span>"; echo "</td>"; echo " <td align=\"right\" valign=\"top\" bgcolor=\"#CCCCCC\">" . $row->NrofBugs . "</td>\r\n"; echo "</tr>"; } echo "</table>"; echo "<span class=tiny>Last Change : $LastUpdate </span>"; ?> <br><br> <a href="http://www.ohardt.com">More Java / PHP source code and tools</a><br><br> Data courtesy of <a href="http://cert.uni-stuttgart.de">RUS-CERT</a> </center> </body> </html> <file_sep><?php require_once "mserv.class.php"; require_once "config.inc.php"; $ms = new MServ($g_host, $g_port, $g_user, $g_pass); $ms->PlayControl($p_action); header ("Location: " . $HTTP_SERVER_VARS["HTTP_REFERER"]); ?><file_sep><?php $link = mysql_connect("localhost", "root", "dbpw") or die("DB error, please try later"); mysql_select_db("prog_db") or die("DB error, please try later"); ?><file_sep><?php require_once "mserv.class.php"; require_once "config.inc.php"; $ms = new MServ($g_host, $g_port, $g_user, $g_pass); getHTMLHeader(); echo "<a href=\"" . $HTTP_REFERER . "\">[Back]</a><br><br>\r\n"; echo "<PRE>"; $albumlist = explode ("<br>", $ms->getTrackList($p_album_nr, "<br>")); foreach ($albumlist as $test) { // echo $test . "<br>"; if (eregi($p_album_nr . "\t([0-9]+)\t([^\t]+)\t([^\t]+)\t([^\t]+)\t([0-9]+\:[0-9]+)", $test, $regexp_res)) { $track_number = $regexp_res[1]; $padded_track_number = $track_number; while (strlen($padded_track_number) < 3) { $padded_track_number = " " . $padded_track_number; } $track_author = $regexp_res[2]; $track_title = $regexp_res[3]; $track_rating = substr($regexp_res[4], 0, 1); $track_time = $regexp_res[5]; echo "$padded_track_number [$track_rating] $track_author <a href=\"trackinfo.php?p_album_nr=$p_album_nr&p_track_nr=" . $track_number . "\">$track_title</a> - $track_time"; echo " RATE : <a href=\"rate.php?p_album_nr=$p_album_nr&p_track_nr=" . $track_number . "&p_value=SUPERB\">SUPERB</a>"; echo " <a href=\"rate.php?p_album_nr=$p_album_nr&p_track_nr=" . $track_number . "&p_value=GOOD\">GOOD</a>"; echo " <a href=\"rate.php?p_album_nr=$p_album_nr&p_track_nr=" . $track_number . "&p_value=NEUTRAL\">NEUTRAL</a>"; echo " <a href=\"rate.php?p_album_nr=$p_album_nr&p_track_nr=" . $track_number . "&p_value=BAD\">BAD</a>"; echo " <a href=\"rate.php?p_album_nr=$p_album_nr&p_track_nr=" . $track_number . "&p_value=AWFUL\">AWFUL</a>"; echo "<br>\r\n"; } } getHTMLFooter(); ?><file_sep>PHP MServ Web Frontend v.0.1 같같같같같같같같같같같같같같 What is this ?? ~~~~~~~~~~~~~~~ This is a web frontend for the (very nice) mserv program, a program which turns your linux server into a mp3 juke box with plenty of features. You can get it at http://www.mserv.org Install ~~~~~~~ To install, extract all files into a directory and change the settings in "config.inc.php" according to our needs. Start with "start.php" or rename it to "index.php" Be sure to have mserv running (adjust the host and port settings int the config file if necessary). What is left to do ? ~~~~~~~~~~~~~~~~~~~~ - (much) better error checking - design - some functions not implemented yet Misc. ~~~~~ You can always get the latest version of this nice frontend at http://www.ohardt.com in the "Computer / Development" section. <file_sep><?php require_once "mserv.class.php"; require_once "config.inc.php"; $ms = new MServ($g_host, $g_port, $g_user, $g_pass); echo "<a href=\"" . $HTTP_REFERER . "\">[Back]</a><br><br>\r\n"; echo "<PRE>"; echo "INFO : " . $ms->getInfo($p_album_nr, $p_track_nr, "<br>") . "<BR>"; ?>
47cedc1db11f397c38ee78b853e49ff7d79cd6ad
[ "JavaScript", "Text", "PHP" ]
18
JavaScript
BackupTheBerlios/mserv-control
c5ccfb5dd139948780721268ae0c16473b409cb3
2b54392aa5bcfb545299fd73a850ddeaf9b6a304
refs/heads/master
<repo_name>andrewmk/ntplib<file_sep>/untplib-client.py import untplib c=untplib.NTPClient() resp=c.request('0.uk.pool.ntp.org', version=3, port=123) print("Offset is ", resp.offset) from machine import RTC import time rtc = RTC() print("Adjusting clock by ", resp.offset, "seconds") rtc.init(time.localtime(time.time() + resp.offset))
2dfcce05cef6ac7ecef71acab6be6ee6757dff75
[ "Python" ]
1
Python
andrewmk/ntplib
db67b8df09946c46a1b4b0edcc2d0aab96fcac8d
8036da7b6de0bfe81a7ebe0612cbeb45bd5d9f1e
refs/heads/master
<file_sep>#pragma once #ifdef POLYGON2D_PLATFORM_WINDOWS #ifdef POLYGON2D_BUILD_DLL #define POLYGON2D_API __declspec(dllexport) #else #define POLYGON2D_API __declspec(dllimport) #endif // POLYGON2D_BUILD_DLL #else #error Polygon2D is only supported on Windows. #endif // POLYGON2D_PLATFORM_WINDOWS <file_sep>#pragma once #include <memory> #include "Core.h" #include "spdlog/spdlog.h" namespace Polygon2D { class POLYGON2D_API Log { public: Log(); ~Log(); static void Init(); inline static std::shared_ptr<spdlog::logger>& GetCoreLogger() { return s_CoreLogger; } inline static std::shared_ptr<spdlog::logger>& GetClientLogger() { return s_ClientLogger; } private: static std::shared_ptr<spdlog::logger> s_CoreLogger; static std::shared_ptr<spdlog::logger> s_ClientLogger; }; } // Core log macros #define POLYGON2D_CORE_TRACE(...) ::Polygon2D::Log::GetCoreLogger()->trace(__VA_ARGS__) #define POLYGON2D_CORE_INFO(...) ::Polygon2D::Log::GetCoreLogger()->info(__VA_ARGS__) #define POLYGON2D_CORE_WARN(...) ::Polygon2D::Log::GetCoreLogger()->warn(__VA_ARGS__) #define POLYGON2D_CORE_ERROR(...) ::Polygon2D::Log::GetCoreLogger()->error(__VA_ARGS__) #define POLYGON2D_CORE_FATAL(...) ::Polygon2D::Log::GetCoreLogger()->fatal(__VA_ARGS__) // Client log macros #define POLYGON2D_TRACE(...) ::Polygon2D::Log::GetClientLogger()->trace(__VA_ARGS__) #define POLYGON2D_INFO(...) ::Polygon2D::Log::GetClientLogger()->info(__VA_ARGS__) #define POLYGON2D_WARN(...) ::Polygon2D::Log::GetClientLogger()->warn(__VA_ARGS__) #define POLYGON2D_ERROR(...) ::Polygon2D::Log::GetClientLogger()->error(__VA_ARGS__) #define POLYGON2D_FATAL(...) ::Polygon2D::Log::GetClientLogger()->fatal(__VA_ARGS__)<file_sep>#pragma once #ifdef POLYGON2D_PLATFORM_WINDOWS extern Polygon2D::Application* Polygon2D::CreateApplication(); int main(int argc, const char** argv) { Polygon2D::Log::Init(); POLYGON2D_CORE_WARN("Initialized Log!"); int a = 5; POLYGON2D_INFO("Hello! Var={0}", a); auto app = Polygon2D::CreateApplication(); app->Run(); delete app; } #endif // POLYGON2D_PLATFORM_WINDOWS <file_sep>#pragma once // For use by Polygon2D applications // Application #include "Polygon2D/Application.h" // Log #include "Polygon2D/Log.h" // EntryPoint #include "Polygon2D/EntryPoint.h"<file_sep># Polygon2D Polygon2D Game Engine <file_sep>#include <Polygon2D.h> class Sandbox : public Polygon2D::Application { public: Sandbox() { } ~Sandbox() { } }; Polygon2D::Application* Polygon2D::CreateApplication() { return new Sandbox(); }
5c70fd55bf46cdc2daf67dd1cdd6a6acd43993a3
[ "Markdown", "C", "C++" ]
6
C
svecko/Polygon2D
b12796bff8ea7e8a98a96a14762d37de6611c0d6
97678746a052b78f61d57dd28d7b8705fcbb7103
refs/heads/main
<repo_name>jeremgms/SymForm<file_sep>/readme.md # SymForm Projet à vocation pédagogique : Génération d'un site statique avec un Backend Notion pour la chaine YouTube [YoanDev](https://www.youtube.com/c/yoandevco) ## 👾 Environnement de développement ### 🏁 Pré-requis * [Symfony CLI](https://symfony.com/download) * [PHP 7.4](https://www.php.net/downloads) * [Composer](https://getcomposer.org/) ### 🔥 Installer le projet en local ```bash composer install symfony serve -d ``` ### ✅ Lancer la génération du site statique ```bash bin/console dump-static-site php -S localhost:8080 -t output ```<file_sep>/src/Service/StaticDumperService.php <?php namespace App\Service; use App\Controller\BlogController; use App\Controller\HomeController; use Symplify\SymfonyStaticDumper\Contract\ControllerWithDataProviderInterface; final class StaticDumperService implements ControllerWithDataProviderInterface { private $notionService; public function __construct(NotionService $notionService) { $this->notionService = $notionService; } public function getControllerClass(): string { return HomeController::class; } public function getControllerMethod(): string { return '__invoke'; } /** * @return string[] */ public function getArguments(): array { $id = []; foreach ($this->notionService->getAll() as $formation) { $id[] = $formation['id']; } return $id; } }
9c8063f0a7217ec84509135ec43a3e01aa5645dc
[ "Markdown", "PHP" ]
2
Markdown
jeremgms/SymForm
b97a3b0309fceb4da3aa7ba9a7fea548399a2f51
9285651b3942c8f20d33e7df4276e7b7753c964c
refs/heads/master
<repo_name>maxlengdell/Visualizing-Sorting-Algorithms<file_sep>/README.md ## MergeSort visualized ![alt text](https://github.com/maxlengdell/Visualizing-Sorting-Algorithms/blob/master/MergeSort.gif "MergeSort Gif") <file_sep>/QuickSort/PyVisualQuickSort.py import pygame import random pygame.font.init() screen = pygame.display.set_mode((900, 650)) array = [0]*150 arr_clr = [('red')]*150 Color_line = (255,0,0); #red clr =[(0, 204, 102), (255, 0, 0), (0, 0, 153), (255, 102, 0)] def generate(): for i in range(1, len(array)): arr_clr[i] = (255,0,0) array[i] = random.randrange(1,300) print(array) def drawLine(num,x,y): pygame.draw.line(screen,Color_line, (x,y),(x,y+num)) def drawArray(): x = 100 y = 0 for i in array: drawLine(i,x,y) x += 5 pygame.display.flip() def update(): screen.fill((255,255,255)) drawArray() pygame.display.update() pygame.event.pump() pygame.time.delay(50) def partition(arr, low, high): pivot = arr[high] i = low-1 for j in range(low,high): if(arr[j] < pivot): #swap i+=1 update() swap(arr,i,j) swap(arr, i+1,high) update() pygame.event.pump() return i + 1 def quickSort(arr, low, high): if(low < high): pi = partition(arr,low,high) quickSort(arr,low, pi-1) quickSort(arr, pi+1, high) def swap(arr,i,j): temp = arr[j] arr[j] = arr[i] arr[i] = temp generate() running = True while running: for event in pygame.event.get(): quickSort(array, 0, len(array) - 1) if event.type == pygame.quit(): running = False pygame.quit() quit() else: quickSort(array, 0, len(array) - 1) if event.type == pygame.K_RETURN: print("run") update() pygame.display.update() # def main(): # print("main run") # global running # running = True # generate() # while running: # for event in pygame.event.get(): # if event.type == pygame.quit(): # running = False # pygame.quit() # quit() # if event.type == pygame.K_RETURN: # print("return") # # update() # pygame.display.update() # # if __name__== "__main__": # main() # <file_sep>/MergeSort/PyVisual.py import pygame import random pygame.font.init() screen = pygame.display.set_mode((900, 650)) width = 1000 length = 700 array = [0]*150 arr_clr = [('red')]*150 Color_line = (255,0,0); #red clr =[(0, 204, 102), (255, 0, 0), (0, 0, 153), (255, 102, 0)] def generate(): for i in range(1, len(array)): arr_clr[i] = (255,0,0) array[i] = random.randrange(1,300) print(array) def drawLine(num,x,y): pygame.draw.line(screen,Color_line, (x,y),(x,y+num)) def drawArray(): x = 100 y = 0 for i in array: drawLine(i,x,y) x += 5 pygame.display.flip() def update(): screen.fill((255,255,255)) drawArray() pygame.display.update() pygame.time.delay(5) def mergeSort(arr,l,r): if l < r: # Same as (l+r)//2, but avoids overflow for # large l and h m = (l + (r - 1)) // 2 # Sort first and second halves mergeSort(arr, l, m) mergeSort(arr, m + 1, r) merge(arr, l, m, r) def merge(arr,l,mid,r): n1 = mid - l + 1 n2 = r - mid # create temp arrays left = [0] * (n1) right = [0] * (n2) # Copy data to temp arrays L[] and R[] for i in range(0, n1): left[i] = arr[l + i] for j in range(0, n2): right[j] = arr[mid + 1 + j] # Merge the temp arrays back into arr[l..r] i = 0 # Initial index of first subarray j = 0 # Initial index of second subarray k = l # Initial index of merged subarray pygame.event.pump() while i < n1 and j < n2: arr_clr[i] = clr[1] arr_clr[j] = clr[1] update() arr_clr[i] = clr[0] arr_clr[j] = clr[0] if left[i] <= right[j]: arr[k] = left[i] i += 1 else: arr[k] = right[j] j += 1 k += 1 # Copy the remaining elements of L[], if there # are any while i < n1: arr[k] = left[i] update() i += 1 k += 1 # Copy the remaining elements of R[], if there # are any while j < n2: arr[k] = right[j] update() j += 1 k += 1 def main(): print("main run") global running running = True generate() while running: (mergeSort(array,0,len(array)-1)) for event in pygame.event.get(): if event.type == pygame.quit(): running = False pygame.quit() quit() if event.type == pygame.K_RETURN: print("return") update() pygame.display.update() if __name__== "__main__": main()
c9c9f96b97402ca6bc80ef0276202d27859f6bc5
[ "Markdown", "Python" ]
3
Markdown
maxlengdell/Visualizing-Sorting-Algorithms
35c92d56faabd126a23d80d002c974dfbfb4ea2b
a8e49125a02481e7bbfc6391169734742fdea1fc